cloud: Replace use of aliased exceptions

Change-Id: I273e7554af766b15deb5ac8f38a6793b119a3bb9
Signed-off-by: Stephen Finucane <stephenfin@redhat.com>
This commit is contained in:
Stephen Finucane 2023-08-31 14:27:00 +01:00
parent e2940efea6
commit 621b561c6c
86 changed files with 961 additions and 839 deletions

View File

@ -17,7 +17,7 @@ import warnings
import jsonpatch import jsonpatch
from openstack.baremetal.v1._proxy import Proxy from openstack.baremetal.v1._proxy import Proxy
from openstack.cloud import exc from openstack import exceptions
from openstack import warnings as os_warnings from openstack import warnings as os_warnings
@ -86,7 +86,7 @@ class BaremetalCloudMixin:
""" """
try: try:
return self.baremetal.find_node(name_or_id, ignore_missing=False) return self.baremetal.find_node(name_or_id, ignore_missing=False)
except exc.OpenStackCloudResourceNotFound: except exceptions.NotFoundException:
return None return None
def get_machine_by_mac(self, mac): def get_machine_by_mac(self, mac):
@ -130,7 +130,7 @@ class BaremetalCloudMixin:
# we need to move the machine back to manageable first. # we need to move the machine back to manageable first.
if node.provision_state == 'available': if node.provision_state == 'available':
if node.instance_id: if node.instance_id:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Refusing to inspect available machine %(node)s " "Refusing to inspect available machine %(node)s "
"which is associated with an instance " "which is associated with an instance "
"(instance_uuid %(inst)s)" "(instance_uuid %(inst)s)"
@ -146,7 +146,7 @@ class BaremetalCloudMixin:
) )
if node.provision_state not in ('manageable', 'inspect failed'): if node.provision_state not in ('manageable', 'inspect failed'):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Machine %(node)s must be in 'manageable', 'inspect failed' " "Machine %(node)s must be in 'manageable', 'inspect failed' "
"or 'available' provision state to start inspection, the " "or 'available' provision state to start inspection, the "
"current state is %(state)s" "current state is %(state)s"
@ -215,29 +215,24 @@ class BaremetalCloudMixin:
] ]
Alternatively, you can provide an array of MAC addresses. Alternatively, you can provide an array of MAC addresses.
:param wait: Boolean value, defaulting to false, to wait for the node :param wait: Boolean value, defaulting to false, to wait for the node
to reach the available state where the node can be provisioned. It to reach the available state where the node can be provisioned. It
must be noted, when set to false, the method will still wait for must be noted, when set to false, the method will still wait for
locks to clear before sending the next required command. locks to clear before sending the next required command.
:param timeout: Integer value, defautling to 3600 seconds, for the wait :param timeout: Integer value, defautling to 3600 seconds, for the wait
state to reach completion. state to reach completion.
:param lock_timeout: Integer value, defaulting to 600 seconds, for :param lock_timeout: Integer value, defaulting to 600 seconds, for
locks to clear. locks to clear.
:param provision_state: The expected provision state, one of "enroll" :param provision_state: The expected provision state, one of "enroll"
"manageable" or "available". Using "available" results in automated "manageable" or "available". Using "available" results in automated
cleaning. cleaning.
:param kwargs: Key value pairs to be passed to the Ironic API, :param kwargs: Key value pairs to be passed to the Ironic API,
including uuid, name, chassis_uuid, driver_info, properties. including uuid, name, chassis_uuid, driver_info, properties.
:raises: OpenStackCloudException on operation error.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
:returns: Current state of the node. :returns: Current state of the node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if provision_state not in ('enroll', 'manageable', 'available'): if provision_state not in ('enroll', 'manageable', 'available'):
raise ValueError( raise ValueError(
@ -301,14 +296,13 @@ class BaremetalCloudMixin:
:param nics: An array of strings that consist of MAC addresses :param nics: An array of strings that consist of MAC addresses
to be removed. to be removed.
:param string uuid: The UUID of the node to be deleted. :param string uuid: The UUID of the node to be deleted.
:param wait: DEPRECATED, do not use. :param wait: DEPRECATED, do not use.
:param timeout: Integer value, representing seconds with a default :param timeout: Integer value, representing seconds with a default
value of 600, which controls the maximum amount of time to block value of 600, which controls the maximum amount of time to block
until a lock is released on machine. until a lock is released on machine.
:raises: OpenStackCloudException on operation failure. :raises: :class:`~openstack.exceptions.SDKException` on operation
failure.
""" """
if wait is not None: if wait is not None:
warnings.warn( warnings.warn(
@ -319,7 +313,7 @@ class BaremetalCloudMixin:
machine = self.get_machine(uuid) machine = self.get_machine(uuid)
invalid_states = ['active', 'cleaning', 'clean wait', 'clean failed'] invalid_states = ['active', 'cleaning', 'clean wait', 'clean failed']
if machine['provision_state'] in invalid_states: if machine['provision_state'] in invalid_states:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Error unregistering node '%s' due to current provision " "Error unregistering node '%s' due to current provision "
"state '%s'" % (uuid, machine['provision_state']) "state '%s'" % (uuid, machine['provision_state'])
) )
@ -330,8 +324,8 @@ class BaremetalCloudMixin:
# failure, and resubitted the request in python-ironicclient. # failure, and resubitted the request in python-ironicclient.
try: try:
self.baremetal.wait_for_node_reservation(machine, timeout) self.baremetal.wait_for_node_reservation(machine, timeout)
except exc.OpenStackCloudException as e: except exceptions.SDKException as e:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Error unregistering node '%s': Exception occured while" "Error unregistering node '%s': Exception occured while"
" waiting to be able to proceed: %s" % (machine['uuid'], e) " waiting to be able to proceed: %s" % (machine['uuid'], e)
) )
@ -375,10 +369,10 @@ class BaremetalCloudMixin:
'value': 'administrator' 'value': 'administrator'
}) })
:raises: OpenStackCloudException on operation error.
:returns: Current state of the node. :returns: Current state of the node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`. :rtype: :class:`~openstack.baremetal.v1.node.Node`.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return self.baremetal.patch_node(name_or_id, patch) return self.baremetal.patch_node(name_or_id, patch)
@ -391,16 +385,16 @@ class BaremetalCloudMixin:
:param string name_or_id: A machine name or UUID to be updated. :param string name_or_id: A machine name or UUID to be updated.
:param attrs: Attributes to updated on the machine. :param attrs: Attributes to updated on the machine.
:raises: OpenStackCloudException on operation error.
:returns: Dictionary containing a machine sub-dictonary consisting :returns: Dictionary containing a machine sub-dictonary consisting
of the updated data returned from the API update operation, and a of the updated data returned from the API update operation, and a
list named changes which contains all of the API paths that list named changes which contains all of the API paths that
received updates. received updates.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
machine = self.get_machine(name_or_id) machine = self.get_machine(name_or_id)
if not machine: if not machine:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Machine update failed to find Machine: %s. " % name_or_id "Machine update failed to find Machine: %s. " % name_or_id
) )
@ -411,7 +405,7 @@ class BaremetalCloudMixin:
machine._to_munch(), new_config machine._to_munch(), new_config
) )
except Exception as e: except Exception as e:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Machine update failed - Error generating JSON patch object " "Machine update failed - Error generating JSON patch object "
"for submission to the API. Machine: %s Error: %s" "for submission to the API. Machine: %s Error: %s"
% (name_or_id, e) % (name_or_id, e)
@ -504,10 +498,10 @@ class BaremetalCloudMixin:
representing the amount of time to wait for the desire end state to representing the amount of time to wait for the desire end state to
be reached. be reached.
:raises: OpenStackCloudException on operation error.
:returns: Current state of the machine upon exit of the method. :returns: Current state of the machine upon exit of the method.
:rtype: :class:`~openstack.baremetal.v1.node.Node`. :rtype: :class:`~openstack.baremetal.v1.node.Node`.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
node = self.baremetal.set_node_provision_state( node = self.baremetal.set_node_provision_state(
name_or_id, name_or_id,
@ -534,9 +528,9 @@ class BaremetalCloudMixin:
the baremetal API to allow for notation as to why the node is in the baremetal API to allow for notation as to why the node is in
maintenance state. maintenance state.
:raises: OpenStackCloudException on operation error.
:returns: None :returns: None
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if state: if state:
self.baremetal.set_node_maintenance(name_or_id, reason) self.baremetal.set_node_maintenance(name_or_id, reason)
@ -554,9 +548,9 @@ class BaremetalCloudMixin:
:param string name_or_id: The Name or UUID value representing the :param string name_or_id: The Name or UUID value representing the
baremetal node. baremetal node.
:raises: OpenStackCloudException on operation error.
:returns: None :returns: None
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.baremetal.unset_node_maintenance(name_or_id) self.baremetal.unset_node_maintenance(name_or_id)
@ -568,9 +562,9 @@ class BaremetalCloudMixin:
:params string name_or_id: A string representing the baremetal :params string name_or_id: A string representing the baremetal
node to have power turned to an "on" state. node to have power turned to an "on" state.
:raises: OpenStackCloudException on operation error.
:returns: None :returns: None
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.baremetal.set_node_power_state(name_or_id, 'power on') self.baremetal.set_node_power_state(name_or_id, 'power on')
@ -582,9 +576,9 @@ class BaremetalCloudMixin:
:params string name_or_id: A string representing the baremetal :params string name_or_id: A string representing the baremetal
node to have power turned to an "off" state. node to have power turned to an "off" state.
:raises: OpenStackCloudException on operation error. :returns: None
:raises: :class:`~openstack.exceptions.SDKException` on operation
:returns: error.
""" """
self.baremetal.set_node_power_state(name_or_id, 'power off') self.baremetal.set_node_power_state(name_or_id, 'power off')
@ -598,9 +592,9 @@ class BaremetalCloudMixin:
:params string name_or_id: A string representing the baremetal :params string name_or_id: A string representing the baremetal
node to have power turned to an "off" state. node to have power turned to an "off" state.
:raises: OpenStackCloudException on operation error.
:returns: None :returns: None
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.baremetal.set_node_power_state(name_or_id, 'rebooting') self.baremetal.set_node_power_state(name_or_id, 'rebooting')
@ -637,7 +631,8 @@ class BaremetalCloudMixin:
DEPRECATED, use ``wait_for_node_reservation`` on the `baremetal` proxy. DEPRECATED, use ``wait_for_node_reservation`` on the `baremetal` proxy.
:raises: OpenStackCloudException upon client failure. :raises: :class:`~openstack.exceptions.SDKException` upon client
failure.
:returns: None :returns: None
""" """
warnings.warn( warnings.warn(

View File

@ -15,7 +15,6 @@ import warnings
from openstack.block_storage.v3._proxy import Proxy from openstack.block_storage.v3._proxy import Proxy
from openstack.block_storage.v3 import quota_set as _qs from openstack.block_storage.v3 import quota_set as _qs
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc
from openstack import exceptions from openstack import exceptions
from openstack import warnings as os_warnings from openstack import warnings as os_warnings
@ -134,9 +133,12 @@ class BlockStorageCloudMixin:
:param bootable: (optional) Make this volume bootable. If set, wait :param bootable: (optional) Make this volume bootable. If set, wait
will also be set to true. will also be set to true.
:param kwargs: Keyword arguments as expected for cinder client. :param kwargs: Keyword arguments as expected for cinder client.
:returns: The created volume ``Volume`` object. :returns: The created volume ``Volume`` object.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if bootable is not None: if bootable is not None:
wait = True wait = True
@ -144,7 +146,7 @@ class BlockStorageCloudMixin:
if image: if image:
image_obj = self.get_image(image) image_obj = self.get_image(image)
if not image_obj: if not image_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Image {image} was requested as the basis for a new" "Image {image} was requested as the basis for a new"
" volume, but was not found on the cloud".format( " volume, but was not found on the cloud".format(
image=image image=image
@ -157,7 +159,7 @@ class BlockStorageCloudMixin:
volume = self.block_storage.create_volume(**kwargs) volume = self.block_storage.create_volume(**kwargs)
if volume['status'] == 'error': if volume['status'] == 'error':
raise exc.OpenStackCloudException("Error in creating volume") raise exceptions.SDKException("Error in creating volume")
if wait: if wait:
self.block_storage.wait_for_status(volume, wait=timeout) self.block_storage.wait_for_status(volume, wait=timeout)
@ -177,9 +179,7 @@ class BlockStorageCloudMixin:
volume = self.get_volume(name_or_id) volume = self.get_volume(name_or_id)
if not volume: if not volume:
raise exc.OpenStackCloudException( raise exceptions.SDKException("Volume %s not found." % name_or_id)
"Volume %s not found." % name_or_id
)
volume = self.block_storage.update_volume(volume, **kwargs) volume = self.block_storage.update_volume(volume, **kwargs)
@ -192,15 +192,17 @@ class BlockStorageCloudMixin:
:param bool bootable: Whether the volume should be bootable. :param bool bootable: Whether the volume should be bootable.
(Defaults to True) (Defaults to True)
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
:returns: None :returns: None
:raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volume = self.get_volume(name_or_id) volume = self.get_volume(name_or_id)
if not volume: if not volume:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Volume {name_or_id} does not exist".format( "Volume {name_or_id} does not exist".format(
name_or_id=name_or_id name_or_id=name_or_id
) )
@ -222,9 +224,12 @@ class BlockStorageCloudMixin:
:param timeout: Seconds to wait for volume deletion. None is forever. :param timeout: Seconds to wait for volume deletion. None is forever.
:param force: Force delete volume even if the volume is in deleting :param force: Force delete volume even if the volume is in deleting
or error_deleting state. or error_deleting state.
:returns: True if deletion was successful, else False. :returns: True if deletion was successful, else False.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volume = self.block_storage.find_volume(name_or_id) volume = self.block_storage.find_volume(name_or_id)
@ -272,7 +277,7 @@ class BlockStorageCloudMixin:
if name_or_id: if name_or_id:
project = self.get_project(name_or_id) project = self.get_project(name_or_id)
if not project: if not project:
raise exc.OpenStackCloudException("project does not exist") raise exceptions.SDKException("project does not exist")
params['project'] = project params['project'] = project
return self.block_storage.get_limits(**params) return self.block_storage.get_limits(**params)
@ -317,9 +322,12 @@ class BlockStorageCloudMixin:
:param volume: The volume dict to detach. :param volume: The volume dict to detach.
:param wait: If true, waits for volume to be detached. :param wait: If true, waits for volume to be detached.
:param timeout: Seconds to wait for volume detachment. None is forever. :param timeout: Seconds to wait for volume detachment. None is forever.
:returns: None :returns: None
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.compute.delete_volume_attachment( self.compute.delete_volume_attachment(
server=server['id'], server=server['id'],
@ -354,19 +362,22 @@ class BlockStorageCloudMixin:
:param device: The device name where the volume will attach. :param device: The device name where the volume will attach.
:param wait: If true, waits for volume to be attached. :param wait: If true, waits for volume to be attached.
:param timeout: Seconds to wait for volume attachment. None is forever. :param timeout: Seconds to wait for volume attachment. None is forever.
:returns: a volume attachment object. :returns: a volume attachment object.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
dev = self.get_volume_attach_device(volume, server['id']) dev = self.get_volume_attach_device(volume, server['id'])
if dev: if dev:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Volume %s already attached to server %s on device %s" "Volume %s already attached to server %s on device %s"
% (volume['id'], server['id'], dev) % (volume['id'], server['id'], dev)
) )
if volume['status'] != 'available': if volume['status'] != 'available':
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Volume %s is not available. Status is '%s'" "Volume %s is not available. Status is '%s'"
% (volume['id'], volume['status']) % (volume['id'], volume['status'])
) )
@ -422,9 +433,12 @@ class BlockStorageCloudMixin:
:param wait: If true, waits for volume snapshot to be created. :param wait: If true, waits for volume snapshot to be created.
:param timeout: Seconds to wait for volume snapshot creation. None is :param timeout: Seconds to wait for volume snapshot creation. None is
forever. forever.
:returns: The created volume ``Snapshot`` object. :returns: The created volume ``Snapshot`` object.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
kwargs = self._get_volume_kwargs(kwargs) kwargs = self._get_volume_kwargs(kwargs)
payload = {'volume_id': volume_id, 'force': force} payload = {'volume_id': volume_id, 'force': force}
@ -500,9 +514,12 @@ class BlockStorageCloudMixin:
forever. forever.
:param incremental: If set to true, the backup will be incremental. :param incremental: If set to true, the backup will be incremental.
:param snapshot_id: The UUID of the source snapshot to back up. :param snapshot_id: The UUID of the source snapshot to back up.
:returns: The created volume ``Backup`` object. :returns: The created volume ``Backup`` object.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
payload = { payload = {
'name': name, 'name': name,
@ -596,12 +613,14 @@ class BlockStorageCloudMixin:
:param force: Allow delete in state other than error or available. :param force: Allow delete in state other than error or available.
:param wait: If true, waits for volume backup to be deleted. :param wait: If true, waits for volume backup to be deleted.
:param timeout: Seconds to wait for volume backup deletion. None is :param timeout: Seconds to wait for volume backup deletion. None is
forever. forever.
:returns: True if deletion was successful, else False.
:raises: OpenStackCloudTimeout if wait time exceeded.
:raises: OpenStackCloudException on operation error.
"""
:returns: True if deletion was successful, else False.
:raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
"""
volume_backup = self.get_volume_backup(name_or_id) volume_backup = self.get_volume_backup(name_or_id)
if not volume_backup: if not volume_backup:
@ -627,9 +646,12 @@ class BlockStorageCloudMixin:
:param wait: If true, waits for volume snapshot to be deleted. :param wait: If true, waits for volume snapshot to be deleted.
:param timeout: Seconds to wait for volume snapshot deletion. None is :param timeout: Seconds to wait for volume snapshot deletion. None is
forever. forever.
:returns: True if deletion was successful, else False. :returns: True if deletion was successful, else False.
:raises: OpenStackCloudTimeout if wait time exceeded. :raises: :class:`~openstack.exceptions.ResourceTimeout` if wait time
:raises: OpenStackCloudException on operation error. exceeded.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volumesnapshot = self.get_volume_snapshot(name_or_id) volumesnapshot = self.get_volume_snapshot(name_or_id)
@ -764,11 +786,12 @@ class BlockStorageCloudMixin:
:param name_or_id: Name or unique ID of the volume type. :param name_or_id: Name or unique ID of the volume type.
:returns: A volume ``Type`` object if found, else None. :returns: A volume ``Type`` object if found, else None.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volume_type = self.get_volume_type(name_or_id) volume_type = self.get_volume_type(name_or_id)
if not volume_type: if not volume_type:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"VolumeType not found: %s" % name_or_id "VolumeType not found: %s" % name_or_id
) )
@ -781,12 +804,14 @@ class BlockStorageCloudMixin:
:param name_or_id: ID or name of a volume_type :param name_or_id: ID or name of a volume_type
:param project_id: A project id :param project_id: A project id
:returns: None :returns: None
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volume_type = self.get_volume_type(name_or_id) volume_type = self.get_volume_type(name_or_id)
if not volume_type: if not volume_type:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"VolumeType not found: %s" % name_or_id "VolumeType not found: %s" % name_or_id
) )
@ -797,12 +822,14 @@ class BlockStorageCloudMixin:
:param name_or_id: ID or name of a volume_type :param name_or_id: ID or name of a volume_type
:param project_id: A project id :param project_id: A project id
:returns: None :returns: None
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
volume_type = self.get_volume_type(name_or_id) volume_type = self.get_volume_type(name_or_id)
if not volume_type: if not volume_type:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"VolumeType not found: %s" % name_or_id "VolumeType not found: %s" % name_or_id
) )
self.block_storage.remove_type_access(volume_type, project_id) self.block_storage.remove_type_access(volume_type, project_id)
@ -812,9 +839,10 @@ class BlockStorageCloudMixin:
:param name_or_id: project name or id :param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value :param kwargs: key/value pairs of quota name and quota value
:returns: None :returns: None
:raises: OpenStackCloudException if the resource to set the :raises: :class:`~openstack.exceptions.SDKException` if the resource to
quota does not exist. set the quota does not exist.
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
@ -827,8 +855,10 @@ class BlockStorageCloudMixin:
"""Get volume quotas for a project """Get volume quotas for a project
:param name_or_id: project name or id :param name_or_id: project name or id
:returns: A volume ``QuotaSet`` object with the quotas :returns: A volume ``QuotaSet`` object with the quotas
:raises: OpenStackCloudException if it's not a valid project :raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
@ -838,9 +868,10 @@ class BlockStorageCloudMixin:
"""Delete volume quotas for a project """Delete volume quotas for a project
:param name_or_id: project name or id :param name_or_id: project name or id
:returns: The deleted volume ``QuotaSet`` object. :returns: The deleted volume ``QuotaSet`` object.
:raises: OpenStackCloudException if it's not a valid project or the :raises: :class:`~openstack.exceptions.SDKException` if it's not a
call failed valid project or the call failed
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)

View File

@ -11,7 +11,7 @@
# limitations under the License. # limitations under the License.
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc from openstack import exceptions
class CoeCloudMixin: class CoeCloudMixin:
@ -20,8 +20,8 @@ class CoeCloudMixin:
:returns: A list of container infrastructure management ``Cluster`` :returns: A list of container infrastructure management ``Cluster``
objects. objects.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.container_infrastructure_management.clusters()) return list(self.container_infrastructure_management.clusters())
@ -35,8 +35,8 @@ class CoeCloudMixin:
:returns: A list of container infrastructure management ``Cluster`` :returns: A list of container infrastructure management ``Cluster``
objects. objects.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
coe_clusters = self.list_coe_clusters() coe_clusters = self.list_coe_clusters()
return _utils._filter_list(coe_clusters, name_or_id, filters) return _utils._filter_list(coe_clusters, name_or_id, filters)
@ -77,11 +77,10 @@ class CoeCloudMixin:
:param string cluster_template_id: ID of the cluster template to use. :param string cluster_template_id: ID of the cluster template to use.
:param dict kwargs: Any other arguments to pass in. :param dict kwargs: Any other arguments to pass in.
:returns: a dict containing the cluster description
:returns: The created container infrastructure management ``Cluster`` :returns: The created container infrastructure management ``Cluster``
object. object.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call wrong during the OpenStack API call
""" """
cluster = self.container_infrastructure_management.create_cluster( cluster = self.container_infrastructure_management.create_cluster(
name=name, name=name,
@ -95,10 +94,11 @@ class CoeCloudMixin:
"""Delete a COE cluster. """Delete a COE cluster.
:param name_or_id: Name or unique ID of the cluster. :param name_or_id: Name or unique ID of the cluster.
:returns: True if the delete succeeded, False if the :returns: True if the delete succeeded, False if the
cluster was not found. cluster was not found.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
cluster = self.get_coe_cluster(name_or_id) cluster = self.get_coe_cluster(name_or_id)
@ -122,11 +122,12 @@ class CoeCloudMixin:
:returns: The updated cluster ``Cluster`` object. :returns: The updated cluster ``Cluster`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
cluster = self.get_coe_cluster(name_or_id) cluster = self.get_coe_cluster(name_or_id)
if not cluster: if not cluster:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"COE cluster %s not found." % name_or_id "COE cluster %s not found." % name_or_id
) )
@ -158,8 +159,8 @@ class CoeCloudMixin:
certificate that client will use to communicate with the cluster. certificate that client will use to communicate with the cluster.
:returns: a dict representing the signed certs. :returns: a dict representing the signed certs.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
return self.container_infrastructure_management.create_cluster_certificate( # noqa: E501 return self.container_infrastructure_management.create_cluster_certificate( # noqa: E501
cluster_uuid=cluster_id, csr=csr cluster_uuid=cluster_id, csr=csr
@ -172,9 +173,8 @@ class CoeCloudMixin:
ClusterTemplates are always returned with full details. ClusterTemplates are always returned with full details.
:returns: a list of dicts containing the cluster template details. :returns: a list of dicts containing the cluster template details.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException``: if something goes wrong during wrong during the OpenStack API call.
the OpenStack API call.
""" """
return list( return list(
self.container_infrastructure_management.cluster_templates() self.container_infrastructure_management.cluster_templates()
@ -191,9 +191,8 @@ class CoeCloudMixin:
detailed output. detailed output.
:returns: a list of dict containing the cluster templates :returns: a list of dict containing the cluster templates
:raises: :class:`~openstack.exceptions.SDKException`: if something goes
:raises: ``OpenStackCloudException``: if something goes wrong during wrong during the OpenStack API call.
the OpenStack API call.
""" """
cluster_templates = self.list_cluster_templates(detail=detail) cluster_templates = self.list_cluster_templates(detail=detail)
return _utils._filter_list(cluster_templates, name_or_id, filters) return _utils._filter_list(cluster_templates, name_or_id, filters)
@ -240,9 +239,8 @@ class CoeCloudMixin:
Other arguments will be passed in kwargs. Other arguments will be passed in kwargs.
:returns: a dict containing the cluster template description :returns: a dict containing the cluster template description
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during wrong during the OpenStack API call
the OpenStack API call
""" """
cluster_template = ( cluster_template = (
self.container_infrastructure_management.create_cluster_template( self.container_infrastructure_management.create_cluster_template(
@ -260,10 +258,11 @@ class CoeCloudMixin:
"""Delete a cluster template. """Delete a cluster template.
:param name_or_id: Name or unique ID of the cluster template. :param name_or_id: Name or unique ID of the cluster template.
:returns: True if the delete succeeded, False if the :returns: True if the delete succeeded, False if the
cluster template was not found. cluster template was not found.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
cluster_template = self.get_cluster_template(name_or_id) cluster_template = self.get_cluster_template(name_or_id)
@ -287,12 +286,12 @@ class CoeCloudMixin:
:param name_or_id: Name or ID of the cluster template being updated. :param name_or_id: Name or ID of the cluster template being updated.
:returns: an update cluster template. :returns: an update cluster template.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
cluster_template = self.get_cluster_template(name_or_id) cluster_template = self.get_cluster_template(name_or_id)
if not cluster_template: if not cluster_template:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Cluster template %s not found." % name_or_id "Cluster template %s not found." % name_or_id
) )
@ -306,8 +305,9 @@ class CoeCloudMixin:
def list_magnum_services(self): def list_magnum_services(self):
"""List all Magnum services. """List all Magnum services.
:returns: a list of dicts containing the service details.
:raises: OpenStackCloudException on operation error. :returns: a list of dicts containing the service details.
:raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return list(self.container_infrastructure_management.services()) return list(self.container_infrastructure_management.services())

View File

@ -99,8 +99,9 @@ class ComputeCloudMixin:
:param string include: If given, will return a flavor whose name :param string include: If given, will return a flavor whose name
contains this string as a substring. contains this string as a substring.
:param get_extra: :param get_extra:
:returns: A compute ``Flavor`` object. :returns: A compute ``Flavor`` object.
:raises: :class:`~openstack.exceptions.OpenStackCloudException` if no :raises: :class:`~openstack.exceptions.SDKException` if no
matching flavour could be found. matching flavour could be found.
""" """
flavors = self.list_flavors(get_extra=get_extra) flavors = self.list_flavors(get_extra=get_extra)
@ -109,7 +110,7 @@ class ComputeCloudMixin:
not include or include in flavor['name'] not include or include in flavor['name']
): ):
return flavor return flavor
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Could not find a flavor with {ram} and '{include}'".format( "Could not find a flavor with {ram} and '{include}'".format(
ram=ram, include=include ram=ram, include=include
) )
@ -175,10 +176,11 @@ class ComputeCloudMixin:
:param name_or_id: Name or unique ID of the server group(s). :param name_or_id: Name or unique ID of the server group(s).
:param filters: A dict containing additional filters to use. :param filters: A dict containing additional filters to use.
:returns: A list of compute ``ServerGroup`` objects matching the search :returns: A list of compute ``ServerGroup`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
server_groups = self.list_server_groups() server_groups = self.list_server_groups()
return _utils._filter_list(server_groups, name_or_id, filters) return _utils._filter_list(server_groups, name_or_id, filters)
@ -283,7 +285,8 @@ class ComputeCloudMixin:
:returns: False if server or security groups are undefined, True :returns: False if server or security groups are undefined, True
otherwise. otherwise.
:raises: ``OpenStackCloudException``, on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server, security_groups = self._get_server_security_groups( server, security_groups = self._get_server_security_groups(
server, security_groups server, security_groups
@ -306,7 +309,8 @@ class ComputeCloudMixin:
:returns: False if server or security groups are undefined, True :returns: False if server or security groups are undefined, True
otherwise. otherwise.
:raises: ``OpenStackCloudException``, on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server, security_groups = self._get_server_security_groups( server, security_groups = self._get_server_security_groups(
server, security_groups server, security_groups
@ -378,16 +382,18 @@ class ComputeCloudMixin:
:param name_or_id: (optional) project name or ID to get limits for :param name_or_id: (optional) project name or ID to get limits for
if different from the current project if different from the current project
:raises: OpenStackCloudException if it's not a valid project
:returns: A compute :returns: A compute
:class:`~openstack.compute.v2.limits.Limits.AbsoluteLimits` object. :class:`~openstack.compute.v2.limits.Limits.AbsoluteLimits` object.
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
""" """
params = {} params = {}
project_id = None project_id = None
if name_or_id: if name_or_id:
proj = self.get_project(name_or_id) proj = self.get_project(name_or_id)
if not proj: if not proj:
raise exc.OpenStackCloudException("project does not exist") raise exceptions.SDKException("project does not exist")
project_id = proj.id project_id = proj.id
params['tenant_id'] = project_id params['tenant_id'] = project_id
return self.compute.get_limits(**params).absolute return self.compute.get_limits(**params).absolute
@ -468,21 +474,21 @@ class ComputeCloudMixin:
:returns: A string containing the text of the console log or an :returns: A string containing the text of the console log or an
empty string if the cloud does not support console logs. empty string if the cloud does not support console logs.
:raises: OpenStackCloudException if an invalid server argument is given :raises: :class:`~openstack.exceptions.SDKException` if an invalid
or if something else unforseen happens server argument is given or if something else unforseen happens
""" """
if not isinstance(server, dict): if not isinstance(server, dict):
server = self.get_server(server, bare=True) server = self.get_server(server, bare=True)
if not server: if not server:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Console log requested for invalid server" "Console log requested for invalid server"
) )
try: try:
return self._get_server_console_output(server['id'], length) return self._get_server_console_output(server['id'], length)
except exc.OpenStackCloudBadRequest: except exceptions.BadRequestException:
return "" return ""
def _get_server_console_output(self, server_id, length=None): def _get_server_console_output(self, server_id, length=None):
@ -582,8 +588,10 @@ class ComputeCloudMixin:
:param name: Name of the keypair being created. :param name: Name of the keypair being created.
:param public_key: Public key for the new keypair. :param public_key: Public key for the new keypair.
:returns: The created compute ``Keypair`` object. :returns: The created compute ``Keypair`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
keypair = { keypair = {
'name': name, 'name': name,
@ -598,8 +606,8 @@ class ComputeCloudMixin:
:param name: Name of the keypair to delete. :param name: Name of the keypair to delete.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
try: try:
self.compute.delete_keypair(name, ignore_missing=False) self.compute.delete_keypair(name, ignore_missing=False)
@ -630,13 +638,15 @@ class ComputeCloudMixin:
:param wait: If true, waits for image to be created. :param wait: If true, waits for image to be created.
:param timeout: Seconds to wait for image creation. None is forever. :param timeout: Seconds to wait for image creation. None is forever.
:param metadata: Metadata to give newly-created image entity :param metadata: Metadata to give newly-created image entity
:returns: The created image ``Image`` object. :returns: The created image ``Image`` object.
:raises: OpenStackCloudException if there are problems uploading :raises: :class:`~openstack.exceptions.SDKException` if there are
problems uploading
""" """
if not isinstance(server, dict): if not isinstance(server, dict):
server_obj = self.get_server(server, bare=True) server_obj = self.get_server(server, bare=True)
if not server_obj: if not server_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Server {server} could not be found and therefore" "Server {server} could not be found and therefore"
" could not be snapshotted.".format(server=server) " could not be snapshotted.".format(server=server)
) )
@ -800,8 +810,10 @@ class ComputeCloudMixin:
:param group: ServerGroup dict, name or id to boot the server in. :param group: ServerGroup dict, name or id to boot the server in.
If a group is provided in both scheduler_hints and in the group If a group is provided in both scheduler_hints and in the group
param, the group param will win. (Optional, defaults to None) param, the group param will win. (Optional, defaults to None)
:returns: The created compute ``Server`` object. :returns: The created compute ``Server`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
# TODO(shade) Image is optional but flavor is not - yet flavor comes # TODO(shade) Image is optional but flavor is not - yet flavor comes
# after image in the argument list. Doh. # after image in the argument list. Doh.
@ -840,7 +852,7 @@ class ComputeCloudMixin:
if group: if group:
group_obj = self.get_server_group(group) group_obj = self.get_server_group(group)
if not group_obj: if not group_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Server Group {group} was requested but was not found" "Server Group {group} was requested but was not found"
" on the cloud".format(group=group) " on the cloud".format(group=group)
) )
@ -856,7 +868,7 @@ class ComputeCloudMixin:
# Be nice and help the user out # Be nice and help the user out
kwargs['nics'] = [kwargs['nics']] kwargs['nics'] = [kwargs['nics']]
else: else:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'nics parameter to create_server takes a list of dicts.' 'nics parameter to create_server takes a list of dicts.'
' Got: {nics}'.format(nics=kwargs['nics']) ' Got: {nics}'.format(nics=kwargs['nics'])
) )
@ -871,7 +883,7 @@ class ComputeCloudMixin:
else: else:
network_obj = self.get_network(name_or_id=net_name) network_obj = self.get_network(name_or_id=net_name)
if not network_obj: if not network_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Network {network} is not a valid network in' 'Network {network} is not a valid network in'
' {cloud}:{region}'.format( ' {cloud}:{region}'.format(
network=network, network=network,
@ -899,7 +911,7 @@ class ComputeCloudMixin:
net_name = nic.pop('net-name') net_name = nic.pop('net-name')
nic_net = self.get_network(net_name) nic_net = self.get_network(net_name)
if not nic_net: if not nic_net:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Requested network {net} could not be found.".format( "Requested network {net} could not be found.".format(
net=net_name net=net_name
) )
@ -908,7 +920,7 @@ class ComputeCloudMixin:
for ip_key in ('v4-fixed-ip', 'v6-fixed-ip', 'fixed_ip'): for ip_key in ('v4-fixed-ip', 'v6-fixed-ip', 'fixed_ip'):
fixed_ip = nic.pop(ip_key, None) fixed_ip = nic.pop(ip_key, None)
if fixed_ip and net.get('fixed_ip'): if fixed_ip and net.get('fixed_ip'):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Only one of v4-fixed-ip, v6-fixed-ip or fixed_ip" "Only one of v4-fixed-ip, v6-fixed-ip or fixed_ip"
" may be given" " may be given"
) )
@ -923,7 +935,7 @@ class ComputeCloudMixin:
utils.require_microversion(self.compute, '2.42') utils.require_microversion(self.compute, '2.42')
net['tag'] = nic.pop('tag') net['tag'] = nic.pop('tag')
if nic: if nic:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Additional unsupported keys given for server network" "Additional unsupported keys given for server network"
" creation: {keys}".format(keys=nic.keys()) " creation: {keys}".format(keys=nic.keys())
) )
@ -1018,7 +1030,7 @@ class ComputeCloudMixin:
if boot_volume: if boot_volume:
volume = self.get_volume(boot_volume) volume = self.get_volume(boot_volume)
if not volume: if not volume:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Volume {boot_volume} is not a valid volume' 'Volume {boot_volume} is not a valid volume'
' in {cloud}:{region}'.format( ' in {cloud}:{region}'.format(
boot_volume=boot_volume, boot_volume=boot_volume,
@ -1041,7 +1053,7 @@ class ComputeCloudMixin:
else: else:
image_obj = self.get_image(image) image_obj = self.get_image(image)
if not image_obj: if not image_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Image {image} is not a valid image in' 'Image {image} is not a valid image in'
' {cloud}:{region}'.format( ' {cloud}:{region}'.format(
image=image, image=image,
@ -1074,7 +1086,7 @@ class ComputeCloudMixin:
for volume in volumes: for volume in volumes:
volume_obj = self.get_volume(volume) volume_obj = self.get_volume(volume)
if not volume_obj: if not volume_obj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Volume {volume} is not a valid volume' 'Volume {volume} is not a valid volume'
' in {cloud}:{region}'.format( ' in {cloud}:{region}'.format(
volume=volume, volume=volume,
@ -1126,7 +1138,7 @@ class ComputeCloudMixin:
# and pass it down into the IP stack. # and pass it down into the IP stack.
remaining_timeout = timeout - int(time.time() - start_time) remaining_timeout = timeout - int(time.time() - start_time)
if remaining_timeout <= 0: if remaining_timeout <= 0:
raise exc.OpenStackCloudTimeout(timeout_message) raise exceptions.ResourceTimeout(timeout_message)
server = self.get_active_server( server = self.get_active_server(
server=server, server=server,
@ -1159,7 +1171,7 @@ class ComputeCloudMixin:
and server['fault'] is not None and server['fault'] is not None
and 'message' in server['fault'] and 'message' in server['fault']
): ):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Error in creating the server." "Error in creating the server."
" Compute service reports fault: {reason}".format( " Compute service reports fault: {reason}".format(
reason=server['fault']['message'] reason=server['fault']['message']
@ -1167,7 +1179,7 @@ class ComputeCloudMixin:
extra_data=dict(server=server), extra_data=dict(server=server),
) )
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Error in creating the server" "Error in creating the server"
" (no further information available)", " (no further information available)",
extra_data=dict(server=server), extra_data=dict(server=server),
@ -1195,13 +1207,13 @@ class ComputeCloudMixin:
try: try:
self._delete_server(server=server, wait=wait, timeout=timeout) self._delete_server(server=server, wait=wait, timeout=timeout)
except Exception as e: except Exception as e:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Server reached ACTIVE state without being' 'Server reached ACTIVE state without being'
' allocated an IP address AND then could not' ' allocated an IP address AND then could not'
' be deleted: {0}'.format(e), ' be deleted: {0}'.format(e),
extra_data=dict(server=server), extra_data=dict(server=server),
) )
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Server reached ACTIVE state without being' 'Server reached ACTIVE state without being'
' allocated an IP address.', ' allocated an IP address.',
extra_data=dict(server=server), extra_data=dict(server=server),
@ -1253,12 +1265,14 @@ class ComputeCloudMixin:
:param dict metadata: A dictionary with the key=value pairs :param dict metadata: A dictionary with the key=value pairs
to set in the server instance. It only updates the key=value pairs to set in the server instance. It only updates the key=value pairs
provided. Existing ones will remain untouched. provided. Existing ones will remain untouched.
:returns: None :returns: None
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server = self.get_server(name_or_id, bare=True) server = self.get_server(name_or_id, bare=True)
if not server: if not server:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Invalid Server {server}'.format(server=name_or_id) 'Invalid Server {server}'.format(server=name_or_id)
) )
@ -1271,12 +1285,14 @@ class ComputeCloudMixin:
to update. to update.
:param metadata_keys: A list with the keys to be deleted :param metadata_keys: A list with the keys to be deleted
from the server instance. from the server instance.
:returns: None :returns: None
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server = self.get_server(name_or_id, bare=True) server = self.get_server(name_or_id, bare=True)
if not server: if not server:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Invalid Server {server}'.format(server=name_or_id) 'Invalid Server {server}'.format(server=name_or_id)
) )
@ -1301,9 +1317,11 @@ class ComputeCloudMixin:
associated with the instance. associated with the instance.
:param int delete_ip_retry: Number of times to retry deleting :param int delete_ip_retry: Number of times to retry deleting
any floating ips, should the first try be unsuccessful. any floating ips, should the first try be unsuccessful.
:returns: True if delete succeeded, False otherwise if the :returns: True if delete succeeded, False otherwise if the
server does not exist. server does not exist.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
# If delete_ips is True, we need the server to not be bare. # If delete_ips is True, we need the server to not be bare.
server = self.compute.find_server(name_or_id, ignore_missing=True) server = self.compute.find_server(name_or_id, ignore_missing=True)
@ -1332,7 +1350,7 @@ class ComputeCloudMixin:
ip = self.get_floating_ip( ip = self.get_floating_ip(
id=None, filters={'floating_ip_address': fip['addr']} id=None, filters={'floating_ip_address': fip['addr']}
) )
except exc.OpenStackCloudURINotFound: except exceptions.NotFoundException:
# We're deleting. If it doesn't exist - awesome # We're deleting. If it doesn't exist - awesome
# NOTE(mordred) If the cloud is a nova FIP cloud but # NOTE(mordred) If the cloud is a nova FIP cloud but
# floating_ip_source is set to neutron, this # floating_ip_source is set to neutron, this
@ -1342,7 +1360,7 @@ class ComputeCloudMixin:
continue continue
deleted = self.delete_floating_ip(ip['id'], retry=delete_ip_retry) deleted = self.delete_floating_ip(ip['id'], retry=delete_ip_retry)
if not deleted: if not deleted:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Tried to delete floating ip {floating_ip}" "Tried to delete floating ip {floating_ip}"
" associated with server {id} but there was" " associated with server {id} but there was"
" an error deleting it. Not deleting server.".format( " an error deleting it. Not deleting server.".format(
@ -1396,8 +1414,10 @@ class ComputeCloudMixin:
detailed = False. detailed = False.
:param name: New name for the server :param name: New name for the server
:param description: New description for the server :param description: New description for the server
:returns: The updated compute ``Server`` object. :returns: The updated compute ``Server`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server = self.compute.find_server(name_or_id, ignore_missing=False) server = self.compute.find_server(name_or_id, ignore_missing=False)
@ -1410,8 +1430,10 @@ class ComputeCloudMixin:
:param name: Name of the server group being created :param name: Name of the server group being created
:param policies: List of policies for the server group. :param policies: List of policies for the server group.
:returns: The created compute ``ServerGroup`` object. :returns: The created compute ``ServerGroup`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
sg_attrs = {'name': name} sg_attrs = {'name': name}
if policies: if policies:
@ -1424,8 +1446,10 @@ class ComputeCloudMixin:
"""Delete a server group. """Delete a server group.
:param name_or_id: Name or ID of the server group to delete :param name_or_id: Name or ID of the server group to delete
:returns: True if delete succeeded, False otherwise :returns: True if delete succeeded, False otherwise
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
server_group = self.get_server_group(name_or_id) server_group = self.get_server_group(name_or_id)
if not server_group: if not server_group:
@ -1462,8 +1486,10 @@ class ComputeCloudMixin:
:param swap: Swap space in MB :param swap: Swap space in MB
:param rxtx_factor: RX/TX factor :param rxtx_factor: RX/TX factor
:param is_public: Make flavor accessible to the public :param is_public: Make flavor accessible to the public
:returns: The created compute ``Flavor`` object. :returns: The created compute ``Flavor`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
attrs = { attrs = {
'disk': disk, 'disk': disk,
@ -1486,8 +1512,10 @@ class ComputeCloudMixin:
"""Delete a flavor """Delete a flavor
:param name_or_id: ID or name of the flavor to delete. :param name_or_id: ID or name of the flavor to delete.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
try: try:
flavor = self.compute.find_flavor(name_or_id) flavor = self.compute.find_flavor(name_or_id)
@ -1497,7 +1525,7 @@ class ComputeCloudMixin:
self.compute.delete_flavor(flavor) self.compute.delete_flavor(flavor)
return True return True
except exceptions.SDKException: except exceptions.SDKException:
raise exceptions.OpenStackCloudException( raise exceptions.SDKException(
"Unable to delete flavor {name}".format(name=name_or_id) "Unable to delete flavor {name}".format(name=name_or_id)
) )
@ -1507,8 +1535,10 @@ class ComputeCloudMixin:
:param string flavor_id: ID of the flavor to update. :param string flavor_id: ID of the flavor to update.
:param dict extra_specs: Dictionary of key-value pairs. :param dict extra_specs: Dictionary of key-value pairs.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudResourceNotFound if flavor ID is not found. error.
:raises: :class:`~openstack.exceptions.BadRequestException` if flavor
ID is not found.
""" """
self.compute.create_flavor_extra_specs(flavor_id, extra_specs) self.compute.create_flavor_extra_specs(flavor_id, extra_specs)
@ -1518,8 +1548,10 @@ class ComputeCloudMixin:
:param string flavor_id: ID of the flavor to update. :param string flavor_id: ID of the flavor to update.
:param keys: List of spec keys to delete. :param keys: List of spec keys to delete.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudResourceNotFound if flavor ID is not found. error.
:raises: :class:`~openstack.exceptions.BadRequestException` if flavor
ID is not found.
""" """
for key in keys: for key in keys:
self.compute.delete_flavor_extra_specs_property(flavor_id, key) self.compute.delete_flavor_extra_specs_property(flavor_id, key)
@ -1530,7 +1562,8 @@ class ComputeCloudMixin:
:param string flavor_id: ID of the private flavor. :param string flavor_id: ID of the private flavor.
:param string project_id: ID of the project/tenant. :param string project_id: ID of the project/tenant.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.compute.flavor_add_tenant_access(flavor_id, project_id) self.compute.flavor_add_tenant_access(flavor_id, project_id)
@ -1540,7 +1573,8 @@ class ComputeCloudMixin:
:param string flavor_id: ID of the private flavor. :param string flavor_id: ID of the private flavor.
:param string project_id: ID of the project/tenant. :param string project_id: ID of the project/tenant.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
self.compute.flavor_remove_tenant_access(flavor_id, project_id) self.compute.flavor_remove_tenant_access(flavor_id, project_id)
@ -1548,8 +1582,10 @@ class ComputeCloudMixin:
"""List access from a private flavor for a project/tenant. """List access from a private flavor for a project/tenant.
:param string flavor_id: ID of the private flavor. :param string flavor_id: ID of the private flavor.
:returns: List of dicts with flavor_id and tenant_id attributes. :returns: List of dicts with flavor_id and tenant_id attributes.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return self.compute.get_flavor_access(flavor_id) return self.compute.get_flavor_access(flavor_id)
@ -1569,10 +1605,11 @@ class ComputeCloudMixin:
:param name: aggregate name or id. :param name: aggregate name or id.
:param filters: a dict containing additional filters to use. :param filters: a dict containing additional filters to use.
:returns: A list of compute ``Aggregate`` objects matching the search :returns: A list of compute ``Aggregate`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
aggregates = self.list_aggregates() aggregates = self.list_aggregates()
return _utils._filter_list(aggregates, name_or_id, filters) return _utils._filter_list(aggregates, name_or_id, filters)
@ -1612,8 +1649,10 @@ class ComputeCloudMixin:
:param name: Name of the host aggregate being created :param name: Name of the host aggregate being created
:param availability_zone: Availability zone to assign hosts :param availability_zone: Availability zone to assign hosts
:returns: The created compute ``Aggregate`` object. :returns: The created compute ``Aggregate`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return self.compute.create_aggregate( return self.compute.create_aggregate(
name=name, availability_zone=availability_zone name=name, availability_zone=availability_zone
@ -1626,8 +1665,10 @@ class ComputeCloudMixin:
:param name_or_id: Name or ID of the aggregate being updated. :param name_or_id: Name or ID of the aggregate being updated.
:param name: New aggregate name :param name: New aggregate name
:param availability_zone: Availability zone to assign to hosts :param availability_zone: Availability zone to assign to hosts
:returns: The updated compute ``Aggregate`` object. :returns: The updated compute ``Aggregate`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
aggregate = self.get_aggregate(name_or_id) aggregate = self.get_aggregate(name_or_id)
return self.compute.update_aggregate(aggregate, **kwargs) return self.compute.update_aggregate(aggregate, **kwargs)
@ -1636,8 +1677,10 @@ class ComputeCloudMixin:
"""Delete a host aggregate. """Delete a host aggregate.
:param name_or_id: Name or ID of the host aggregate to delete. :param name_or_id: Name or ID of the host aggregate to delete.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if isinstance(name_or_id, (str, bytes)) and not name_or_id.isdigit(): if isinstance(name_or_id, (str, bytes)) and not name_or_id.isdigit():
aggregate = self.get_aggregate(name_or_id) aggregate = self.get_aggregate(name_or_id)
@ -1662,12 +1705,12 @@ class ComputeCloudMixin:
{'key': None} to remove a key) {'key': None} to remove a key)
:returns: a dict representing the new host aggregate. :returns: a dict representing the new host aggregate.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
aggregate = self.get_aggregate(name_or_id) aggregate = self.get_aggregate(name_or_id)
if not aggregate: if not aggregate:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Host aggregate %s not found." % name_or_id "Host aggregate %s not found." % name_or_id
) )
@ -1679,11 +1722,12 @@ class ComputeCloudMixin:
:param name_or_id: Name or ID of the host aggregate. :param name_or_id: Name or ID of the host aggregate.
:param host_name: Host to add. :param host_name: Host to add.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
aggregate = self.get_aggregate(name_or_id) aggregate = self.get_aggregate(name_or_id)
if not aggregate: if not aggregate:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Host aggregate %s not found." % name_or_id "Host aggregate %s not found." % name_or_id
) )
@ -1695,11 +1739,12 @@ class ComputeCloudMixin:
:param name_or_id: Name or ID of the host aggregate. :param name_or_id: Name or ID of the host aggregate.
:param host_name: Host to remove. :param host_name: Host to remove.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
aggregate = self.get_aggregate(name_or_id) aggregate = self.get_aggregate(name_or_id)
if not aggregate: if not aggregate:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Host aggregate %s not found." % name_or_id "Host aggregate %s not found." % name_or_id
) )
@ -1711,8 +1756,8 @@ class ComputeCloudMixin:
:param name_or_id: project name or id :param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value :param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the :raises: :class:`~openstack.exceptions.SDKException` if the resource to
quota does not exist. set the quota does not exist.
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
kwargs['force'] = True kwargs['force'] = True
@ -1724,8 +1769,10 @@ class ComputeCloudMixin:
"""Get quota for a project """Get quota for a project
:param name_or_id: project name or id :param name_or_id: project name or id
:returns: A compute ``QuotaSet`` object if found, else None. :returns: A compute ``QuotaSet`` object if found, else None.
:raises: OpenStackCloudException if it's not a valid project :raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
return self.compute.get_quota_set(proj) return self.compute.get_quota_set(proj)
@ -1734,9 +1781,9 @@ class ComputeCloudMixin:
"""Delete quota for a project """Delete quota for a project
:param name_or_id: project name or id :param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
nova client call failed :raises: :class:`~openstack.exceptions.SDKException` if it's not a
:returns: None valid project or the nova client call failed
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
self.compute.revert_quota_set(proj) self.compute.revert_quota_set(proj)
@ -1750,9 +1797,10 @@ class ComputeCloudMixin:
was started) was started)
:param end: :class:`datetime.datetime` or string. End date in UTC. :param end: :class:`datetime.datetime` or string. End date in UTC.
Defaults to now Defaults to now
:raises: OpenStackCloudException if it's not a valid project
:returns: A :class:`~openstack.compute.v2.usage.Usage` object :returns: A :class:`~openstack.compute.v2.usage.Usage` object
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
""" """
def parse_date(date): def parse_date(date):
@ -1762,7 +1810,7 @@ class ComputeCloudMixin:
# Yes. This is an exception mask. However,iso8601 is an # Yes. This is an exception mask. However,iso8601 is an
# implementation detail - and the error message is actually # implementation detail - and the error message is actually
# less informative. # less informative.
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Date given, {date}, is invalid. Please pass in a date" "Date given, {date}, is invalid. Please pass in a date"
" string in ISO 8601 format -" " string in ISO 8601 format -"
" YYYY-MM-DDTHH:MM:SS".format(date=date) " YYYY-MM-DDTHH:MM:SS".format(date=date)
@ -1775,7 +1823,7 @@ class ComputeCloudMixin:
proj = self.get_project(name_or_id) proj = self.get_project(name_or_id)
if not proj: if not proj:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"project does not exist: {name}".format(name=proj.id) "project does not exist: {name}".format(name=proj.id)
) )

View File

@ -11,7 +11,6 @@
# limitations under the License. # limitations under the License.
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc
from openstack.dns.v2._proxy import Proxy from openstack.dns.v2._proxy import Proxy
from openstack import exceptions from openstack import exceptions
from openstack import resource from openstack import resource
@ -74,8 +73,8 @@ class DnsCloudMixin:
if zone_type is secondary) if zone_type is secondary)
:returns: a dict representing the created zone. :returns: a dict representing the created zone.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
# We capitalize in case the user passes time in lowercase, as # We capitalize in case the user passes time in lowercase, as
@ -83,7 +82,7 @@ class DnsCloudMixin:
if zone_type is not None: if zone_type is not None:
zone_type = zone_type.upper() zone_type = zone_type.upper()
if zone_type not in ('PRIMARY', 'SECONDARY'): if zone_type not in ('PRIMARY', 'SECONDARY'):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Invalid type %s, valid choices are PRIMARY or SECONDARY" "Invalid type %s, valid choices are PRIMARY or SECONDARY"
% zone_type % zone_type
) )
@ -105,7 +104,7 @@ class DnsCloudMixin:
try: try:
return self.dns.create_zone(**zone) return self.dns.create_zone(**zone)
except exceptions.SDKException: except exceptions.SDKException:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Unable to create zone {name}".format(name=name) "Unable to create zone {name}".format(name=name)
) )
@ -122,14 +121,12 @@ class DnsCloudMixin:
if zone_type is secondary) if zone_type is secondary)
:returns: a dict representing the updated zone. :returns: a dict representing the updated zone.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
zone = self.get_zone(name_or_id) zone = self.get_zone(name_or_id)
if not zone: if not zone:
raise exc.OpenStackCloudException( raise exceptions.SDKException("Zone %s not found." % name_or_id)
"Zone %s not found." % name_or_id
)
return self.dns.update_zone(zone['id'], **kwargs) return self.dns.update_zone(zone['id'], **kwargs)
@ -139,8 +136,8 @@ class DnsCloudMixin:
:param name_or_id: Name or ID of the zone being deleted. :param name_or_id: Name or ID of the zone being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
zone = self.dns.find_zone(name_or_id) zone = self.dns.find_zone(name_or_id)
@ -166,7 +163,7 @@ class DnsCloudMixin:
else: else:
zone_obj = self.get_zone(zone) zone_obj = self.get_zone(zone)
if zone_obj is None: if zone_obj is None:
raise exc.OpenStackCloudException("Zone %s not found." % zone) raise exceptions.SDKException("Zone %s not found." % zone)
return list(self.dns.recordsets(zone_obj)) return list(self.dns.recordsets(zone_obj))
def get_recordset(self, zone, name_or_id): def get_recordset(self, zone, name_or_id):
@ -185,7 +182,7 @@ class DnsCloudMixin:
else: else:
zone_obj = self.get_zone(zone) zone_obj = self.get_zone(zone)
if not zone_obj: if not zone_obj:
raise exc.OpenStackCloudException("Zone %s not found." % zone) raise exceptions.SDKException("Zone %s not found." % zone)
try: try:
return self.dns.find_recordset( return self.dns.find_recordset(
zone=zone_obj, name_or_id=name_or_id, ignore_missing=False zone=zone_obj, name_or_id=name_or_id, ignore_missing=False
@ -211,16 +208,15 @@ class DnsCloudMixin:
:param ttl: TTL value of the recordset :param ttl: TTL value of the recordset
:returns: a dict representing the created recordset. :returns: a dict representing the created recordset.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
if isinstance(zone, resource.Resource): if isinstance(zone, resource.Resource):
zone_obj = zone zone_obj = zone
else: else:
zone_obj = self.get_zone(zone) zone_obj = self.get_zone(zone)
if not zone_obj: if not zone_obj:
raise exc.OpenStackCloudException("Zone %s not found." % zone) raise exceptions.SDKException("Zone %s not found." % zone)
# We capitalize the type in case the user sends in lowercase # We capitalize the type in case the user sends in lowercase
recordset_type = recordset_type.upper() recordset_type = recordset_type.upper()
@ -247,13 +243,13 @@ class DnsCloudMixin:
:param ttl: TTL (Time to live) value in seconds of the recordset :param ttl: TTL (Time to live) value in seconds of the recordset
:returns: a dict representing the updated recordset. :returns: a dict representing the updated recordset.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
rs = self.get_recordset(zone, name_or_id) rs = self.get_recordset(zone, name_or_id)
if not rs: if not rs:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Recordset %s not found." % name_or_id "Recordset %s not found." % name_or_id
) )
@ -269,8 +265,8 @@ class DnsCloudMixin:
:param name_or_id: Name or ID of the recordset being deleted. :param name_or_id: Name or ID of the recordset being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
recordset = self.get_recordset(zone, name_or_id) recordset = self.get_recordset(zone, name_or_id)

View File

@ -67,7 +67,7 @@ class FloatingIPCloudMixin:
def _nova_list_floating_ips(self): def _nova_list_floating_ips(self):
try: try:
data = proxy._json_response(self.compute.get('/os-floating-ips')) data = proxy._json_response(self.compute.get('/os-floating-ips'))
except exc.OpenStackCloudURINotFound: except exceptions.NotFoundException:
return [] return []
return self._get_and_munchify('floating_ips', data) return self._get_and_munchify('floating_ips', data)
@ -109,7 +109,7 @@ class FloatingIPCloudMixin:
if self._use_neutron_floating(): if self._use_neutron_floating():
try: try:
return self._neutron_list_floating_ips(filters) return self._neutron_list_floating_ips(filters)
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
# Nova-network don't support server-side floating ips # Nova-network don't support server-side floating ips
# filtering, so it's safer to return an empty list than # filtering, so it's safer to return an empty list than
# to fallback to Nova which may return more results that # to fallback to Nova which may return more results that
@ -206,8 +206,8 @@ class FloatingIPCloudMixin:
:param server: (server) Server the Floating IP is for :param server: (server) Server the Floating IP is for
:returns: a list of floating IP addresses. :returns: a list of floating IP addresses.
:raises: ``OpenStackCloudResourceNotFound``, if an external network :raises: :class:`~openstack.exceptions.BadRequestException` if an
that meets the specified criteria cannot be found. external network that meets the specified criteria cannot be found.
""" """
if project_id is None: if project_id is None:
# Make sure we are only listing floatingIPs allocated the current # Make sure we are only listing floatingIPs allocated the current
@ -229,7 +229,7 @@ class FloatingIPCloudMixin:
break break
if floating_network_id is None: if floating_network_id is None:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"unable to find external network {net}".format(net=network) "unable to find external network {net}".format(net=network)
) )
else: else:
@ -265,9 +265,8 @@ class FloatingIPCloudMixin:
:param pool: Nova floating IP pool name. :param pool: Nova floating IP pool name.
:returns: a list of floating IP addresses. :returns: a list of floating IP addresses.
:raises: :class:`~openstack.exceptions.BadRequestException` if a
:raises: ``OpenStackCloudResourceNotFound``, if a floating IP pool floating IP pool is not specified and cannot be found.
is not specified and cannot be found.
""" """
with _utils.openstacksdk_exceptions( with _utils.openstacksdk_exceptions(
@ -276,7 +275,7 @@ class FloatingIPCloudMixin:
if pool is None: if pool is None:
pools = self.list_floating_ip_pools() pools = self.list_floating_ip_pools()
if not pools: if not pools:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"unable to find a floating ip pool" "unable to find a floating ip pool"
) )
pool = pools[0]['name'] pool = pools[0]['name']
@ -323,7 +322,7 @@ class FloatingIPCloudMixin:
network=network, server=server network=network, server=server
) )
return f_ips[0] return f_ips[0]
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
self.log.debug( self.log.debug(
"Something went wrong talking to neutron API: " "Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", "'%(msg)s'. Trying with Nova.",
@ -346,7 +345,7 @@ class FloatingIPCloudMixin:
if floating_network: if floating_network:
floating_network_id = floating_network floating_network_id = floating_network
else: else:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"unable to find an external network" "unable to find an external network"
) )
return floating_network_id return floating_network_id
@ -384,8 +383,8 @@ class FloatingIPCloudMixin:
provided. provided.
:returns: a floating IP address :returns: a floating IP address
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: ``OpenStackCloudException``, on operation error. error.
""" """
if self._use_neutron_floating(): if self._use_neutron_floating():
try: try:
@ -398,7 +397,7 @@ class FloatingIPCloudMixin:
wait=wait, wait=wait,
timeout=timeout, timeout=timeout,
) )
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
self.log.debug( self.log.debug(
"Something went wrong talking to neutron API: " "Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", "'%(msg)s'. Trying with Nova.",
@ -407,7 +406,7 @@ class FloatingIPCloudMixin:
# Fall-through, trying with Nova # Fall-through, trying with Nova
if port: if port:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"This cloud uses nova-network which does not support" "This cloud uses nova-network which does not support"
" arbitrary floating-ip/port mappings. Please nudge" " arbitrary floating-ip/port mappings. Please nudge"
" your cloud provider to upgrade the networking stack" " your cloud provider to upgrade the networking stack"
@ -440,7 +439,7 @@ class FloatingIPCloudMixin:
try: try:
network = self.network.find_network(network_name_or_id) network = self.network.find_network(network_name_or_id)
except exceptions.ResourceNotFound: except exceptions.ResourceNotFound:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"unable to find network for floating ips with ID " "unable to find network for floating ips with ID "
"{0}".format(network_name_or_id) "{0}".format(network_name_or_id)
) )
@ -481,7 +480,7 @@ class FloatingIPCloudMixin:
fip = self.get_floating_ip(fip_id) fip = self.get_floating_ip(fip_id)
if fip and fip['status'] == 'ACTIVE': if fip and fip['status'] == 'ACTIVE':
break break
except exc.OpenStackCloudTimeout: except exceptions.ResourceTimeout:
self.log.error( self.log.error(
"Timed out on floating ip %(fip)s becoming active." "Timed out on floating ip %(fip)s becoming active."
" Deleting", " Deleting",
@ -499,7 +498,7 @@ class FloatingIPCloudMixin:
raise raise
if fip['port_id'] != port: if fip['port_id'] != port:
if server: if server:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Attempted to create FIP on port {port} for server" "Attempted to create FIP on port {port} for server"
" {server} but FIP has port {port_id}".format( " {server} but FIP has port {port_id}".format(
port=port, port=port,
@ -508,7 +507,7 @@ class FloatingIPCloudMixin:
) )
) )
else: else:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Attempted to create FIP on port {port}" "Attempted to create FIP on port {port}"
" but something went wrong".format(port=port) " but something went wrong".format(port=port)
) )
@ -521,7 +520,7 @@ class FloatingIPCloudMixin:
if pool is None: if pool is None:
pools = self.list_floating_ip_pools() pools = self.list_floating_ip_pools()
if not pools: if not pools:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"unable to find a floating ip pool" "unable to find a floating ip pool"
) )
pool = pools[0]['name'] pool = pools[0]['name']
@ -548,9 +547,9 @@ class FloatingIPCloudMixin:
occur. occur.
:returns: True if the IP address has been deleted, False if the IP :returns: True if the IP address has been deleted, False if the IP
address was not found. address was not found.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: ``OpenStackCloudException``, on operation error. error.
""" """
for count in range(0, max(0, retry) + 1): for count in range(0, max(0, retry) + 1):
result = self._delete_floating_ip(floating_ip_id) result = self._delete_floating_ip(floating_ip_id)
@ -566,7 +565,7 @@ class FloatingIPCloudMixin:
if not f_ip or f_ip['status'] == 'DOWN': if not f_ip or f_ip['status'] == 'DOWN':
return True return True
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Attempted to delete Floating IP {ip} with ID {id} a total of" "Attempted to delete Floating IP {ip} with ID {id} a total of"
" {retry} times. Although the cloud did not indicate any errors" " {retry} times. Although the cloud did not indicate any errors"
" the floating ip is still in existence. Aborting further" " the floating ip is still in existence. Aborting further"
@ -581,7 +580,7 @@ class FloatingIPCloudMixin:
if self._use_neutron_floating(): if self._use_neutron_floating():
try: try:
return self._neutron_delete_floating_ip(floating_ip_id) return self._neutron_delete_floating_ip(floating_ip_id)
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
self.log.debug( self.log.debug(
"Something went wrong talking to neutron API: " "Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", "'%(msg)s'. Trying with Nova.",
@ -606,7 +605,7 @@ class FloatingIPCloudMixin:
fip_id=floating_ip_id fip_id=floating_ip_id
), ),
) )
except exc.OpenStackCloudURINotFound: except exceptions.NotFoundException:
return False return False
return True return True
@ -629,8 +628,8 @@ class FloatingIPCloudMixin:
occur. occur.
:returns: Number of Floating IPs deleted, False if none :returns: Number of Floating IPs deleted, False if none
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: ``OpenStackCloudException``, on operation error. error.
""" """
processed = [] processed = []
if self._use_neutron_floating(): if self._use_neutron_floating():
@ -669,8 +668,8 @@ class FloatingIPCloudMixin:
FIP to attach to will come from. FIP to attach to will come from.
:returns: The server ``openstack.compute.v2.server.Server`` :returns: The server ``openstack.compute.v2.server.Server``
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException, on operation error. error.
""" """
# Short circuit if we're asking to attach an IP that's already # Short circuit if we're asking to attach an IP that's already
# attached # attached
@ -697,7 +696,7 @@ class FloatingIPCloudMixin:
fixed_address=fixed_address, fixed_address=fixed_address,
nat_destination=nat_destination, nat_destination=nat_destination,
) )
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
self.log.debug( self.log.debug(
"Something went wrong talking to neutron API: " "Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", "'%(msg)s'. Trying with Nova.",
@ -738,7 +737,7 @@ class FloatingIPCloudMixin:
nat_destination=nat_destination, nat_destination=nat_destination,
) )
if not port: if not port:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"unable to find a port for server {0}".format(server['id']) "unable to find a port for server {0}".format(server['id'])
) )
@ -753,7 +752,7 @@ class FloatingIPCloudMixin:
): ):
f_ip = self.get_floating_ip(id=floating_ip_id) f_ip = self.get_floating_ip(id=floating_ip_id)
if f_ip is None: if f_ip is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"unable to find floating IP {0}".format(floating_ip_id) "unable to find floating IP {0}".format(floating_ip_id)
) )
error_message = "Error attaching IP {ip} to instance {id}".format( error_message = "Error attaching IP {ip} to instance {id}".format(
@ -777,16 +776,16 @@ class FloatingIPCloudMixin:
:param floating_ip_id: Id of the floating IP to detach. :param floating_ip_id: Id of the floating IP to detach.
:returns: True if the IP has been detached, or False if the IP wasn't :returns: True if the IP has been detached, or False if the IP wasn't
attached to any server. attached to any server.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: ``OpenStackCloudException``, on operation error. error.
""" """
if self._use_neutron_floating(): if self._use_neutron_floating():
try: try:
return self._neutron_detach_ip_from_server( return self._neutron_detach_ip_from_server(
server_id=server_id, floating_ip_id=floating_ip_id server_id=server_id, floating_ip_id=floating_ip_id
) )
except exc.OpenStackCloudURINotFound as e: except exceptions.NotFoundException as e:
self.log.debug( self.log.debug(
"Something went wrong talking to neutron API: " "Something went wrong talking to neutron API: "
"'%(msg)s'. Trying with Nova.", "'%(msg)s'. Trying with Nova.",
@ -820,7 +819,7 @@ class FloatingIPCloudMixin:
def _nova_detach_ip_from_server(self, server_id, floating_ip_id): def _nova_detach_ip_from_server(self, server_id, floating_ip_id):
f_ip = self.get_floating_ip(id=floating_ip_id) f_ip = self.get_floating_ip(id=floating_ip_id)
if f_ip is None: if f_ip is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"unable to find floating IP {0}".format(floating_ip_id) "unable to find floating IP {0}".format(floating_ip_id)
) )
error_message = "Error detaching IP {ip} from instance {id}".format( error_message = "Error detaching IP {ip} from instance {id}".format(
@ -921,8 +920,8 @@ class FloatingIPCloudMixin:
floating IP should be on floating IP should be on
:returns: The updated server ``openstack.compute.v2.server.Server`` :returns: The updated server ``openstack.compute.v2.server.Server``
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: ``OpenStackCloudException``, on operation error. error.
""" """
if type(ips) != list: if type(ips) != list:
@ -999,7 +998,7 @@ class FloatingIPCloudMixin:
timeout=timeout, timeout=timeout,
skip_attach=skip_attach, skip_attach=skip_attach,
) )
except exc.OpenStackCloudTimeout: except exceptions.ResourceTimeout:
if self._use_neutron_floating() and created: if self._use_neutron_floating() and created:
# We are here because we created an IP on the port # We are here because we created an IP on the port
# It failed. Delete so as not to leak an unmanaged # It failed. Delete so as not to leak an unmanaged
@ -1131,7 +1130,7 @@ class FloatingIPCloudMixin:
# No floating ip network - no FIPs # No floating ip network - no FIPs
try: try:
self._get_floating_network_id() self._get_floating_network_id()
except exc.OpenStackCloudException: except exceptions.SDKException:
return False return False
(port_obj, fixed_ip_address) = self._nat_destination_port( (port_obj, fixed_ip_address) = self._nat_destination_port(
@ -1169,7 +1168,7 @@ class FloatingIPCloudMixin:
if nat_destination: if nat_destination:
nat_network = self.get_network(nat_destination) nat_network = self.get_network(nat_destination)
if not nat_network: if not nat_network:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'NAT Destination {nat_destination} was configured' 'NAT Destination {nat_destination} was configured'
' but not found on the cloud. Please check your' ' but not found on the cloud. Please check your'
' config and your cloud and try again.'.format( ' config and your cloud and try again.'.format(
@ -1180,7 +1179,7 @@ class FloatingIPCloudMixin:
nat_network = self.get_nat_destination() nat_network = self.get_nat_destination()
if not nat_network: if not nat_network:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Multiple ports were found for server {server}' 'Multiple ports were found for server {server}'
' but none of the networks are a valid NAT' ' but none of the networks are a valid NAT'
' destination, so it is impossible to add a' ' destination, so it is impossible to add a'
@ -1198,7 +1197,7 @@ class FloatingIPCloudMixin:
if maybe_port['network_id'] == nat_network['id']: if maybe_port['network_id'] == nat_network['id']:
maybe_ports.append(maybe_port) maybe_ports.append(maybe_port)
if not maybe_ports: if not maybe_ports:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'No port on server {server} was found matching' 'No port on server {server} was found matching'
' your NAT destination network {dest}. Please ' ' your NAT destination network {dest}. Please '
' check your config'.format( ' check your config'.format(
@ -1224,7 +1223,7 @@ class FloatingIPCloudMixin:
if ip.version == 4: if ip.version == 4:
fixed_address = address['ip_address'] fixed_address = address['ip_address']
return port, fixed_address return port, fixed_address
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"unable to find a free fixed IPv4 address for server " "unable to find a free fixed IPv4 address for server "
"{0}".format(server['id']) "{0}".format(server['id'])
) )

View File

@ -11,7 +11,6 @@
# limitations under the License. # limitations under the License.
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc
from openstack import exceptions from openstack import exceptions
from openstack.identity.v3._proxy import Proxy from openstack.identity.v3._proxy import Proxy
from openstack import utils from openstack import utils
@ -41,7 +40,7 @@ class IdentityCloudMixin:
# mention api versions # mention api versions
if utils.supports_version(self.identity, '3'): if utils.supports_version(self.identity, '3'):
if not domain_id: if not domain_id:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"User or project creation requires an explicit domain_id " "User or project creation requires an explicit domain_id "
"argument." "argument."
) )
@ -87,8 +86,8 @@ class IdentityCloudMixin:
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A list of identity ``Project`` objects. :returns: A list of identity ``Project`` objects.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
if not filters: if not filters:
filters = {} filters = {}
@ -154,9 +153,10 @@ class IdentityCloudMixin:
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param domain_id: Domain ID to scope the retrieved project. :param domain_id: Domain ID to scope the retrieved project.
:returns: An identity ``Project`` object. :returns: An identity ``Project`` object.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return _utils._get_entity( return _utils._get_entity(
self, 'project', name_or_id, filters, domain_id=domain_id self, 'project', name_or_id, filters, domain_id=domain_id
@ -218,9 +218,10 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the project. :param name_or_id: Name or unique ID of the project.
:param domain_id: Domain ID to scope the retrieved project. :param domain_id: Domain ID to scope the retrieved project.
:returns: True if delete succeeded, False if the project was not found. :returns: True if delete succeeded, False if the project was not found.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call wrong during the OpenStack API call
""" """
try: try:
project = self.identity.find_project( project = self.identity.find_project(
@ -245,9 +246,10 @@ class IdentityCloudMixin:
:param name: :param name:
:param domain_id: Domain ID to scope the retrieved users. :param domain_id: Domain ID to scope the retrieved users.
:returns: A list of identity ``User`` objects. :returns: A list of identity ``User`` objects.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.users(**kwargs)) return list(self.identity.users(**kwargs))
@ -273,9 +275,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A list of identity ``User`` objects :returns: A list of identity ``User`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
kwargs = {} kwargs = {}
# NOTE(jdwidari) if name_or_id isn't UUID like then make use of server- # NOTE(jdwidari) if name_or_id isn't UUID like then make use of server-
@ -312,9 +315,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: an identity ``User`` object :returns: an identity ``User`` object
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return _utils._get_entity(self, 'user', name_or_id, filters, **kwargs) return _utils._get_entity(self, 'user', name_or_id, filters, **kwargs)
@ -397,13 +401,13 @@ class IdentityCloudMixin:
def _get_user_and_group(self, user_name_or_id, group_name_or_id): def _get_user_and_group(self, user_name_or_id, group_name_or_id):
user = self.get_user(user_name_or_id) user = self.get_user(user_name_or_id)
if not user: if not user:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'User {user} not found'.format(user=user_name_or_id) 'User {user} not found'.format(user=user_name_or_id)
) )
group = self.get_group(group_name_or_id) group = self.get_group(group_name_or_id)
if not group: if not group:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Group {user} not found'.format(user=group_name_or_id) 'Group {user} not found'.format(user=group_name_or_id)
) )
@ -414,8 +418,9 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the user. :param name_or_id: Name or unique ID of the user.
:param group_name_or_id: Group name or ID :param group_name_or_id: Group name or ID
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call :raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call
""" """
user, group = self._get_user_and_group(name_or_id, group_name_or_id) user, group = self._get_user_and_group(name_or_id, group_name_or_id)
@ -426,9 +431,10 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the user. :param name_or_id: Name or unique ID of the user.
:param group_name_or_id: Group name or ID :param group_name_or_id: Group name or ID
:returns: True if user is in the group, False otherwise :returns: True if user is in the group, False otherwise
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call wrong during the OpenStack API call
""" """
user, group = self._get_user_and_group(name_or_id, group_name_or_id) user, group = self._get_user_and_group(name_or_id, group_name_or_id)
@ -439,8 +445,9 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the user. :param name_or_id: Name or unique ID of the user.
:param group_name_or_id: Group name or ID :param group_name_or_id: Group name or ID
:raises: ``OpenStackCloudException`` if something goes wrong during
the OpenStack API call :raises: :class:`~openstack.exceptions.SDKException` if something goes
wrong during the OpenStack API call
""" """
user, group = self._get_user_and_group(name_or_id, group_name_or_id) user, group = self._get_user_and_group(name_or_id, group_name_or_id)
@ -455,9 +462,10 @@ class IdentityCloudMixin:
:param service_type: Service type. (type or service_type required.) :param service_type: Service type. (type or service_type required.)
:param description: Service description (optional). :param description: Service description (optional).
:param enabled: Whether the service is enabled (v3 only) :param enabled: Whether the service is enabled (v3 only)
:returns: an identity ``Service`` object :returns: an identity ``Service`` object
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
type_ = kwargs.pop('type', None) type_ = kwargs.pop('type', None)
service_type = kwargs.pop('service_type', None) service_type = kwargs.pop('service_type', None)
@ -489,8 +497,8 @@ class IdentityCloudMixin:
"""List all Keystone services. """List all Keystone services.
:returns: A list of identity ``Service`` object :returns: A list of identity ``Service`` object
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.services()) return list(self.identity.services())
@ -515,9 +523,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a list of identity ``Service`` objects :returns: a list of identity ``Service`` objects
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
services = self.list_services() services = self.list_services()
return _utils._filter_list(services, name_or_id, filters) return _utils._filter_list(services, name_or_id, filters)
@ -527,9 +536,11 @@ class IdentityCloudMixin:
"""Get exactly one Keystone service. """Get exactly one Keystone service.
:param name_or_id: Name or unique ID of the service. :param name_or_id: Name or unique ID of the service.
:returns: an identity ``Service`` object :returns: an identity ``Service`` object
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call or if multiple matches are found. wrong during the OpenStack API call or if multiple matches are
found.
""" """
return _utils._get_entity(self, 'service', name_or_id, filters) return _utils._get_entity(self, 'service', name_or_id, filters)
@ -537,9 +548,10 @@ class IdentityCloudMixin:
"""Delete a Keystone service. """Delete a Keystone service.
:param name_or_id: Name or unique ID of the service. :param name_or_id: Name or unique ID of the service.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call wrong during the OpenStack API call
""" """
service = self.get_service(name_or_id=name_or_id) service = self.get_service(name_or_id=name_or_id)
if service is None: if service is None:
@ -575,23 +587,25 @@ class IdentityCloudMixin:
:param admin_url: Endpoint admin URL. :param admin_url: Endpoint admin URL.
:param region: Endpoint region. :param region: Endpoint region.
:param enabled: Whether the endpoint is enabled :param enabled: Whether the endpoint is enabled
:returns: A list of identity ``Endpoint`` objects :returns: A list of identity ``Endpoint`` objects
:raises: OpenStackCloudException if the service cannot be found or if :raises: :class:`~openstack.exceptions.SDKException` if the service
something goes wrong during the OpenStack API call. cannot be found or if something goes wrong during the OpenStack API
call.
""" """
public_url = kwargs.pop('public_url', None) public_url = kwargs.pop('public_url', None)
internal_url = kwargs.pop('internal_url', None) internal_url = kwargs.pop('internal_url', None)
admin_url = kwargs.pop('admin_url', None) admin_url = kwargs.pop('admin_url', None)
if (url or interface) and (public_url or internal_url or admin_url): if (url or interface) and (public_url or internal_url or admin_url):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"create_endpoint takes either url and interface OR " "create_endpoint takes either url and interface OR "
"public_url, internal_url, admin_url" "public_url, internal_url, admin_url"
) )
service = self.get_service(name_or_id=service_name_or_id) service = self.get_service(name_or_id=service_name_or_id)
if service is None: if service is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"service {service} not found".format( "service {service} not found".format(
service=service_name_or_id service=service_name_or_id
) )
@ -652,8 +666,8 @@ class IdentityCloudMixin:
"""List Keystone endpoints. """List Keystone endpoints.
:returns: A list of identity ``Endpoint`` objects :returns: A list of identity ``Endpoint`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.endpoints()) return list(self.identity.endpoints())
@ -678,9 +692,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: A list of identity ``Endpoint`` objects :returns: A list of identity ``Endpoint`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
# NOTE(SamYaple): With keystone v3 we can filter directly via the # NOTE(SamYaple): With keystone v3 we can filter directly via the
# the keystone api, but since the return of all the endpoints even in # the keystone api, but since the return of all the endpoints even in
@ -702,9 +717,10 @@ class IdentityCloudMixin:
"""Delete a Keystone endpoint. """Delete a Keystone endpoint.
:param id: ID of the endpoint to delete. :param id: ID of the endpoint to delete.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
endpoint = self.get_endpoint(id=id) endpoint = self.get_endpoint(id=id)
if endpoint is None: if endpoint is None:
@ -725,7 +741,8 @@ class IdentityCloudMixin:
:param description: A description of the domain. :param description: A description of the domain.
:param enabled: Is the domain enabled or not (default True). :param enabled: Is the domain enabled or not (default True).
:returns: The created identity ``Endpoint`` object. :returns: The created identity ``Endpoint`` object.
:raise OpenStackCloudException: if the domain cannot be created. :raises: :class:`~openstack.exceptions.SDKException` if the domain
cannot be created.
""" """
domain_ref = {'name': name, 'enabled': enabled} domain_ref = {'name': name, 'enabled': enabled}
if description is not None: if description is not None:
@ -750,16 +767,17 @@ class IdentityCloudMixin:
:param enabled: :param enabled:
:param name_or_id: Name or unique ID of the domain. :param name_or_id: Name or unique ID of the domain.
:returns: The updated identity ``Domain`` object. :returns: The updated identity ``Domain`` object.
:raise OpenStackCloudException: if the domain cannot be updated :raises: :class:`~openstack.exceptions.SDKException` if the domain
cannot be updated
""" """
if domain_id is None: if domain_id is None:
if name_or_id is None: if name_or_id is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"You must pass either domain_id or name_or_id value" "You must pass either domain_id or name_or_id value"
) )
dom = self.get_domain(None, name_or_id) dom = self.get_domain(None, name_or_id)
if dom is None: if dom is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Domain {0} not found for updating".format(name_or_id) "Domain {0} not found for updating".format(name_or_id)
) )
domain_id = dom['id'] domain_id = dom['id']
@ -777,14 +795,15 @@ class IdentityCloudMixin:
:param domain_id: ID of the domain to delete. :param domain_id: ID of the domain to delete.
:param name_or_id: Name or unique ID of the domain. :param name_or_id: Name or unique ID of the domain.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
try: try:
if domain_id is None: if domain_id is None:
if name_or_id is None: if name_or_id is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"You must pass either domain_id or name_or_id value" "You must pass either domain_id or name_or_id value"
) )
dom = self.get_domain(name_or_id=name_or_id) dom = self.get_domain(name_or_id=name_or_id)
@ -808,8 +827,8 @@ class IdentityCloudMixin:
"""List Keystone domains. """List Keystone domains.
:returns: A list of identity ``Domain`` objects. :returns: A list of identity ``Domain`` objects.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.domains(**filters)) return list(self.identity.domains(**filters))
@ -835,9 +854,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a list of identity ``Domain`` objects :returns: a list of identity ``Domain`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
if filters is None: if filters is None:
filters = {} filters = {}
@ -872,9 +892,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: an identity ``Domain`` object :returns: an identity ``Domain`` object
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
if domain_id is None: if domain_id is None:
return self.identity.find_domain(name_or_id) return self.identity.find_domain(name_or_id)
@ -886,9 +907,10 @@ class IdentityCloudMixin:
"""List Keystone groups. """List Keystone groups.
:param domain_id: Domain ID. :param domain_id: Domain ID.
:returns: A list of identity ``Group`` objects :returns: A list of identity ``Group`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.groups(**kwargs)) return list(self.identity.groups(**kwargs))
@ -915,9 +937,10 @@ class IdentityCloudMixin:
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:param domain_id: domain id. :param domain_id: domain id.
:returns: A list of identity ``Group`` objects :returns: A list of identity ``Group`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
groups = self.list_groups(**kwargs) groups = self.list_groups(**kwargs)
return _utils._filter_list(groups, name_or_id, filters) return _utils._filter_list(groups, name_or_id, filters)
@ -929,9 +952,10 @@ class IdentityCloudMixin:
"""Get exactly one Keystone group. """Get exactly one Keystone group.
:param name_or_id: Name or unique ID of the group(s). :param name_or_id: Name or unique ID of the group(s).
:returns: An identity ``Group`` object :returns: An identity ``Group`` object
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return _utils._get_entity(self, 'group', name_or_id, filters, **kwargs) return _utils._get_entity(self, 'group', name_or_id, filters, **kwargs)
@ -941,9 +965,10 @@ class IdentityCloudMixin:
:param string name: Group name. :param string name: Group name.
:param string description: Group description. :param string description: Group description.
:param string domain: Domain name or ID for the group. :param string domain: Domain name or ID for the group.
:returns: An identity ``Group`` object :returns: An identity ``Group`` object
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
group_ref = {'name': name} group_ref = {'name': name}
if description: if description:
@ -951,7 +976,7 @@ class IdentityCloudMixin:
if domain: if domain:
dom = self.get_domain(domain) dom = self.get_domain(domain)
if not dom: if not dom:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Creating group {group} failed: Invalid domain " "Creating group {group} failed: Invalid domain "
"{domain}".format(group=name, domain=domain) "{domain}".format(group=name, domain=domain)
) )
@ -973,13 +998,14 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the group. :param name_or_id: Name or unique ID of the group.
:param name: New group name. :param name: New group name.
:param description: New group description. :param description: New group description.
:returns: The updated identity ``Group`` object. :returns: The updated identity ``Group`` object.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
group = self.identity.find_group(name_or_id, **kwargs) group = self.identity.find_group(name_or_id, **kwargs)
if group is None: if group is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Group {0} not found for updating".format(name_or_id) "Group {0} not found for updating".format(name_or_id)
) )
@ -997,9 +1023,10 @@ class IdentityCloudMixin:
"""Delete a group """Delete a group
:param name_or_id: Name or unique ID of the group. :param name_or_id: Name or unique ID of the group.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
try: try:
group = self.identity.find_group(name_or_id) group = self.identity.find_group(name_or_id)
@ -1021,8 +1048,8 @@ class IdentityCloudMixin:
"""List Keystone roles. """List Keystone roles.
:returns: A list of identity ``Role`` objects :returns: A list of identity ``Role`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return list(self.identity.roles(**kwargs)) return list(self.identity.roles(**kwargs))
@ -1047,9 +1074,10 @@ class IdentityCloudMixin:
Example:: Example::
"[?last_name==`Smith`] | [?other.gender]==`Female`]" "[?last_name==`Smith`] | [?other.gender]==`Female`]"
:returns: a list of identity ``Role`` objects :returns: a list of identity ``Role`` objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
roles = self.list_roles() roles = self.list_roles()
return _utils._filter_list(roles, name_or_id, filters) return _utils._filter_list(roles, name_or_id, filters)
@ -1061,9 +1089,10 @@ class IdentityCloudMixin:
"""Get a Keystone role. """Get a Keystone role.
:param name_or_id: Name or unique ID of the role. :param name_or_id: Name or unique ID of the role.
:returns: An identity ``Role`` object if found, else None. :returns: An identity ``Role`` object if found, else None.
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
return _utils._get_entity(self, 'role', name_or_id, filters, **kwargs) return _utils._get_entity(self, 'role', name_or_id, filters, **kwargs)
@ -1120,8 +1149,8 @@ class IdentityCloudMixin:
:returns: A list of indentity :returns: A list of indentity
:class:`openstack.identity.v3.role_assignment.RoleAssignment` :class:`openstack.identity.v3.role_assignment.RoleAssignment`
objects objects
:raises: ``OpenStackCloudException``: if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
# NOTE(samueldmq): although 'include_names' is a valid query parameter # NOTE(samueldmq): although 'include_names' is a valid query parameter
# in the keystone v3 list role assignments API, it would have NO effect # in the keystone v3 list role assignments API, it would have NO effect
@ -1162,7 +1191,8 @@ class IdentityCloudMixin:
:param string name: The name of the role. :param string name: The name of the role.
:param domain_id: domain id (v3) :param domain_id: domain id (v3)
:returns: an identity ``Role`` object :returns: an identity ``Role`` object
:raise OpenStackCloudException: if the role cannot be created :raises: :class:`~openstack.exceptions.SDKException` if the role cannot
be created
""" """
kwargs['name'] = name kwargs['name'] = name
return self.identity.create_role(**kwargs) return self.identity.create_role(**kwargs)
@ -1175,7 +1205,8 @@ class IdentityCloudMixin:
:param string name: The new role name :param string name: The new role name
:param domain_id: domain id :param domain_id: domain id
:returns: an identity ``Role`` object :returns: an identity ``Role`` object
:raise OpenStackCloudException: if the role cannot be created :raises: :class:`~openstack.exceptions.SDKException` if the role cannot
be created
""" """
role = self.get_role(name_or_id, **kwargs) role = self.get_role(name_or_id, **kwargs)
if role is None: if role is None:
@ -1190,9 +1221,10 @@ class IdentityCloudMixin:
:param name_or_id: Name or unique ID of the role. :param name_or_id: Name or unique ID of the role.
:param domain_id: domain id (v3) :param domain_id: domain id (v3)
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: ``OpenStackCloudException`` if something goes wrong during :raises: :class:`~openstack.exceptions.SDKException` if something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
role = self.get_role(name_or_id, **kwargs) role = self.get_role(name_or_id, **kwargs)
if role is None: if role is None:
@ -1229,9 +1261,7 @@ class IdentityCloudMixin:
data['role'] = self.identity.find_role(name_or_id=role) data['role'] = self.identity.find_role(name_or_id=role)
if not data['role']: if not data['role']:
raise exc.OpenStackCloudException( raise exceptions.SDKException('Role {0} not found.'.format(role))
'Role {0} not found.'.format(role)
)
if user: if user:
# use cloud.get_user to save us from bad searching by name # use cloud.get_user to save us from bad searching by name
@ -1242,15 +1272,15 @@ class IdentityCloudMixin:
) )
if data.get('user') and data.get('group'): if data.get('user') and data.get('group'):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Specify either a group or a user, not both' 'Specify either a group or a user, not both'
) )
if data.get('user') is None and data.get('group') is None: if data.get('user') is None and data.get('group') is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Must specify either a user or a group' 'Must specify either a user or a group'
) )
if project is None and domain is None and system is None: if project is None and domain is None and system is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Must specify either a domain, project or system' 'Must specify either a domain, project or system'
) )
@ -1293,8 +1323,8 @@ class IdentityCloudMixin:
NOTE: precedence is given first to project, then domain, then system NOTE: precedence is given first to project, then domain, then system
:returns: True if the role is assigned, otherwise False :returns: True if the role is assigned, otherwise False
:raises: :class:`~openstack.exceptions.SDKException` if the role cannot
:raise OpenStackCloudException: if the role cannot be granted be granted
""" """
data = self._get_grant_revoke_params( data = self._get_grant_revoke_params(
name_or_id, name_or_id,
@ -1401,8 +1431,8 @@ class IdentityCloudMixin:
NOTE: precedence is given first to project, then domain, then system NOTE: precedence is given first to project, then domain, then system
:returns: True if the role is revoke, otherwise False :returns: True if the role is revoke, otherwise False
:raises: :class:`~openstack.exceptions.SDKException` if the role cannot
:raise OpenStackCloudException: if the role cannot be removed be removed
""" """
data = self._get_grant_revoke_params( data = self._get_grant_revoke_params(
name_or_id, name_or_id,

View File

@ -11,7 +11,7 @@
# limitations under the License. # limitations under the License.
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc from openstack import exceptions
from openstack.image.v2._proxy import Proxy from openstack.image.v2._proxy import Proxy
from openstack import utils from openstack import utils
@ -104,30 +104,32 @@ class ImageCloudMixin:
this or output_path must be specified this or output_path must be specified
:param int chunk_size: size in bytes to read from the wire and buffer :param int chunk_size: size in bytes to read from the wire and buffer
at one time. Defaults to 1024 * 1024 = 1 MiB at one time. Defaults to 1024 * 1024 = 1 MiB
:returns: When output_path and output_file are not given - the bytes :returns: When output_path and output_file are not given - the bytes
comprising the given Image when stream is False, otherwise a comprising the given Image when stream is False, otherwise a
:class:`requests.Response` instance. When output_path or :class:`requests.Response` instance. When output_path or
output_file are given - an image output_file are given - an image
:class:`~openstack.image.v2.image.Image` instance. :class:`~openstack.image.v2.image.Image` instance.
:raises: OpenStackCloudException in the event download_image is called :raises: :class:`~openstack.exceptions.SDKException` in the event
without exactly one of either output_path or output_file download_image is called without exactly one of either output_path
:raises: OpenStackCloudResourceNotFound if no images are found matching or output_file
the name or ID provided :raises: :class:`~openstack.exceptions.BadRequestException` if no
images are found matching the name or ID provided
""" """
if output_path is None and output_file is None: if output_path is None and output_file is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'No output specified, an output path or file object' 'No output specified, an output path or file object'
' is necessary to write the image data to' ' is necessary to write the image data to'
) )
elif output_path is not None and output_file is not None: elif output_path is not None and output_file is not None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Both an output path and file object were provided,' 'Both an output path and file object were provided,'
' however only one can be used at once' ' however only one can be used at once'
) )
image = self.image.find_image(name_or_id) image = self.image.find_image(name_or_id)
if not image: if not image:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"No images with name or ID %s were found" % name_or_id, None "No images with name or ID %s were found" % name_or_id, None
) )
@ -167,7 +169,7 @@ class ImageCloudMixin:
if image['status'] == 'active': if image['status'] == 'active':
return image return image
elif image['status'] == 'error': elif image['status'] == 'error':
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Image {image} hit error state'.format(image=image_id) 'Image {image} hit error state'.format(image=image_id)
) )
@ -186,8 +188,8 @@ class ImageCloudMixin:
:param delete_objects: If True, also deletes uploaded swift objects. :param delete_objects: If True, also deletes uploaded swift objects.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` if there are
:raises: OpenStackCloudException if there are problems deleting. problems deleting.
""" """
image = self.get_image(name_or_id) image = self.get_image(name_or_id)
if not image: if not image:
@ -279,7 +281,8 @@ class ImageCloudMixin:
If a value is in meta and kwargs, meta wins. If a value is in meta and kwargs, meta wins.
:returns: An image :class:`openstack.image.v2.image.Image` object. :returns: An image :class:`openstack.image.v2.image.Image` object.
:raises: OpenStackCloudException if there are problems uploading :raises: :class:`~openstack.exceptions.SDKException` if there are
problems uploading
""" """
if volume: if volume:
image = self.block_storage.create_image( image = self.block_storage.create_image(
@ -319,7 +322,7 @@ class ImageCloudMixin:
image_obj = self.get_image(image.id) image_obj = self.get_image(image.id)
if image_obj and image_obj.status not in ('queued', 'saving'): if image_obj and image_obj.status not in ('queued', 'saving'):
return image_obj return image_obj
except exc.OpenStackCloudTimeout: except exceptions.ResourceTimeout:
self.log.debug( self.log.debug(
"Timeout waiting for image to become ready. Deleting." "Timeout waiting for image to become ready. Deleting."
) )

View File

@ -35,10 +35,11 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the desired network. :param name_or_id: Name or ID of the desired network.
:param filters: A dict containing additional filters to use. e.g. :param filters: A dict containing additional filters to use. e.g.
{'router:external': True} {'router:external': True}
:returns: A list of network ``Network`` objects matching the search :returns: A list of network ``Network`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
query = {} query = {}
if name_or_id: if name_or_id:
@ -54,10 +55,11 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the desired router. :param name_or_id: Name or ID of the desired router.
:param filters: A dict containing additional filters to use. e.g. :param filters: A dict containing additional filters to use. e.g.
{'admin_state_up': True} {'admin_state_up': True}
:returns: A list of network ``Router`` objects matching the search :returns: A list of network ``Router`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
query = {} query = {}
if name_or_id: if name_or_id:
@ -73,10 +75,11 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the desired subnet. :param name_or_id: Name or ID of the desired subnet.
:param filters: A dict containing additional filters to use. e.g. :param filters: A dict containing additional filters to use. e.g.
{'enable_dhcp': True} {'enable_dhcp': True}
:returns: A list of network ``Subnet`` objects matching the search :returns: A list of network ``Subnet`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
query = {} query = {}
if name_or_id: if name_or_id:
@ -92,10 +95,11 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the desired port. :param name_or_id: Name or ID of the desired port.
:param filters: A dict containing additional filters to use. e.g. :param filters: A dict containing additional filters to use. e.g.
{'device_id': '2711c67a-b4a7-43dd-ace7-6187b791c3f0'} {'device_id': '2711c67a-b4a7-43dd-ace7-6187b791c3f0'}
:returns: A list of network ``Port`` objects matching the search :returns: A list of network ``Port`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
# If the filter is a string, do not push the filter down to neutron; # If the filter is a string, do not push the filter down to neutron;
# get all the ports and filter locally. # get all the ports and filter locally.
@ -208,10 +212,11 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the desired policy. :param name_or_id: Name or ID of the desired policy.
:param filters: a dict containing additional filters to use. e.g. :param filters: a dict containing additional filters to use. e.g.
{'shared': True} {'shared': True}
:returns: A list of network ``QosPolicy`` objects matching the search :returns: A list of network ``QosPolicy`` objects matching the search
criteria. criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -467,7 +472,8 @@ class NetworkCloudMixin:
:param string dns_domain: Specify the DNS domain associated with :param string dns_domain: Specify the DNS domain associated with
this network. this network.
:returns: The created network ``Network`` object. :returns: The created network ``Network`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
network = { network = {
'name': name, 'name': name,
@ -482,7 +488,7 @@ class NetworkCloudMixin:
if availability_zone_hints is not None: if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list): if not isinstance(availability_zone_hints, list):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'availability_zone_hints' must be a list" "Parameter 'availability_zone_hints' must be a list"
) )
if not self._has_neutron_extension('network_availability_zone'): if not self._has_neutron_extension('network_availability_zone'):
@ -494,7 +500,7 @@ class NetworkCloudMixin:
if provider: if provider:
if not isinstance(provider, dict): if not isinstance(provider, dict):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'provider' must be a dict" "Parameter 'provider' must be a dict"
) )
# Only pass what we know # Only pass what we know
@ -515,18 +521,18 @@ class NetworkCloudMixin:
if port_security_enabled is not None: if port_security_enabled is not None:
if not isinstance(port_security_enabled, bool): if not isinstance(port_security_enabled, bool):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'port_security_enabled' must be a bool" "Parameter 'port_security_enabled' must be a bool"
) )
network['port_security_enabled'] = port_security_enabled network['port_security_enabled'] = port_security_enabled
if mtu_size: if mtu_size:
if not isinstance(mtu_size, int): if not isinstance(mtu_size, int):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'mtu_size' must be an integer." "Parameter 'mtu_size' must be an integer."
) )
if not mtu_size >= 68: if not mtu_size >= 68:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'mtu_size' must be greater than 67." "Parameter 'mtu_size' must be greater than 67."
) )
@ -568,13 +574,15 @@ class NetworkCloudMixin:
:param bool port_security_enabled: Enable or disable port security. :param bool port_security_enabled: Enable or disable port security.
:param string dns_domain: Specify the DNS domain associated with :param string dns_domain: Specify the DNS domain associated with
this network. this network.
:returns: The updated network ``Network`` object. :returns: The updated network ``Network`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
provider = kwargs.pop('provider', None) provider = kwargs.pop('provider', None)
if provider: if provider:
if not isinstance(provider, dict): if not isinstance(provider, dict):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'provider' must be a dict" "Parameter 'provider' must be a dict"
) )
for key in ('physical_network', 'network_type', 'segmentation_id'): for key in ('physical_network', 'network_type', 'segmentation_id'):
@ -586,26 +594,24 @@ class NetworkCloudMixin:
if 'port_security_enabled' in kwargs: if 'port_security_enabled' in kwargs:
if not isinstance(kwargs['port_security_enabled'], bool): if not isinstance(kwargs['port_security_enabled'], bool):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'port_security_enabled' must be a bool" "Parameter 'port_security_enabled' must be a bool"
) )
if 'mtu_size' in kwargs: if 'mtu_size' in kwargs:
if not isinstance(kwargs['mtu_size'], int): if not isinstance(kwargs['mtu_size'], int):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'mtu_size' must be an integer." "Parameter 'mtu_size' must be an integer."
) )
if kwargs['mtu_size'] < 68: if kwargs['mtu_size'] < 68:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'mtu_size' must be greater than 67." "Parameter 'mtu_size' must be greater than 67."
) )
kwargs['mtu'] = kwargs.pop('mtu_size') kwargs['mtu'] = kwargs.pop('mtu_size')
network = self.get_network(name_or_id) network = self.get_network(name_or_id)
if not network: if not network:
raise exc.OpenStackCloudException( raise exceptions.SDKException("Network %s not found." % name_or_id)
"Network %s not found." % name_or_id
)
network = self.network.update_network(network, **kwargs) network = self.network.update_network(network, **kwargs)
@ -619,8 +625,8 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the network being deleted. :param name_or_id: Name or ID of the network being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
network = self.get_network(name_or_id) network = self.get_network(name_or_id)
if not network: if not network:
@ -640,13 +646,13 @@ class NetworkCloudMixin:
:param name_or_id: project name or id :param name_or_id: project name or id
:param kwargs: key/value pairs of quota name and quota value :param kwargs: key/value pairs of quota name and quota value
:raises: OpenStackCloudException if the resource to set the :raises: :class:`~openstack.exceptions.SDKException` if the resource to
quota does not exist. set the quota does not exist.
""" """
proj = self.get_project(name_or_id) proj = self.get_project(name_or_id)
if not proj: if not proj:
raise exc.OpenStackCloudException("project does not exist") raise exceptions.SDKException("project does not exist")
self.network.update_quota(proj.id, **kwargs) self.network.update_quota(proj.id, **kwargs)
@ -656,8 +662,10 @@ class NetworkCloudMixin:
:param name_or_id: project name or id :param name_or_id: project name or id
:param details: if set to True it will return details about usage :param details: if set to True it will return details about usage
of quotas by given project of quotas by given project
:raises: OpenStackCloudException if it's not a valid project
:returns: A network ``Quota`` object if found, else None. :returns: A network ``Quota`` object if found, else None.
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project
""" """
proj = self.identity.find_project(name_or_id, ignore_missing=False) proj = self.identity.find_project(name_or_id, ignore_missing=False)
return self.network.get_quota(proj.id, details) return self.network.get_quota(proj.id, details)
@ -673,14 +681,14 @@ class NetworkCloudMixin:
"""Delete network quotas for a project """Delete network quotas for a project
:param name_or_id: project name or id :param name_or_id: project name or id
:raises: OpenStackCloudException if it's not a valid project or the
network client call failed
:returns: dict with the quotas :returns: dict with the quotas
:raises: :class:`~openstack.exceptions.SDKException` if it's not a
valid project or the network client call failed
""" """
proj = self.get_project(name_or_id) proj = self.get_project(name_or_id)
if not proj: if not proj:
raise exc.OpenStackCloudException("project does not exist") raise exceptions.SDKException("project does not exist")
self.network.delete_quota(proj.id) self.network.delete_quota(proj.id)
@_utils.valid_kwargs( @_utils.valid_kwargs(
@ -1348,8 +1356,10 @@ class NetworkCloudMixin:
:param bool default: Set the QoS policy as default for project. :param bool default: Set the QoS policy as default for project.
:param string project_id: Specify the project ID this QoS policy :param string project_id: Specify the project ID this QoS policy
will be created on (admin-only). will be created on (admin-only).
:returns: The created network ``QosPolicy`` object. :returns: The created network ``QosPolicy`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1380,8 +1390,10 @@ class NetworkCloudMixin:
:param bool shared: If True, the QoS policy will be set as shared. :param bool shared: If True, the QoS policy will be set as shared.
:param bool default: If True, the QoS policy will be set as default for :param bool default: If True, the QoS policy will be set as default for
project. project.
:returns: The updated network ``QosPolicyRule`` object. :returns: The updated network ``QosPolicyRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1404,7 +1416,7 @@ class NetworkCloudMixin:
curr_policy = self.network.find_qos_policy(name_or_id) curr_policy = self.network.find_qos_policy(name_or_id)
if not curr_policy: if not curr_policy:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"QoS policy %s not found." % name_or_id "QoS policy %s not found." % name_or_id
) )
@ -1416,8 +1428,8 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the policy being deleted. :param name_or_id: Name or ID of the policy being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1446,10 +1458,11 @@ class NetworkCloudMixin:
:param string rule_id: ID of searched rule. :param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g. :param filters: a dict containing additional filters to use. e.g.
{'max_kbps': 1000} {'max_kbps': 1000}
:returns: A list of network ``QoSBandwidthLimitRule`` objects matching :returns: A list of network ``QoSBandwidthLimitRule`` objects matching
the search criteria. the search criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
rules = self.list_qos_bandwidth_limit_rules(policy_name_or_id, filters) rules = self.list_qos_bandwidth_limit_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters) return _utils._filter_list(rules, rule_id, filters)
@ -1461,8 +1474,8 @@ class NetworkCloudMixin:
from rules should be listed. from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down :param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSBandwidthLimitRule`` objects. :returns: A list of network ``QoSBandwidthLimitRule`` objects.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be :raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
found. policy will not be found.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1471,7 +1484,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1503,7 +1516,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1527,8 +1540,10 @@ class NetworkCloudMixin:
:param int max_burst_kbps: Maximum burst value (in kilobits). :param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress. :param string direction: Ingress or egress.
The direction in which the traffic will be limited. The direction in which the traffic will be limited.
:returns: The created network ``QoSBandwidthLimitRule`` object. :returns: The created network ``QoSBandwidthLimitRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1537,7 +1552,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1569,8 +1584,10 @@ class NetworkCloudMixin:
:param int max_burst_kbps: Maximum burst value (in kilobits). :param int max_burst_kbps: Maximum burst value (in kilobits).
:param string direction: Ingress or egress. :param string direction: Ingress or egress.
The direction in which the traffic will be limited. The direction in which the traffic will be limited.
:returns: The updated network ``QoSBandwidthLimitRule`` object. :returns: The updated network ``QoSBandwidthLimitRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1581,7 +1598,7 @@ class NetworkCloudMixin:
policy_name_or_id, ignore_missing=True policy_name_or_id, ignore_missing=True
) )
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1603,7 +1620,7 @@ class NetworkCloudMixin:
qos_rule=rule_id, qos_policy=policy qos_rule=rule_id, qos_policy=policy
) )
if not curr_rule: if not curr_rule:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"QoS bandwidth_limit_rule {rule_id} not found in policy " "QoS bandwidth_limit_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id']) "{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
) )
@ -1619,7 +1636,8 @@ class NetworkCloudMixin:
rule is associated. rule is associated.
:param string rule_id: ID of rule to update. :param string rule_id: ID of rule to update.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1628,7 +1646,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1663,10 +1681,11 @@ class NetworkCloudMixin:
:param string rule_id: ID of searched rule. :param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g. :param filters: a dict containing additional filters to use. e.g.
{'dscp_mark': 32} {'dscp_mark': 32}
:returns: A list of network ``QoSDSCPMarkingRule`` objects matching the :returns: A list of network ``QoSDSCPMarkingRule`` objects matching the
search criteria. search criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
rules = self.list_qos_dscp_marking_rules(policy_name_or_id, filters) rules = self.list_qos_dscp_marking_rules(policy_name_or_id, filters)
return _utils._filter_list(rules, rule_id, filters) return _utils._filter_list(rules, rule_id, filters)
@ -1678,8 +1697,8 @@ class NetworkCloudMixin:
from rules should be listed. from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down :param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSDSCPMarkingRule`` objects. :returns: A list of network ``QoSDSCPMarkingRule`` objects.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be :raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
found. policy will not be found.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1690,7 +1709,7 @@ class NetworkCloudMixin:
policy_name_or_id, ignore_missing=True policy_name_or_id, ignore_missing=True
) )
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1717,7 +1736,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1735,8 +1754,10 @@ class NetworkCloudMixin:
:param string policy_name_or_id: Name or ID of the QoS policy to which :param string policy_name_or_id: Name or ID of the QoS policy to which
rule should be associated. rule should be associated.
:param int dscp_mark: DSCP mark value :param int dscp_mark: DSCP mark value
:returns: The created network ``QoSDSCPMarkingRule`` object. :returns: The created network ``QoSDSCPMarkingRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1745,7 +1766,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1765,8 +1786,10 @@ class NetworkCloudMixin:
rule is associated. rule is associated.
:param string rule_id: ID of rule to update. :param string rule_id: ID of rule to update.
:param int dscp_mark: DSCP mark value :param int dscp_mark: DSCP mark value
:returns: The updated network ``QoSDSCPMarkingRule`` object. :returns: The updated network ``QoSDSCPMarkingRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1775,7 +1798,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1787,7 +1810,7 @@ class NetworkCloudMixin:
curr_rule = self.network.get_qos_dscp_marking_rule(rule_id, policy) curr_rule = self.network.get_qos_dscp_marking_rule(rule_id, policy)
if not curr_rule: if not curr_rule:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"QoS dscp_marking_rule {rule_id} not found in policy " "QoS dscp_marking_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id']) "{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
) )
@ -1803,7 +1826,8 @@ class NetworkCloudMixin:
rule is associated. rule is associated.
:param string rule_id: ID of rule to update. :param string rule_id: ID of rule to update.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1812,7 +1836,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1847,10 +1871,11 @@ class NetworkCloudMixin:
:param string rule_id: ID of searched rule. :param string rule_id: ID of searched rule.
:param filters: a dict containing additional filters to use. e.g. :param filters: a dict containing additional filters to use. e.g.
{'min_kbps': 1000} {'min_kbps': 1000}
:returns: A list of network ``QoSMinimumBandwidthRule`` objects :returns: A list of network ``QoSMinimumBandwidthRule`` objects
matching the search criteria. matching the search criteria.
:raises: ``OpenStackCloudException`` if something goes wrong during the :raises: :class:`~openstack.exceptions.SDKException` if something goes
OpenStack API call. wrong during the OpenStack API call.
""" """
rules = self.list_qos_minimum_bandwidth_rules( rules = self.list_qos_minimum_bandwidth_rules(
policy_name_or_id, filters policy_name_or_id, filters
@ -1866,8 +1891,8 @@ class NetworkCloudMixin:
from rules should be listed. from rules should be listed.
:param filters: (optional) A dict of filter conditions to push down :param filters: (optional) A dict of filter conditions to push down
:returns: A list of network ``QoSMinimumBandwidthRule`` objects. :returns: A list of network ``QoSMinimumBandwidthRule`` objects.
:raises: ``OpenStackCloudResourceNotFound`` if QoS policy will not be :raises: ``:class:`~openstack.exceptions.BadRequestException``` if QoS
found. policy will not be found.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1876,7 +1901,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1906,7 +1931,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1928,8 +1953,10 @@ class NetworkCloudMixin:
:param int min_kbps: Minimum bandwidth value (in kilobits per second). :param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress. :param string direction: Ingress or egress.
The direction in which the traffic will be available. The direction in which the traffic will be available.
:returns: The created network ``QoSMinimumBandwidthRule`` object. :returns: The created network ``QoSMinimumBandwidthRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1938,7 +1965,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1960,8 +1987,10 @@ class NetworkCloudMixin:
:param int min_kbps: Minimum bandwidth value (in kilobits per second). :param int min_kbps: Minimum bandwidth value (in kilobits per second).
:param string direction: Ingress or egress. :param string direction: Ingress or egress.
The direction in which the traffic will be available. The direction in which the traffic will be available.
:returns: The updated network ``QoSMinimumBandwidthRule`` object. :returns: The updated network ``QoSMinimumBandwidthRule`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -1970,7 +1999,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -1984,7 +2013,7 @@ class NetworkCloudMixin:
rule_id, policy rule_id, policy
) )
if not curr_rule: if not curr_rule:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"QoS minimum_bandwidth_rule {rule_id} not found in policy " "QoS minimum_bandwidth_rule {rule_id} not found in policy "
"{policy_id}".format(rule_id=rule_id, policy_id=policy['id']) "{policy_id}".format(rule_id=rule_id, policy_id=policy['id'])
) )
@ -2000,7 +2029,8 @@ class NetworkCloudMixin:
rule is associated. rule is associated.
:param string rule_id: ID of rule to delete. :param string rule_id: ID of rule to delete.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if not self._has_neutron_extension('qos'): if not self._has_neutron_extension('qos'):
raise exc.OpenStackCloudUnavailableExtension( raise exc.OpenStackCloudUnavailableExtension(
@ -2009,7 +2039,7 @@ class NetworkCloudMixin:
policy = self.network.find_qos_policy(policy_name_or_id) policy = self.network.find_qos_policy(policy_name_or_id)
if not policy: if not policy:
raise exc.OpenStackCloudResourceNotFound( raise exceptions.NotFoundException(
"QoS policy {name_or_id} not Found.".format( "QoS policy {name_or_id} not Found.".format(
name_or_id=policy_name_or_id name_or_id=policy_name_or_id
) )
@ -2039,8 +2069,10 @@ class NetworkCloudMixin:
:param dict router: The dict object of the router being changed :param dict router: The dict object of the router being changed
:param string subnet_id: The ID of the subnet to use for the interface :param string subnet_id: The ID of the subnet to use for the interface
:param string port_id: The ID of the port to use for the interface :param string port_id: The ID of the port to use for the interface
:returns: The raw response body from the request. :returns: The raw response body from the request.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return self.network.add_interface_to_router( return self.network.add_interface_to_router(
router=router, subnet_id=subnet_id, port_id=port_id router=router, subnet_id=subnet_id, port_id=port_id
@ -2060,8 +2092,8 @@ class NetworkCloudMixin:
:param string port_id: The ID of the port to use for the interface :param string port_id: The ID of the port to use for the interface
:returns: None on success :returns: None on success
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
if not subnet_id and not port_id: if not subnet_id and not port_id:
raise ValueError( raise ValueError(
@ -2141,10 +2173,12 @@ class NetworkCloudMixin:
] ]
:param string project_id: Project ID for the router. :param string project_id: Project ID for the router.
:param types.ListType availability_zone_hints: :param types.ListType availability_zone_hints: A list of availability
A list of availability zone hints. zone hints.
:returns: The created network ``Router`` object. :returns: The created network ``Router`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
router = {'admin_state_up': admin_state_up} router = {'admin_state_up': admin_state_up}
if project_id is not None: if project_id is not None:
@ -2158,7 +2192,7 @@ class NetworkCloudMixin:
router['external_gateway_info'] = ext_gw_info router['external_gateway_info'] = ext_gw_info
if availability_zone_hints is not None: if availability_zone_hints is not None:
if not isinstance(availability_zone_hints, list): if not isinstance(availability_zone_hints, list):
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Parameter 'availability_zone_hints' must be a list" "Parameter 'availability_zone_hints' must be a list"
) )
if not self._has_neutron_extension('router_availability_zone'): if not self._has_neutron_extension('router_availability_zone'):
@ -2213,7 +2247,8 @@ class NetworkCloudMixin:
] ]
:returns: The updated network ``Router`` object. :returns: The updated network ``Router`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
router = {} router = {}
if name: if name:
@ -2240,9 +2275,7 @@ class NetworkCloudMixin:
curr_router = self.get_router(name_or_id) curr_router = self.get_router(name_or_id)
if not curr_router: if not curr_router:
raise exc.OpenStackCloudException( raise exceptions.SDKException("Router %s not found." % name_or_id)
"Router %s not found." % name_or_id
)
return self.network.update_router(curr_router, **router) return self.network.update_router(curr_router, **router)
@ -2256,8 +2289,8 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the router being deleted. :param name_or_id: Name or ID of the router being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
router = self.network.find_router(name_or_id, ignore_missing=True) router = self.network.find_router(name_or_id, ignore_missing=True)
if not router: if not router:
@ -2352,8 +2385,10 @@ class NetworkCloudMixin:
``use_default_subnetpool`` and ``subnetpool_name_or_id`` may be ``use_default_subnetpool`` and ``subnetpool_name_or_id`` may be
specified at the same time. specified at the same time.
:param kwargs: Key value pairs to be passed to the Neutron API. :param kwargs: Key value pairs to be passed to the Neutron API.
:returns: The created network ``Subnet`` object. :returns: The created network ``Subnet`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
if tenant_id is not None: if tenant_id is not None:
@ -2363,28 +2398,28 @@ class NetworkCloudMixin:
network = self.get_network(network_name_or_id, filters) network = self.get_network(network_name_or_id, filters)
if not network: if not network:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Network %s not found." % network_name_or_id "Network %s not found." % network_name_or_id
) )
if disable_gateway_ip and gateway_ip: if disable_gateway_ip and gateway_ip:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip' 'arg:disable_gateway_ip is not allowed with arg:gateway_ip'
) )
uses_subnetpool = use_default_subnetpool or subnetpool_name_or_id uses_subnetpool = use_default_subnetpool or subnetpool_name_or_id
if not cidr and not uses_subnetpool: if not cidr and not uses_subnetpool:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'arg:cidr is required when a subnetpool is not used' 'arg:cidr is required when a subnetpool is not used'
) )
if cidr and uses_subnetpool: if cidr and uses_subnetpool:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'arg:cidr and subnetpool may not be used at the same time' 'arg:cidr and subnetpool may not be used at the same time'
) )
if use_default_subnetpool and subnetpool_name_or_id: if use_default_subnetpool and subnetpool_name_or_id:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'arg:use_default_subnetpool and arg:subnetpool_id may not be ' 'arg:use_default_subnetpool and arg:subnetpool_id may not be '
'used at the same time' 'used at the same time'
) )
@ -2393,7 +2428,7 @@ class NetworkCloudMixin:
if subnetpool_name_or_id: if subnetpool_name_or_id:
subnetpool = self.get_subnetpool(subnetpool_name_or_id) subnetpool = self.get_subnetpool(subnetpool_name_or_id)
if not subnetpool: if not subnetpool:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Subnetpool %s not found." % subnetpool_name_or_id "Subnetpool %s not found." % subnetpool_name_or_id
) )
@ -2402,9 +2437,7 @@ class NetworkCloudMixin:
try: try:
ip_version = int(ip_version) ip_version = int(ip_version)
except ValueError: except ValueError:
raise exc.OpenStackCloudException( raise exceptions.SDKException('ip_version must be an integer')
'ip_version must be an integer'
)
# The body of the neutron message for the subnet we wish to create. # The body of the neutron message for the subnet we wish to create.
# This includes attributes that are required or have defaults. # This includes attributes that are required or have defaults.
@ -2457,8 +2490,8 @@ class NetworkCloudMixin:
:param name_or_id: Name or ID of the subnet being deleted. :param name_or_id: Name or ID of the subnet being deleted.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
subnet = self.network.find_subnet(name_or_id, ignore_missing=True) subnet = self.network.find_subnet(name_or_id, ignore_missing=True)
if not subnet: if not subnet:
@ -2522,7 +2555,8 @@ class NetworkCloudMixin:
] ]
:returns: The updated network ``Subnet`` object. :returns: The updated network ``Subnet`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
subnet = {} subnet = {}
if subnet_name: if subnet_name:
@ -2545,15 +2579,13 @@ class NetworkCloudMixin:
return return
if disable_gateway_ip and gateway_ip: if disable_gateway_ip and gateway_ip:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'arg:disable_gateway_ip is not allowed with arg:gateway_ip' 'arg:disable_gateway_ip is not allowed with arg:gateway_ip'
) )
curr_subnet = self.get_subnet(name_or_id) curr_subnet = self.get_subnet(name_or_id)
if not curr_subnet: if not curr_subnet:
raise exc.OpenStackCloudException( raise exceptions.SDKException("Subnet %s not found." % name_or_id)
"Subnet %s not found." % name_or_id
)
return self.network.update_subnet(curr_subnet, **subnet) return self.network.update_subnet(curr_subnet, **subnet)
@ -2647,8 +2679,10 @@ class NetworkCloudMixin:
be propagated. (Optional) be propagated. (Optional)
:param mac_learning_enabled: If mac learning should be enabled on the :param mac_learning_enabled: If mac learning should be enabled on the
port. (Optional) port. (Optional)
:returns: The created network ``Port`` object. :returns: The created network ``Port`` object.
:raises: ``OpenStackCloudException`` on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
kwargs['network_id'] = network_id kwargs['network_id'] = network_id
@ -2721,12 +2755,14 @@ class NetworkCloudMixin:
:param port_security_enabled: The security port state created on :param port_security_enabled: The security port state created on
the network. (Optional) the network. (Optional)
:param qos_policy_id: The ID of the QoS policy to apply for port. :param qos_policy_id: The ID of the QoS policy to apply for port.
:returns: The updated network ``Port`` object. :returns: The updated network ``Port`` object.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
port = self.get_port(name_or_id=name_or_id) port = self.get_port(name_or_id=name_or_id)
if port is None: if port is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"failed to find port '{port}'".format(port=name_or_id) "failed to find port '{port}'".format(port=name_or_id)
) )
@ -2738,8 +2774,8 @@ class NetworkCloudMixin:
:param name_or_id: ID or name of the port to delete. :param name_or_id: ID or name of the port to delete.
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
port = self.network.find_port(name_or_id) port = self.network.find_port(name_or_id)

View File

@ -12,7 +12,7 @@
import threading import threading
from openstack.cloud import exc from openstack import exceptions
class NetworkCommonCloudMixin: class NetworkCommonCloudMixin:
@ -81,7 +81,7 @@ class NetworkCommonCloudMixin:
# though, that's fine, clearly the neutron introspection is # though, that's fine, clearly the neutron introspection is
# not going to work. # not going to work.
all_networks = self.list_networks() all_networks = self.list_networks()
except exc.OpenStackCloudException: except exceptions.SDKException:
self._network_list_stamp = True self._network_list_stamp = True
return return
@ -145,7 +145,7 @@ class NetworkCommonCloudMixin:
# External Floating IPv4 networks # External Floating IPv4 networks
if self._nat_source in (network['name'], network['id']): if self._nat_source in (network['name'], network['id']):
if nat_source: if nat_source:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Multiple networks were found matching' 'Multiple networks were found matching'
' {nat_net} which is the network configured' ' {nat_net} which is the network configured'
' to be the NAT source. Please check your' ' to be the NAT source. Please check your'
@ -163,7 +163,7 @@ class NetworkCommonCloudMixin:
# NAT Destination # NAT Destination
if self._nat_destination in (network['name'], network['id']): if self._nat_destination in (network['name'], network['id']):
if nat_destination: if nat_destination:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Multiple networks were found matching' 'Multiple networks were found matching'
' {nat_net} which is the network configured' ' {nat_net} which is the network configured'
' to be the NAT destination. Please check your' ' to be the NAT destination. Please check your'
@ -180,7 +180,7 @@ class NetworkCommonCloudMixin:
if all_subnets is None: if all_subnets is None:
try: try:
all_subnets = self.list_subnets() all_subnets = self.list_subnets()
except exc.OpenStackCloudException: except exceptions.SDKException:
# Thanks Rackspace broken neutron # Thanks Rackspace broken neutron
all_subnets = [] all_subnets = []
@ -198,7 +198,7 @@ class NetworkCommonCloudMixin:
# Default network # Default network
if self._default_network in (network['name'], network['id']): if self._default_network in (network['name'], network['id']):
if default_network: if default_network:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Multiple networks were found matching' 'Multiple networks were found matching'
' {default_net} which is the network' ' {default_net} which is the network'
' configured to be the default interface' ' configured to be the default interface'
@ -212,7 +212,7 @@ class NetworkCommonCloudMixin:
# Validate config vs. reality # Validate config vs. reality
for net_name in self._external_ipv4_names: for net_name in self._external_ipv4_names:
if net_name not in [net['name'] for net in external_ipv4_networks]: if net_name not in [net['name'] for net in external_ipv4_networks]:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Networks: {network} was provided for external IPv4" "Networks: {network} was provided for external IPv4"
" access and those networks could not be found".format( " access and those networks could not be found".format(
network=net_name network=net_name
@ -221,7 +221,7 @@ class NetworkCommonCloudMixin:
for net_name in self._internal_ipv4_names: for net_name in self._internal_ipv4_names:
if net_name not in [net['name'] for net in internal_ipv4_networks]: if net_name not in [net['name'] for net in internal_ipv4_networks]:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Networks: {network} was provided for internal IPv4" "Networks: {network} was provided for internal IPv4"
" access and those networks could not be found".format( " access and those networks could not be found".format(
network=net_name network=net_name
@ -230,7 +230,7 @@ class NetworkCommonCloudMixin:
for net_name in self._external_ipv6_names: for net_name in self._external_ipv6_names:
if net_name not in [net['name'] for net in external_ipv6_networks]: if net_name not in [net['name'] for net in external_ipv6_networks]:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Networks: {network} was provided for external IPv6" "Networks: {network} was provided for external IPv6"
" access and those networks could not be found".format( " access and those networks could not be found".format(
network=net_name network=net_name
@ -239,7 +239,7 @@ class NetworkCommonCloudMixin:
for net_name in self._internal_ipv6_names: for net_name in self._internal_ipv6_names:
if net_name not in [net['name'] for net in internal_ipv6_networks]: if net_name not in [net['name'] for net in internal_ipv6_networks]:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Networks: {network} was provided for internal IPv6" "Networks: {network} was provided for internal IPv6"
" access and those networks could not be found".format( " access and those networks could not be found".format(
network=net_name network=net_name
@ -247,21 +247,21 @@ class NetworkCommonCloudMixin:
) )
if self._nat_destination and not nat_destination: if self._nat_destination and not nat_destination:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Network {network} was configured to be the' 'Network {network} was configured to be the'
' destination for inbound NAT but it could not be' ' destination for inbound NAT but it could not be'
' found'.format(network=self._nat_destination) ' found'.format(network=self._nat_destination)
) )
if self._nat_source and not nat_source: if self._nat_source and not nat_source:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Network {network} was configured to be the' 'Network {network} was configured to be the'
' source for inbound NAT but it could not be' ' source for inbound NAT but it could not be'
' found'.format(network=self._nat_source) ' found'.format(network=self._nat_source)
) )
if self._default_network and not default_network: if self._default_network and not default_network:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Network {network} was configured to be the' 'Network {network} was configured to be the'
' default network interface but it could not be' ' default network interface but it could not be'
' found'.format(network=self._default_network) ' found'.format(network=self._default_network)

View File

@ -16,7 +16,6 @@ import urllib.parse
import keystoneauth1.exceptions import keystoneauth1.exceptions
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc
from openstack import exceptions from openstack import exceptions
from openstack.object_store.v1._proxy import Proxy from openstack.object_store.v1._proxy import Proxy
@ -42,7 +41,8 @@ class ObjectStoreCloudMixin:
:param prefix: Only objects with this prefix will be returned. :param prefix: Only objects with this prefix will be returned.
(optional) (optional)
:returns: A list of object store ``Container`` objects. :returns: A list of object store ``Container`` objects.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return list(self.object_store.containers(prefix=prefix)) return list(self.object_store.containers(prefix=prefix))
@ -57,8 +57,8 @@ class ObjectStoreCloudMixin:
:returns: A list of object store ``Container`` objects matching the :returns: A list of object store ``Container`` objects matching the
search criteria. search criteria.
:raises: ``OpenStackCloudException``: If something goes wrong during :raises: :class:`~openstack.exceptions.SDKException`: If something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
containers = self.list_containers() containers = self.list_containers()
return _utils._filter_list(containers, name, filters) return _utils._filter_list(containers, name, filters)
@ -112,7 +112,7 @@ class ObjectStoreCloudMixin:
except exceptions.NotFoundException: except exceptions.NotFoundException:
return False return False
except exceptions.ConflictException: except exceptions.ConflictException:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
'Attempt to delete container {container} failed. The' 'Attempt to delete container {container} failed. The'
' container is not empty. Please delete the objects' ' container is not empty. Please delete the objects'
' inside it before deleting the container'.format( ' inside it before deleting the container'.format(
@ -140,7 +140,7 @@ class ObjectStoreCloudMixin:
:param refresh: Flag to trigger refresh of the container properties :param refresh: Flag to trigger refresh of the container properties
""" """
if access not in OBJECT_CONTAINER_ACLS: if access not in OBJECT_CONTAINER_ACLS:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Invalid container access specified: %s. Must be one of %s" "Invalid container access specified: %s. Must be one of %s"
% (access, list(OBJECT_CONTAINER_ACLS.keys())) % (access, list(OBJECT_CONTAINER_ACLS.keys()))
) )
@ -153,13 +153,12 @@ class ObjectStoreCloudMixin:
:param str name: Name of the container. :param str name: Name of the container.
:returns: The contol list for the container. :returns: The contol list for the container.
:raises: :class:`~openstack.exceptions.OpenStackCloudException` if the :raises: :class:`~openstack.exceptions.SDKException` if the container
container was not found or container access could not be was not found or container access could not be determined.
determined.
""" """
container = self.get_container(name, skip_cache=True) container = self.get_container(name, skip_cache=True)
if not container: if not container:
raise exc.OpenStackCloudException("Container not found: %s" % name) raise exceptions.SDKException("Container not found: %s" % name)
acl = container.read_ACL or '' acl = container.read_ACL or ''
for key, value in OBJECT_CONTAINER_ACLS.items(): for key, value in OBJECT_CONTAINER_ACLS.items():
# Convert to string for the comparison because swiftclient # Convert to string for the comparison because swiftclient
@ -167,7 +166,7 @@ class ObjectStoreCloudMixin:
# on bytes doesn't work like you'd think # on bytes doesn't work like you'd think
if str(acl) == str(value): if str(acl) == str(value):
return key return key
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Could not determine container access for ACL: %s." % acl "Could not determine container access for ACL: %s." % acl
) )
@ -281,8 +280,10 @@ class ObjectStoreCloudMixin:
uploads of identical data. (optional, defaults to True) uploads of identical data. (optional, defaults to True)
:param metadata: This dict will get changed into headers that set :param metadata: This dict will get changed into headers that set
metadata of the object metadata of the object
:returns: The created object store ``Object`` object. :returns: The created object store ``Object`` object.
:raises: ``OpenStackCloudException`` on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return self.object_store.create_object( return self.object_store.create_object(
container, container,
@ -306,8 +307,10 @@ class ObjectStoreCloudMixin:
metadata of the object metadata of the object
:param headers: These will be passed through to the object update :param headers: These will be passed through to the object update
API as HTTP Headers. API as HTTP Headers.
:returns: None :returns: None
:raises: ``OpenStackCloudException`` on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
meta = metadata.copy() or {} meta = metadata.copy() or {}
meta.update(**headers) meta.update(**headers)
@ -320,8 +323,10 @@ class ObjectStoreCloudMixin:
:param full_listing: Ignored. Present for backwards compat :param full_listing: Ignored. Present for backwards compat
:param prefix: Only objects with this prefix will be returned. :param prefix: Only objects with this prefix will be returned.
(optional) (optional)
:returns: A list of object store ``Object`` objects. :returns: A list of object store ``Object`` objects.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
return list( return list(
self.object_store.objects(container=container, prefix=prefix) self.object_store.objects(container=container, prefix=prefix)
@ -338,8 +343,8 @@ class ObjectStoreCloudMixin:
:returns: A list of object store ``Object`` objects matching the :returns: A list of object store ``Object`` objects matching the
search criteria. search criteria.
:raises: ``OpenStackCloudException``: If something goes wrong during :raises: :class:`~openstack.exceptions.SDKException`: If something goes
the OpenStack API call. wrong during the OpenStack API call.
""" """
objects = self.list_objects(container) objects = self.list_objects(container)
return _utils._filter_list(objects, name, filters) return _utils._filter_list(objects, name, filters)
@ -351,8 +356,10 @@ class ObjectStoreCloudMixin:
:param string name: Name of the object to delete. :param string name: Name of the object to delete.
:param dict meta: Metadata for the object in question. (optional, will :param dict meta: Metadata for the object in question. (optional, will
be fetched if not provided) be fetched if not provided)
:returns: True if delete succeeded, False if the object was not found. :returns: True if delete succeeded, False if the object was not found.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
try: try:
self.object_store.delete_object( self.object_store.delete_object(
@ -404,8 +411,10 @@ class ObjectStoreCloudMixin:
:param string query_string: Query args for uri. (delimiter, prefix, :param string query_string: Query args for uri. (delimiter, prefix,
etc.) etc.)
:param bool stream: Whether to stream the response or not. :param bool stream: Whether to stream the response or not.
:returns: A `requests.Response` :returns: A `requests.Response`
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
endpoint = self._get_object_endpoint(container, obj, query_string) endpoint = self._get_object_endpoint(container, obj, query_string)
return self.object_store.get(endpoint, stream=stream) return self.object_store.get(endpoint, stream=stream)
@ -437,9 +446,11 @@ class ObjectStoreCloudMixin:
etc.) etc.)
:param int resp_chunk_size: Chunk size of data to read. Only used if :param int resp_chunk_size: Chunk size of data to read. Only used if
the results are the results are
:returns: An iterator over the content or None if the object is not :returns: An iterator over the content or None if the object is not
found. found.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
try: try:
for ret in self.object_store.stream_object( for ret in self.object_store.stream_object(
@ -471,9 +482,11 @@ class ObjectStoreCloudMixin:
contents. If this option is given, body in the return tuple will be contents. If this option is given, body in the return tuple will be
None. outfile can either be a file path given as a string, or a None. outfile can either be a file path given as a string, or a
File like object. File like object.
:returns: Tuple (headers, body) of the object, or None if the object :returns: Tuple (headers, body) of the object, or None if the object
is not found (404). is not found (404).
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
""" """
try: try:
obj = self.object_store.get_object( obj = self.object_store.get_object(

View File

@ -11,7 +11,7 @@
# limitations under the License. # limitations under the License.
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc from openstack import exceptions
from openstack.orchestration.util import event_utils from openstack.orchestration.util import event_utils
from openstack.orchestration.v1._proxy import Proxy from openstack.orchestration.v1._proxy import Proxy
@ -67,9 +67,8 @@ class OrchestrationCloudMixin:
specified. specified.
:returns: a dict containing the stack description :returns: a dict containing the stack description
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during wrong during the OpenStack API call
the OpenStack API call
""" """
params = dict( params = dict(
tags=tags, tags=tags,
@ -124,9 +123,8 @@ class OrchestrationCloudMixin:
specified. specified.
:returns: a dict containing the stack description :returns: a dict containing the stack description
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during wrong during the OpenStack API calls
the OpenStack API calls
""" """
params = dict( params = dict(
tags=tags, tags=tags,
@ -166,9 +164,8 @@ class OrchestrationCloudMixin:
:param boolean wait: Whether to wait for the delete to finish :param boolean wait: Whether to wait for the delete to finish
:returns: True if delete succeeded, False if the stack was not found. :returns: True if delete succeeded, False if the stack was not found.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during wrong during the OpenStack API call
the OpenStack API call
""" """
stack = self.get_stack(name_or_id, resolve_outputs=False) stack = self.get_stack(name_or_id, resolve_outputs=False)
if stack is None: if stack is None:
@ -189,11 +186,11 @@ class OrchestrationCloudMixin:
event_utils.poll_for_events( event_utils.poll_for_events(
self, stack_name=name_or_id, action='DELETE', marker=marker self, stack_name=name_or_id, action='DELETE', marker=marker
) )
except exc.OpenStackCloudHTTPError: except exceptions.HttpException:
pass pass
stack = self.get_stack(name_or_id, resolve_outputs=False) stack = self.get_stack(name_or_id, resolve_outputs=False)
if stack and stack['stack_status'] == 'DELETE_FAILED': if stack and stack['stack_status'] == 'DELETE_FAILED':
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Failed to delete stack {id}: {reason}".format( "Failed to delete stack {id}: {reason}".format(
id=name_or_id, reason=stack['stack_status_reason'] id=name_or_id, reason=stack['stack_status_reason']
) )
@ -210,9 +207,8 @@ class OrchestrationCloudMixin:
:returns: a list of ``openstack.orchestration.v1.stack.Stack`` :returns: a list of ``openstack.orchestration.v1.stack.Stack``
containing the stack description. containing the stack description.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during the wrong during the OpenStack API call.
OpenStack API call.
""" """
stacks = self.list_stacks() stacks = self.list_stacks()
return _utils._filter_list(stacks, name_or_id, filters) return _utils._filter_list(stacks, name_or_id, filters)
@ -221,11 +217,11 @@ class OrchestrationCloudMixin:
"""List all stacks. """List all stacks.
:param dict query: Query parameters to limit stacks. :param dict query: Query parameters to limit stacks.
:returns: a list of :class:`openstack.orchestration.v1.stack.Stack` :returns: a list of :class:`openstack.orchestration.v1.stack.Stack`
objects containing the stack description. objects containing the stack description.
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during the wrong during the OpenStack API call.
OpenStack API call.
""" """
return list(self.orchestration.stacks(**query)) return list(self.orchestration.stacks(**query))
@ -240,9 +236,9 @@ class OrchestrationCloudMixin:
:returns: a :class:`openstack.orchestration.v1.stack.Stack` :returns: a :class:`openstack.orchestration.v1.stack.Stack`
containing the stack description containing the stack description
:raises: :class:`~openstack.exceptions.SDKException` if something goes
:raises: ``OpenStackCloudException`` if something goes wrong during the wrong during the OpenStack API call or if multiple matches are
OpenStack API call or if multiple matches are found. found.
""" """
def _search_one_stack(name_or_id=None, filters=None): def _search_one_stack(name_or_id=None, filters=None):
@ -256,7 +252,7 @@ class OrchestrationCloudMixin:
) )
if stack.status == 'DELETE_COMPLETE': if stack.status == 'DELETE_COMPLETE':
return [] return []
except exc.OpenStackCloudURINotFound: except exceptions.NotFoundException:
return [] return []
return _utils._filter_list([stack], name_or_id, filters) return _utils._filter_list([stack], name_or_id, filters)

View File

@ -128,7 +128,8 @@ class SecurityGroupCloudMixin:
:returns: A ``openstack.network.v2.security_group.SecurityGroup`` :returns: A ``openstack.network.v2.security_group.SecurityGroup``
representing the new security group. representing the new security group.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
:raises: OpenStackCloudUnavailableFeature if security groups are :raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud. not supported on this cloud.
""" """
@ -165,7 +166,8 @@ class SecurityGroupCloudMixin:
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
:raises: OpenStackCloudUnavailableFeature if security groups are :raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud. not supported on this cloud.
""" """
@ -208,8 +210,8 @@ class SecurityGroupCloudMixin:
:returns: A ``openstack.network.v2.security_group.SecurityGroup`` :returns: A ``openstack.network.v2.security_group.SecurityGroup``
describing the updated security group. describing the updated security group.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
# Security groups not supported # Security groups not supported
if not self._has_secgroups(): if not self._has_secgroups():
@ -220,7 +222,7 @@ class SecurityGroupCloudMixin:
group = self.get_security_group(name_or_id) group = self.get_security_group(name_or_id)
if group is None: if group is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Security group %s not found." % name_or_id "Security group %s not found." % name_or_id
) )
@ -298,10 +300,11 @@ class SecurityGroupCloudMixin:
on (admin-only). on (admin-only).
:param string description: :param string description:
Description of the rule, max 255 characters. Description of the rule, max 255 characters.
:returns: A ``openstack.network.v2.security_group.SecurityGroup`` :returns: A ``openstack.network.v2.security_group.SecurityGroup``
representing the new security group rule. representing the new security group rule.
:raises: :class:`~openstack.exceptions.SDKException` on operation
:raises: OpenStackCloudException on operation error. error.
""" """
# Security groups not supported # Security groups not supported
if not self._has_secgroups(): if not self._has_secgroups():
@ -311,7 +314,7 @@ class SecurityGroupCloudMixin:
secgroup = self.get_security_group(secgroup_name_or_id) secgroup = self.get_security_group(secgroup_name_or_id)
if not secgroup: if not secgroup:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Security group %s not found." % secgroup_name_or_id "Security group %s not found." % secgroup_name_or_id
) )
@ -341,15 +344,13 @@ class SecurityGroupCloudMixin:
else: else:
# NOTE: Neutron accepts None for protocol. Nova does not. # NOTE: Neutron accepts None for protocol. Nova does not.
if protocol is None: if protocol is None:
raise exc.OpenStackCloudException('Protocol must be specified') raise exceptions.SDKException('Protocol must be specified')
if direction == 'egress': if direction == 'egress':
self.log.debug( self.log.debug(
'Rule creation failed: Nova does not support egress rules' 'Rule creation failed: Nova does not support egress rules'
) )
raise exc.OpenStackCloudException( raise exceptions.SDKException('No support for egress rules')
'No support for egress rules'
)
# NOTE: Neutron accepts None for ports, but Nova requires -1 # NOTE: Neutron accepts None for ports, but Nova requires -1
# as the equivalent value for ICMP. # as the equivalent value for ICMP.
@ -399,7 +400,8 @@ class SecurityGroupCloudMixin:
:returns: True if delete succeeded, False otherwise. :returns: True if delete succeeded, False otherwise.
:raises: OpenStackCloudException on operation error. :raises: :class:`~openstack.exceptions.SDKException` on operation
error.
:raises: OpenStackCloudUnavailableFeature if security groups are :raises: OpenStackCloudUnavailableFeature if security groups are
not supported on this cloud. not supported on this cloud.
""" """
@ -422,7 +424,7 @@ class SecurityGroupCloudMixin:
'/os-security-group-rules/{id}'.format(id=rule_id) '/os-security-group-rules/{id}'.format(id=rule_id)
) )
) )
except exc.OpenStackCloudResourceNotFound: except exceptions.NotFoundException:
return False return False
return True return True

View File

@ -23,7 +23,7 @@ import jmespath
import netifaces import netifaces
from openstack import _log from openstack import _log
from openstack.cloud import exc from openstack import exceptions
def _dictify_resource(resource): def _dictify_resource(resource):
@ -177,7 +177,7 @@ def _get_entity(cloud, resource, name_or_id, filters, **kwargs):
entities = search(name_or_id, filters, **kwargs) entities = search(name_or_id, filters, **kwargs)
if entities: if entities:
if len(entities) > 1: if len(entities) > 1:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Multiple matches found for %s" % name_or_id "Multiple matches found for %s" % name_or_id
) )
return entities[0] return entities[0]
@ -231,24 +231,24 @@ def openstacksdk_exceptions(error_message=None):
"""Context manager for dealing with openstack exceptions. """Context manager for dealing with openstack exceptions.
:param string error_message: String to use for the exception message :param string error_message: String to use for the exception message
content on non-OpenStackCloudExceptions. content on non-SDKException exception.
Useful for avoiding wrapping OpenStackCloudException exceptions Useful for avoiding wrapping SDKException exceptions
within themselves. Code called from within the context may throw such within themselves. Code called from within the context may throw such
exceptions without having to catch and reraise them. exceptions without having to catch and reraise them.
Non-OpenStackCloudException exceptions thrown within the context will Non-SDKException exceptions thrown within the context will
be wrapped and the exception message will be appended to the given be wrapped and the exception message will be appended to the given
error message. error message.
""" """
try: try:
yield yield
except exc.OpenStackCloudException: except exceptions.SDKException:
raise raise
except Exception as e: except Exception as e:
if error_message is None: if error_message is None:
error_message = str(e) error_message = str(e)
raise exc.OpenStackCloudException(error_message) raise exceptions.SDKException(error_message)
def safe_dict_min(key, data): def safe_dict_min(key, data):
@ -273,7 +273,7 @@ def safe_dict_min(key, data):
try: try:
val = int(d[key]) val = int(d[key])
except ValueError: except ValueError:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Search for minimum value failed. " "Search for minimum value failed. "
"Value for {key} is not an integer: {value}".format( "Value for {key} is not an integer: {value}".format(
key=key, value=d[key] key=key, value=d[key]
@ -306,7 +306,7 @@ def safe_dict_max(key, data):
try: try:
val = int(d[key]) val = int(d[key])
except ValueError: except ValueError:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Search for maximum value failed. " "Search for maximum value failed. "
"Value for {key} is not an integer: {value}".format( "Value for {key} is not an integer: {value}".format(
key=key, value=d[key] key=key, value=d[key]
@ -360,7 +360,8 @@ def range_filter(data, key, range_exp):
:param string range_exp: The expression describing the range of values. :param string range_exp: The expression describing the range of values.
:returns: A list subset of the original data set. :returns: A list subset of the original data set.
:raises: OpenStackCloudException on invalid range expressions. :raises: :class:`~openstack.exceptions.SDKException` on invalid range
expressions.
""" """
filtered = [] filtered = []
range_exp = str(range_exp).upper() range_exp = str(range_exp).upper()
@ -388,7 +389,7 @@ def range_filter(data, key, range_exp):
# If parsing the range fails, it must be a bad value. # If parsing the range fails, it must be a bad value.
if val_range is None: if val_range is None:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Invalid range value: {value}".format(value=range_exp) "Invalid range value: {value}".format(value=range_exp)
) )

View File

@ -21,6 +21,7 @@ import yaml
import openstack.cloud import openstack.cloud
import openstack.cloud.inventory import openstack.cloud.inventory
from openstack import exceptions
def output_format_dict(data, use_yaml): def output_format_dict(data, use_yaml):
@ -76,7 +77,7 @@ def main():
elif args.host: elif args.host:
output = inventory.get_host(args.host) output = inventory.get_host(args.host)
print(output_format_dict(output, args.yaml)) print(output_format_dict(output, args.yaml))
except openstack.cloud.OpenStackCloudException as e: except exceptions.SDKException as e:
sys.stderr.write(e.message + '\n') sys.stderr.write(e.message + '\n')
sys.exit(1) sys.exit(1)
sys.exit(0) sys.exit(0)

View File

@ -15,7 +15,6 @@
from openstack import exceptions from openstack import exceptions
OpenStackCloudException = exceptions.SDKException OpenStackCloudException = exceptions.SDKException
OpenStackCloudTimeout = exceptions.ResourceTimeout
class OpenStackCloudCreateException(OpenStackCloudException): class OpenStackCloudCreateException(OpenStackCloudException):
@ -39,6 +38,7 @@ class OpenStackCloudUnavailableFeature(OpenStackCloudException):
# Backwards compat # Backwards compat
OpenStackCloudTimeout = exceptions.ResourceTimeout
OpenStackCloudHTTPError = exceptions.HttpException OpenStackCloudHTTPError = exceptions.HttpException
OpenStackCloudBadRequest = exceptions.BadRequestException OpenStackCloudBadRequest = exceptions.BadRequestException
OpenStackCloudURINotFound = exceptions.NotFoundException OpenStackCloudURINotFound = exceptions.NotFoundException

View File

@ -74,7 +74,7 @@ class OpenStackInventory:
detailed=expand, all_projects=all_projects detailed=expand, all_projects=all_projects
): ):
hostvars.append(server) hostvars.append(server)
except exceptions.OpenStackCloudException: except exceptions.SDKException:
# Don't fail on one particular cloud as others may work # Don't fail on one particular cloud as others may work
if fail_on_cloud_config: if fail_on_cloud_config:
raise raise

View File

@ -16,7 +16,7 @@ import ipaddress
import socket import socket
from openstack import _log from openstack import _log
from openstack.cloud import exc from openstack import exceptions
from openstack import utils from openstack import utils
@ -452,7 +452,7 @@ def _get_supplemental_addresses(cloud, server):
server['addresses'][fixed_net].append( server['addresses'][fixed_net].append(
_make_address_dict(fip, port) _make_address_dict(fip, port)
) )
except exc.OpenStackCloudException: except exceptions.SDKException:
# If something goes wrong with a cloud call, that's cool - this is # If something goes wrong with a cloud call, that's cool - this is
# an attempt to provide additional data and should not block forward # an attempt to provide additional data and should not block forward
# progress # progress
@ -498,7 +498,7 @@ def add_server_interfaces(cloud, server):
def expand_server_security_groups(cloud, server): def expand_server_security_groups(cloud, server):
try: try:
groups = cloud.list_server_security_groups(server) groups = cloud.list_server_security_groups(server)
except exc.OpenStackCloudException: except exceptions.SDKException:
groups = [] groups = []
server['security_groups'] = groups or [] server['security_groups'] = groups or []
@ -550,7 +550,7 @@ def get_hostvars_from_server(cloud, server, mounts=None):
# Make things easier to consume elsewhere # Make things easier to consume elsewhere
volume['device'] = volume['attachments'][0]['device'] volume['device'] = volume['attachments'][0]['device']
volumes.append(volume) volumes.append(volume)
except exc.OpenStackCloudException: except exceptions.SDKException:
pass pass
server_vars['volumes'] = volumes server_vars['volumes'] = volumes
if mounts: if mounts:

View File

@ -24,7 +24,6 @@ import requestsexceptions
from openstack import _log from openstack import _log
from openstack.cloud import _object_store from openstack.cloud import _object_store
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc
from openstack.cloud import meta from openstack.cloud import meta
import openstack.config import openstack.config
from openstack.config import cloud_region as cloud_region_mod from openstack.config import cloud_region as cloud_region_mod
@ -445,7 +444,8 @@ class _OpenStackCloudMixin:
{"vcpus": "<=5", "ram": "<=2048", "disk": "1"} {"vcpus": "<=5", "ram": "<=2048", "disk": "1"}
:returns: A list subset of the original data set. :returns: A list subset of the original data set.
:raises: OpenStackCloudException on invalid range expressions. :raises: :class:`~openstack.exceptions.SDKException` on invalid range
expressions.
""" """
filtered = [] filtered = []
@ -491,10 +491,10 @@ class _OpenStackCloudMixin:
"Endpoint not found in %s cloud: %s", self.name, str(e) "Endpoint not found in %s cloud: %s", self.name, str(e)
) )
endpoint = None endpoint = None
except exc.OpenStackCloudException: except exceptions.SDKException:
raise raise
except Exception as e: except Exception as e:
raise exc.OpenStackCloudException( raise exceptions.SDKException(
"Error getting {service} endpoint on {cloud}:{region}:" "Error getting {service} endpoint on {cloud}:{region}:"
" {error}".format( " {error}".format(
service=service_key, service=service_key,
@ -525,7 +525,7 @@ class _OpenStackCloudMixin:
kwargs['min_version'] = version kwargs['min_version'] = version
kwargs['max_version'] = version kwargs['max_version'] = version
endpoint = self.get_session_endpoint(service_key, **kwargs) endpoint = self.get_session_endpoint(service_key, **kwargs)
except exc.OpenStackCloudException: except exceptions.SDKException:
return False return False
if endpoint: if endpoint:
return True return True

View File

@ -32,9 +32,6 @@ class SDKException(Exception):
super(SDKException, self).__init__(self.message) super(SDKException, self).__init__(self.message)
OpenStackCloudException = SDKException
class EndpointNotFound(SDKException): class EndpointNotFound(SDKException):
"""A mismatch occurred between what the client and server expect.""" """A mismatch occurred between what the client and server expect."""
@ -274,3 +271,7 @@ class ServiceDisabledException(ConfigException):
class ServiceDiscoveryException(SDKException): class ServiceDiscoveryException(SDKException):
"""The service cannot be discovered.""" """The service cannot be discovered."""
# Backwards compatibility
OpenStackCloudException = SDKException

View File

@ -13,8 +13,7 @@
import os import os
import warnings import warnings
from openstack.cloud import exc from openstack import exceptions as exc
from openstack import exceptions
from openstack.image.v1 import image as _image from openstack.image.v1 import image as _image
from openstack import proxy from openstack import proxy
from openstack import utils from openstack import utils
@ -128,7 +127,7 @@ class Proxy(proxy.Proxy):
or 'all_stores' in kwargs or 'all_stores' in kwargs
or 'all_stores_must_succeed' in kwargs or 'all_stores_must_succeed' in kwargs
): ):
raise exceptions.InvalidRequest( raise exc.InvalidRequest(
"Glance v1 does not support stores or image import" "Glance v1 does not support stores or image import"
) )
@ -151,7 +150,7 @@ class Proxy(proxy.Proxy):
container_format = 'bare' container_format = 'bare'
if data and filename: if data and filename:
raise exceptions.SDKException( raise exc.SDKException(
'Passing filename and data simultaneously is not supported' 'Passing filename and data simultaneously is not supported'
) )
@ -163,7 +162,7 @@ class Proxy(proxy.Proxy):
) )
if validate_checksum and data and not isinstance(data, bytes): if validate_checksum and data and not isinstance(data, bytes):
raise exceptions.SDKException( raise exc.SDKException(
'Validating checksum is not possible when data is not a ' 'Validating checksum is not possible when data is not a '
'direct binary object' 'direct binary object'
) )
@ -301,11 +300,11 @@ class Proxy(proxy.Proxy):
data=image_data, data=image_data,
), ),
) )
except exc.OpenStackCloudHTTPError: except exc.HttpException:
self.log.debug("Deleting failed upload of image %s", name) self.log.debug("Deleting failed upload of image %s", name)
try: try:
self.delete('/images/{id}'.format(id=image.id)) self.delete('/images/{id}'.format(id=image.id))
except exc.OpenStackCloudHTTPError: except exc.HttpException:
# We're just trying to clean up - if it doesn't work - shrug # We're just trying to clean up - if it doesn't work - shrug
self.log.warning( self.log.warning(
"Failed deleting image after we failed uploading it.", "Failed deleting image after we failed uploading it.",

View File

@ -394,7 +394,8 @@ class Proxy(proxy.Proxy):
:param metadata: This dict will get changed into headers that set :param metadata: This dict will get changed into headers that set
metadata of the object metadata of the object
:raises: ``OpenStackCloudException`` on operation error. :raises: ``:class:`~openstack.exceptions.SDKException``` on operation
error.
""" """
if data is not None and filename: if data is not None and filename:
raise ValueError( raise ValueError(

View File

@ -21,7 +21,7 @@ import datetime
from fixtures import TimeoutException from fixtures import TimeoutException
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
from openstack import utils from openstack import utils
@ -52,7 +52,7 @@ class TestCompute(base.BaseFunctionalTest):
for volume in volumes: for volume in volumes:
if volume.status != 'deleting': if volume.status != 'deleting':
self.user_cloud.delete_volume(volume.id, wait=True) self.user_cloud.delete_volume(volume.id, wait=True)
except (exc.OpenStackCloudTimeout, TimeoutException): except (exceptions.ResourceTimeout, TimeoutException):
# Ups, some timeout occured during process of deletion server # Ups, some timeout occured during process of deletion server
# or volumes, so now we will try to call delete each of them # or volumes, so now we will try to call delete each of them
# once again and we will try to live with it # once again and we will try to live with it
@ -197,7 +197,7 @@ class TestCompute(base.BaseFunctionalTest):
def test_list_all_servers_bad_permissions(self): def test_list_all_servers_bad_permissions(self):
# Normal users are not allowed to pass all_projects=True # Normal users are not allowed to pass all_projects=True
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.user_cloud.list_servers, self.user_cloud.list_servers,
all_projects=True, all_projects=True,
) )
@ -252,7 +252,7 @@ class TestCompute(base.BaseFunctionalTest):
def test_get_server_console_bad_server(self): def test_get_server_console_bad_server(self):
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.user_cloud.get_server_console, self.user_cloud.get_server_console,
server=self.server_name, server=self.server_name,
) )
@ -525,7 +525,7 @@ class TestCompute(base.BaseFunctionalTest):
self.assertEqual(set(updated_server.metadata.items()), set([])) self.assertEqual(set(updated_server.metadata.items()), set([]))
self.assertRaises( self.assertRaises(
exc.OpenStackCloudURINotFound, exceptions.NotFoundException,
self.user_cloud.delete_server_metadata, self.user_cloud.delete_server_metadata,
self.server_name, self.server_name,
['key1'], ['key1'],

View File

@ -17,7 +17,7 @@ test_domain
Functional tests for keystone domain resource. Functional tests for keystone domain resource.
""" """
import openstack.cloud from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -45,9 +45,7 @@ class TestDomain(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise openstack.cloud.OpenStackCloudException( raise exceptions.SDKException('\n'.join(exception_list))
'\n'.join(exception_list)
)
def test_search_domains(self): def test_search_domains(self):
domain_name = self.domain_prefix + '_search' domain_name = self.domain_prefix + '_search'

View File

@ -22,8 +22,8 @@ Functional tests for endpoint resource.
import random import random
import string import string
from openstack.cloud.exc import OpenStackCloudException
from openstack.cloud.exc import OpenStackCloudUnavailableFeature from openstack.cloud.exc import OpenStackCloudUnavailableFeature
from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -65,7 +65,7 @@ class TestEndpoints(base.KeystoneBaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_services(self): def _cleanup_services(self):
exception_list = list() exception_list = list()
@ -82,7 +82,7 @@ class TestEndpoints(base.KeystoneBaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_endpoint(self): def test_create_endpoint(self):
service_name = self.new_item_name + '_create' service_name = self.new_item_name + '_create'

View File

@ -19,7 +19,7 @@ test_flavor
Functional tests for flavor resource. Functional tests for flavor resource.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -47,7 +47,7 @@ class TestFlavor(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_flavor(self): def test_create_flavor(self):
if not self.operator_cloud: if not self.operator_cloud:

View File

@ -24,8 +24,8 @@ import sys
from testtools import content from testtools import content
from openstack.cloud.exc import OpenStackCloudException
from openstack.cloud import meta from openstack.cloud import meta
from openstack import exceptions
from openstack import proxy from openstack import proxy
from openstack.tests.functional import base from openstack.tests.functional import base
from openstack import utils from openstack import utils
@ -116,7 +116,7 @@ class TestFloatingIP(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_ips(self, server): def _cleanup_ips(self, server):
exception_list = list() exception_list = list()
@ -137,7 +137,7 @@ class TestFloatingIP(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _setup_networks(self): def _setup_networks(self):
if self.user_cloud.has_service('network'): if self.user_cloud.has_service('network'):

View File

@ -17,7 +17,7 @@ test_groups
Functional tests for keystone group resource. Functional tests for keystone group resource.
""" """
import openstack.cloud from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -46,9 +46,7 @@ class TestGroup(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise openstack.cloud.OpenStackCloudException( raise exceptions.SDKException('\n'.join(exception_list))
'\n'.join(exception_list)
)
def test_create_group(self): def test_create_group(self):
group_name = self.group_prefix + '_create' group_name = self.group_prefix + '_create'

View File

@ -20,7 +20,7 @@ Functional tests for identity methods.
import random import random
import string import string
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -53,7 +53,7 @@ class TestIdentity(base.KeystoneBaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_users(self): def _cleanup_users(self):
exception_list = list() exception_list = list()
@ -66,7 +66,7 @@ class TestIdentity(base.KeystoneBaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_roles(self): def _cleanup_roles(self):
exception_list = list() exception_list = list()
@ -79,7 +79,7 @@ class TestIdentity(base.KeystoneBaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _create_user(self, **kwargs): def _create_user(self, **kwargs):
domain_id = None domain_id = None

View File

@ -17,7 +17,7 @@ test_network
Functional tests for network methods. Functional tests for network methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -43,7 +43,7 @@ class TestNetwork(base.BaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_network_basic(self): def test_create_network_basic(self):
net1 = self.operator_cloud.create_network(name=self.network_name) net1 = self.operator_cloud.create_network(name=self.network_name)

View File

@ -23,7 +23,7 @@ import tempfile
from testtools import content from testtools import content
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -97,7 +97,7 @@ class TestObject(base.BaseFunctionalTest):
self.assertIsNotNone( self.assertIsNotNone(
self.user_cloud.get_object(container_name, name) self.user_cloud.get_object(container_name, name)
) )
except exc.OpenStackCloudException as e: except exceptions.SDKException as e:
self.addDetail( self.addDetail(
'failed_response', 'failed_response',
content.text_content(str(e.response.headers)), content.text_content(str(e.response.headers)),
@ -186,7 +186,7 @@ class TestObject(base.BaseFunctionalTest):
) )
downloaded_content = open(fake_file.name, 'rb').read() downloaded_content = open(fake_file.name, 'rb').read()
self.assertEqual(fake_content, downloaded_content) self.assertEqual(fake_content, downloaded_content)
except exc.OpenStackCloudException as e: except exceptions.SDKException as e:
self.addDetail( self.addDetail(
'failed_response', 'failed_response',
content.text_content(str(e.response.headers)), content.text_content(str(e.response.headers)),

View File

@ -22,7 +22,7 @@ Functional tests for port resource.
import random import random
import string import string
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -59,7 +59,7 @@ class TestPort(base.BaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_port(self): def test_create_port(self):
port_name = self.new_port_name + '_create' port_name = self.new_port_name + '_create'

View File

@ -20,7 +20,7 @@ Functional tests for project resource.
""" """
import pprint import pprint
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -43,7 +43,7 @@ class TestProject(base.KeystoneBaseFunctionalTest):
exception_list.append(str(e)) exception_list.append(str(e))
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_project(self): def test_create_project(self):
project_name = self.new_project_name + '_create' project_name = self.new_project_name + '_create'

View File

@ -18,7 +18,7 @@ test_qos_bandwidth_limit_rule
Functional tests for QoS bandwidth limit methods. Functional tests for QoS bandwidth limit methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -41,7 +41,7 @@ class TestQosBandwidthLimitRule(base.BaseFunctionalTest):
try: try:
self.operator_cloud.delete_qos_policy(self.policy['id']) self.operator_cloud.delete_qos_policy(self.policy['id'])
except Exception as e: except Exception as e:
raise OpenStackCloudException(e) raise exceptions.SDKException(e)
def test_qos_bandwidth_limit_rule_lifecycle(self): def test_qos_bandwidth_limit_rule_lifecycle(self):
max_kbps = 1500 max_kbps = 1500

View File

@ -18,7 +18,7 @@ test_qos_dscp_marking_rule
Functional tests for QoS DSCP marking rule methods. Functional tests for QoS DSCP marking rule methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -41,7 +41,7 @@ class TestQosDscpMarkingRule(base.BaseFunctionalTest):
try: try:
self.operator_cloud.delete_qos_policy(self.policy['id']) self.operator_cloud.delete_qos_policy(self.policy['id'])
except Exception as e: except Exception as e:
raise OpenStackCloudException(e) raise exceptions.SDKException(e)
def test_qos_dscp_marking_rule_lifecycle(self): def test_qos_dscp_marking_rule_lifecycle(self):
dscp_mark = 16 dscp_mark = 16

View File

@ -18,7 +18,7 @@ test_qos_minumum_bandwidth_rule
Functional tests for QoS minimum bandwidth methods. Functional tests for QoS minimum bandwidth methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -41,7 +41,7 @@ class TestQosMinimumBandwidthRule(base.BaseFunctionalTest):
try: try:
self.operator_cloud.delete_qos_policy(self.policy['id']) self.operator_cloud.delete_qos_policy(self.policy['id'])
except Exception as e: except Exception as e:
raise OpenStackCloudException(e) raise exceptions.SDKException(e)
def test_qos_minimum_bandwidth_rule_lifecycle(self): def test_qos_minimum_bandwidth_rule_lifecycle(self):
min_kbps = 1500 min_kbps = 1500

View File

@ -18,7 +18,7 @@ test_qos_policy
Functional tests for QoS policies methods. Functional tests for QoS policies methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -45,7 +45,7 @@ class TestQosPolicy(base.BaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_qos_policy_basic(self): def test_create_qos_policy_basic(self):
policy = self.operator_cloud.create_qos_policy(name=self.policy_name) policy = self.operator_cloud.create_qos_policy(name=self.policy_name)

View File

@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -28,7 +28,7 @@ class TestRangeSearch(base.BaseFunctionalTest):
def test_range_search_bad_range(self): def test_range_search_bad_range(self):
flavors = self.user_cloud.list_flavors(get_extra=False) flavors = self.user_cloud.list_flavors(get_extra=False)
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.user_cloud.range_search, self.user_cloud.range_search,
flavors, flavors,
{"ram": "<1a0"}, {"ram": "<1a0"},

View File

@ -19,7 +19,7 @@ Functional tests for router methods.
import ipaddress import ipaddress
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -64,7 +64,7 @@ class TestRouter(base.BaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_networks(self): def _cleanup_networks(self):
exception_list = list() exception_list = list()
@ -77,7 +77,7 @@ class TestRouter(base.BaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _cleanup_subnets(self): def _cleanup_subnets(self):
exception_list = list() exception_list = list()
@ -90,7 +90,7 @@ class TestRouter(base.BaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_router_basic(self): def test_create_router_basic(self):
net1_name = self.network_prefix + '_net1' net1_name = self.network_prefix + '_net1'

View File

@ -22,8 +22,8 @@ Functional tests for service resource.
import random import random
import string import string
from openstack.cloud.exc import OpenStackCloudException from openstack.cloud import exc
from openstack.cloud.exc import OpenStackCloudUnavailableFeature from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -57,7 +57,7 @@ class TestServices(base.KeystoneBaseFunctionalTest):
if exception_list: if exception_list:
# Raise an error: we must make users aware that something went # Raise an error: we must make users aware that something went
# wrong # wrong
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def test_create_service(self): def test_create_service(self):
service = self.operator_cloud.create_service( service = self.operator_cloud.create_service(
@ -72,7 +72,7 @@ class TestServices(base.KeystoneBaseFunctionalTest):
if ver.startswith('2'): if ver.startswith('2'):
# NOTE(SamYaple): Update service only works with v3 api # NOTE(SamYaple): Update service only works with v3 api
self.assertRaises( self.assertRaises(
OpenStackCloudUnavailableFeature, exc.OpenStackCloudUnavailableFeature,
self.operator_cloud.update_service, self.operator_cloud.update_service,
'service_id', 'service_id',
name='new name', name='new name',

View File

@ -19,7 +19,7 @@ Functional tests for stack methods.
import tempfile import tempfile
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.functional import base from openstack.tests.functional import base
@ -88,7 +88,7 @@ class TestStack(base.BaseFunctionalTest):
test_template.close() test_template.close()
stack_name = self.getUniqueString('validate_template') stack_name = self.getUniqueString('validate_template')
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.user_cloud.create_stack, self.user_cloud.create_stack,
name=stack_name, name=stack_name,
template_file=test_template.name, template_file=test_template.name,

View File

@ -17,7 +17,7 @@ test_users
Functional tests for user methods. Functional tests for user methods.
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -41,7 +41,7 @@ class TestUsers(base.KeystoneBaseFunctionalTest):
continue continue
if exception_list: if exception_list:
raise OpenStackCloudException('\n'.join(exception_list)) raise exceptions.SDKException('\n'.join(exception_list))
def _create_user(self, **kwargs): def _create_user(self, **kwargs):
domain_id = None domain_id = None

View File

@ -20,7 +20,7 @@ Functional tests for block storage methods.
from fixtures import TimeoutException from fixtures import TimeoutException
from testtools import content from testtools import content
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
from openstack import utils from openstack import utils
@ -123,7 +123,7 @@ class TestVolume(base.BaseFunctionalTest):
break break
if not found: if not found:
break break
except (exc.OpenStackCloudTimeout, TimeoutException): except (exceptions.ResourceTimeout, TimeoutException):
# NOTE(slaweq): ups, some volumes are still not removed # NOTE(slaweq): ups, some volumes are still not removed
# so we should try to force delete it once again and move # so we should try to force delete it once again and move
# forward # forward

View File

@ -20,7 +20,7 @@ Functional tests for block storage methods.
""" """
import testtools import testtools
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.functional import base from openstack.tests.functional import base
@ -94,7 +94,7 @@ class TestVolumeType(base.BaseFunctionalTest):
def test_add_volume_type_access_missing_volume(self): def test_add_volume_type_access_missing_volume(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, "VolumeType not found.*" exceptions.SDKException, "VolumeType not found.*"
): ):
self.operator_cloud.add_volume_type_access( self.operator_cloud.add_volume_type_access(
'MISSING_VOLUME_TYPE', self.operator_cloud.current_project_id 'MISSING_VOLUME_TYPE', self.operator_cloud.current_project_id
@ -102,7 +102,7 @@ class TestVolumeType(base.BaseFunctionalTest):
def test_remove_volume_type_access_missing_volume(self): def test_remove_volume_type_access_missing_volume(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, "VolumeType not found.*" exceptions.SDKException, "VolumeType not found.*"
): ):
self.operator_cloud.remove_volume_type_access( self.operator_cloud.remove_volume_type_access(
'MISSING_VOLUME_TYPE', self.operator_cloud.current_project_id 'MISSING_VOLUME_TYPE', self.operator_cloud.current_project_id
@ -110,7 +110,7 @@ class TestVolumeType(base.BaseFunctionalTest):
def test_add_volume_type_access_bad_project(self): def test_add_volume_type_access_bad_project(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudBadRequest, "Unable to authorize.*" exceptions.BadRequestException, "Unable to authorize.*"
): ):
self.operator_cloud.add_volume_type_access( self.operator_cloud.add_volume_type_access(
'test-volume-type', 'BAD_PROJECT_ID' 'test-volume-type', 'BAD_PROJECT_ID'
@ -118,7 +118,7 @@ class TestVolumeType(base.BaseFunctionalTest):
def test_remove_volume_type_access_missing_project(self): def test_remove_volume_type_access_missing_project(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudURINotFound, "Unable to revoke.*" exceptions.NotFoundException, "Unable to revoke.*"
): ):
self.operator_cloud.remove_volume_type_access( self.operator_cloud.remove_volume_type_access(
'test-volume-type', '00000000000000000000000000000000' 'test-volume-type', '00000000000000000000000000000000'

View File

@ -18,7 +18,7 @@ from uuid import uuid4
import testtools import testtools
from openstack.cloud import _utils from openstack.cloud import _utils
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
RANGE_DATA = [ RANGE_DATA = [
@ -200,7 +200,7 @@ class TestUtils(base.TestCase):
"""Test non-integer key value raises OSCE""" """Test non-integer key value raises OSCE"""
data = [{'f1': 3}, {'f1': "aaa"}, {'f1': 1}] data = [{'f1': 3}, {'f1': "aaa"}, {'f1': 1}]
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Search for minimum value failed. " "Search for minimum value failed. "
"Value for f1 is not an integer: aaa", "Value for f1 is not an integer: aaa",
): ):
@ -240,7 +240,7 @@ class TestUtils(base.TestCase):
"""Test non-integer key value raises OSCE""" """Test non-integer key value raises OSCE"""
data = [{'f1': 3}, {'f1': "aaa"}, {'f1': 1}] data = [{'f1': 3}, {'f1': "aaa"}, {'f1': 1}]
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Search for maximum value failed. " "Search for maximum value failed. "
"Value for f1 is not an integer: aaa", "Value for f1 is not an integer: aaa",
): ):
@ -308,13 +308,13 @@ class TestUtils(base.TestCase):
def test_range_filter_invalid_int(self): def test_range_filter_invalid_int(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, "Invalid range value: <1A0" exceptions.SDKException, "Invalid range value: <1A0"
): ):
_utils.range_filter(RANGE_DATA, "key1", "<1A0") _utils.range_filter(RANGE_DATA, "key1", "<1A0")
def test_range_filter_invalid_op(self): def test_range_filter_invalid_op(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, "Invalid range value: <>100" exceptions.SDKException, "Invalid range value: <>100"
): ):
_utils.range_filter(RANGE_DATA, "key1", "<>100") _utils.range_filter(RANGE_DATA, "key1", "<>100")

View File

@ -21,7 +21,6 @@ import uuid
from testscenarios import load_tests_apply_scenarios as load_tests # noqa from testscenarios import load_tests_apply_scenarios as load_tests # noqa
from openstack.cloud import exc
from openstack import exceptions from openstack import exceptions
from openstack.network.v2 import port as _port from openstack.network.v2 import port as _port
from openstack.tests import fakes from openstack.tests import fakes
@ -319,7 +318,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.inspect_machine, self.cloud.inspect_machine,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
wait=True, wait=True,
@ -344,7 +343,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaisesRegex( self.assertRaisesRegex(
exc.OpenStackCloudException, exceptions.SDKException,
'associated with an instance', 'associated with an instance',
self.cloud.inspect_machine, self.cloud.inspect_machine,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
@ -744,7 +743,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.inspect_machine, self.cloud.inspect_machine,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
wait=True, wait=True,
@ -985,7 +984,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.set_machine_power_reboot, self.cloud.set_machine_power_reboot,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
) )
@ -1195,7 +1194,7 @@ class TestBaremetalNode(base.IronicTestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.node_set_provision_state, self.cloud.node_set_provision_state,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
'active', 'active',
@ -1267,7 +1266,7 @@ class TestBaremetalNode(base.IronicTestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.node_set_provision_state, self.cloud.node_set_provision_state,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
'active', 'active',
@ -1378,7 +1377,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.wait_for_baremetal_node_lock, self.cloud.wait_for_baremetal_node_lock,
self.fake_baremetal_node, self.fake_baremetal_node,
timeout=0.001, timeout=0.001,
@ -1742,7 +1741,7 @@ class TestBaremetalNode(base.IronicTestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.register_machine, self.cloud.register_machine,
nics, nics,
**node_to_post **node_to_post
@ -1807,7 +1806,7 @@ class TestBaremetalNode(base.IronicTestCase):
# state to the API is essentially a busy state that we # state to the API is essentially a busy state that we
# want to block on until it has cleared. # want to block on until it has cleared.
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.register_machine, self.cloud.register_machine,
nics, nics,
timeout=0.001, timeout=0.001,
@ -1897,7 +1896,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.register_machine, self.cloud.register_machine,
nics, nics,
wait=True, wait=True,
@ -1946,7 +1945,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaisesRegex( self.assertRaisesRegex(
exc.OpenStackCloudException, exceptions.SDKException,
'no ports for you', 'no ports for you',
self.cloud.register_machine, self.cloud.register_machine,
nics, nics,
@ -2012,7 +2011,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaisesRegex( self.assertRaisesRegex(
exc.OpenStackCloudException, exceptions.SDKException,
'no ports for you', 'no ports for you',
self.cloud.register_machine, self.cloud.register_machine,
nics, nics,
@ -2101,7 +2100,7 @@ class TestBaremetalNode(base.IronicTestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.unregister_machine, self.cloud.unregister_machine,
nics, nics,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
@ -2211,7 +2210,7 @@ class TestBaremetalNode(base.IronicTestCase):
for state in invalid_states: for state in invalid_states:
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.unregister_machine, self.cloud.unregister_machine,
nics, nics,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],

View File

@ -19,7 +19,7 @@ Tests for baremetal port related operations
from testscenarios import load_tests_apply_scenarios as load_tests # noqa from testscenarios import load_tests_apply_scenarios as load_tests # noqa
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -71,7 +71,7 @@ class TestBaremetalPort(base.IronicTestCase):
) )
] ]
) )
self.assertRaises(exc.OpenStackCloudException, self.cloud.list_nics) self.assertRaises(exceptions.SDKException, self.cloud.list_nics)
self.assert_calls() self.assert_calls()
def test_list_nics_for_machine(self): def test_list_nics_for_machine(self):
@ -121,7 +121,7 @@ class TestBaremetalPort(base.IronicTestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.list_nics_for_machine, self.cloud.list_nics_for_machine,
self.fake_baremetal_node['uuid'], self.fake_baremetal_node['uuid'],
) )

View File

@ -15,8 +15,8 @@ import uuid
import testtools import testtools
from openstack.cloud import exc
from openstack import connection from openstack import connection
from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
from openstack import utils from openstack import utils
@ -145,7 +145,7 @@ class TestCloud(base.TestCase):
def test_iterate_timeout_bad_wait(self): def test_iterate_timeout_bad_wait(self):
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Wait value must be an int or float value.", "Wait value must be an int or float value.",
): ):
for count in utils.iterate_timeout( for count in utils.iterate_timeout(
@ -174,7 +174,7 @@ class TestCloud(base.TestCase):
@mock.patch('time.sleep') @mock.patch('time.sleep')
def test_iterate_timeout_timeout(self, mock_sleep): def test_iterate_timeout_timeout(self, mock_sleep):
message = "timeout test" message = "timeout test"
with testtools.ExpectedException(exc.OpenStackCloudTimeout, message): with testtools.ExpectedException(exceptions.ResourceTimeout, message):
for count in utils.iterate_timeout(0.1, message, wait=1): for count in utils.iterate_timeout(0.1, message, wait=1):
pass pass
mock_sleep.assert_called_with(1.0) mock_sleep.assert_called_with(1.0)

View File

@ -210,9 +210,9 @@ class TestClusterTemplates(base.TestCase):
# for matching the old error message text. Investigate plumbing # for matching the old error message text. Investigate plumbing
# an error message in to the adapter call so that we can give a # an error message in to the adapter call so that we can give a
# more informative error. Also, the test was originally catching # more informative error. Also, the test was originally catching
# OpenStackCloudException - but for some reason testtools will not # SDKException - but for some reason testtools will not
# match the more specific HTTPError, even though it's a subclass # match the more specific HTTPError, even though it's a subclass
# of OpenStackCloudException. # of SDKException.
with testtools.ExpectedException(exceptions.ForbiddenException): with testtools.ExpectedException(exceptions.ForbiddenException):
self.cloud.create_cluster_template('fake-cluster-template') self.cloud.create_cluster_template('fake-cluster-template')
self.assert_calls() self.assert_calls()

View File

@ -12,7 +12,6 @@
import uuid import uuid
from openstack.cloud import exc
from openstack import exceptions from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -495,6 +494,6 @@ class TestServers(base.TestCase):
] ]
) )
self.assertRaises(exc.OpenStackCloudException, self.cloud.list_servers) self.assertRaises(exceptions.SDKException, self.cloud.list_servers)
self.assert_calls() self.assert_calls()

View File

@ -21,10 +21,10 @@ import base64
from unittest import mock from unittest import mock
import uuid import uuid
from openstack.cloud import exc
from openstack.cloud import meta from openstack.cloud import meta
from openstack.compute.v2 import server from openstack.compute.v2 import server
from openstack import connection from openstack import connection
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -81,7 +81,7 @@ class TestCreateServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
{'id': 'image-id'}, {'id': 'image-id'},
@ -135,7 +135,7 @@ class TestCreateServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
{'id': 'image-id'}, {'id': 'image-id'},
@ -196,7 +196,7 @@ class TestCreateServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
dict(id='image-id'), dict(id='image-id'),
@ -251,7 +251,7 @@ class TestCreateServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudTimeout, exceptions.ResourceTimeout,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
dict(id='image-id'), dict(id='image-id'),
@ -815,7 +815,7 @@ class TestCreateServer(base.TestCase):
mock_add_ips_to_server.return_value = fake_server mock_add_ips_to_server.return_value = fake_server
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
{'id': 'image-id'}, {'id': 'image-id'},
@ -1179,7 +1179,7 @@ class TestCreateServer(base.TestCase):
self.use_nothing() self.use_nothing()
fixed_ip = '10.0.0.1' fixed_ip = '10.0.0.1'
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_server, self.cloud.create_server,
'server-name', 'server-name',
dict(id='image-id'), dict(id='image-id'),

View File

@ -18,8 +18,8 @@ Tests for the `create_volume_snapshot` command.
""" """
from openstack.block_storage.v3 import snapshot from openstack.block_storage.v3 import snapshot
from openstack.cloud import exc
from openstack.cloud import meta from openstack.cloud import meta
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -125,7 +125,7 @@ class TestCreateVolumeSnapshot(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudTimeout, exceptions.ResourceTimeout,
self.cloud.create_volume_snapshot, self.cloud.create_volume_snapshot,
volume_id=volume_id, volume_id=volume_id,
wait=True, wait=True,
@ -181,7 +181,7 @@ class TestCreateVolumeSnapshot(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_volume_snapshot, self.cloud.create_volume_snapshot,
volume_id=volume_id, volume_id=volume_id,
wait=True, wait=True,

View File

@ -18,7 +18,7 @@ Tests for the `delete_server` command.
""" """
import uuid import uuid
from openstack.cloud import exc as shade_exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -204,7 +204,7 @@ class TestDeleteServer(base.TestCase):
) )
self.assertRaises( self.assertRaises(
shade_exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_server, self.cloud.delete_server,
'speedy', 'speedy',
wait=False, wait=False,

View File

@ -17,8 +17,8 @@ test_delete_volume_snapshot
Tests for the `delete_volume_snapshot` command. Tests for the `delete_volume_snapshot` command.
""" """
from openstack.cloud import exc
from openstack.cloud import meta from openstack.cloud import meta
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -66,7 +66,7 @@ class TestDeleteVolumeSnapshot(base.TestCase):
def test_delete_volume_snapshot_with_error(self): def test_delete_volume_snapshot_with_error(self):
""" """
Test that a exception while deleting a volume snapshot will cause an Test that a exception while deleting a volume snapshot will cause an
OpenStackCloudException. SDKException.
""" """
fake_snapshot = fakes.FakeVolumeSnapshot( fake_snapshot = fakes.FakeVolumeSnapshot(
'1234', 'available', 'foo', 'derpysnapshot' '1234', 'available', 'foo', 'derpysnapshot'
@ -94,7 +94,7 @@ class TestDeleteVolumeSnapshot(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_volume_snapshot, self.cloud.delete_volume_snapshot,
name_or_id='1234', name_or_id='1234',
) )
@ -138,7 +138,7 @@ class TestDeleteVolumeSnapshot(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudTimeout, exceptions.ResourceTimeout,
self.cloud.delete_volume_snapshot, self.cloud.delete_volume_snapshot,
name_or_id='1234', name_or_id='1234',
wait=True, wait=True,

View File

@ -10,7 +10,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -43,7 +43,7 @@ class TestDomainParams(base.TestCase):
project_data = self._get_project_data(v3=True) project_data = self._get_project_data(v3=True)
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud._get_identity_params, self.cloud._get_identity_params,
domain_id=None, domain_id=None,
project=project_data.project_name, project=project_data.project_name,

View File

@ -18,7 +18,7 @@ import uuid
import testtools import testtools
from testtools import matchers from testtools import matchers
import openstack.cloud from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -145,9 +145,7 @@ class TestDomains(base.TestCase):
domain_data = self._get_domain_data( domain_data = self._get_domain_data(
domain_name='domain_name', enabled=True domain_name='domain_name', enabled=True
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.BadRequestException):
openstack.cloud.OpenStackCloudBadRequest
):
self.register_uris( self.register_uris(
[ [
dict( dict(
@ -237,9 +235,7 @@ class TestDomains(base.TestCase):
), ),
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.ResourceNotFound):
openstack.exceptions.ResourceNotFound
):
self.cloud.delete_domain(domain_data.domain_id) self.cloud.delete_domain(domain_data.domain_id)
self.assert_calls() self.assert_calls()
@ -320,8 +316,6 @@ class TestDomains(base.TestCase):
) )
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.ConflictException):
openstack.exceptions.ConflictException
):
self.cloud.delete_domain(domain_data.domain_id) self.cloud.delete_domain(domain_data.domain_id)
self.assert_calls() self.assert_calls()

View File

@ -10,8 +10,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from openstack import exceptions
import openstack.cloud
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -136,7 +135,7 @@ class TestFlavors(base.TestCase):
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_flavor, self.cloud.delete_flavor,
'vanilla', 'vanilla',
) )
@ -278,7 +277,7 @@ class TestFlavors(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_flavor_by_ram, self.cloud.get_flavor_by_ram,
ram=100, ram=100,
) )

View File

@ -22,7 +22,7 @@ Tests Floating IP resource methods for Neutron
import copy import copy
import datetime import datetime
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
from openstack import utils from openstack import utils
@ -341,7 +341,7 @@ class TestFloatingIP(base.TestCase):
# Fails because we requested a port and the returned FIP has no port # Fails because we requested a port and the returned FIP has no port
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_floating_ip, self.cloud.create_floating_ip,
network='my-network', network='my-network',
port='ce705c24-c1ef-408a-bda3-7bbd946164ab', port='ce705c24-c1ef-408a-bda3-7bbd946164ab',
@ -492,7 +492,7 @@ class TestFloatingIP(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud._neutron_available_floating_ips, self.cloud._neutron_available_floating_ips,
network='INVALID', network='INVALID',
) )
@ -993,7 +993,7 @@ class TestFloatingIP(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_floating_ip, self.cloud.delete_floating_ip,
floating_ip_id=fip_id, floating_ip_id=fip_id,
retry=2, retry=2,
@ -1313,7 +1313,7 @@ class TestFloatingIP(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud._neutron_create_floating_ip, self.cloud._neutron_create_floating_ip,
server=dict(id='some-server'), server=dict(id='some-server'),
) )

View File

@ -19,7 +19,7 @@ test_floating_ip_pool
Test floating IP pool resource (managed by nova) Test floating IP pool resource (managed by nova)
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -96,7 +96,8 @@ class TestFloatingIPPool(base.TestCase):
) )
self.assertRaises( self.assertRaises(
OpenStackCloudException, self.cloud.list_floating_ip_pools exceptions.SDKException,
self.cloud.list_floating_ip_pools,
) )
self.assert_calls() self.assert_calls()

View File

@ -18,7 +18,6 @@ import tempfile
from unittest import mock from unittest import mock
import uuid import uuid
from openstack.cloud import exc
from openstack.cloud import meta from openstack.cloud import meta
from openstack import connection from openstack import connection
from openstack import exceptions from openstack import exceptions
@ -70,7 +69,7 @@ class TestImage(BaseTestImage):
def test_download_image_no_output(self): def test_download_image_no_output(self):
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.download_image, self.cloud.download_image,
self.image_name, self.image_name,
) )
@ -78,7 +77,7 @@ class TestImage(BaseTestImage):
def test_download_image_two_outputs(self): def test_download_image_two_outputs(self):
fake_fd = io.BytesIO() fake_fd = io.BytesIO()
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.download_image, self.cloud.download_image,
self.image_name, self.image_name,
output_path='fake_path', output_path='fake_path',
@ -110,7 +109,7 @@ class TestImage(BaseTestImage):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudResourceNotFound, exceptions.NotFoundException,
self.cloud.download_image, self.cloud.download_image,
self.image_name, self.image_name,
output_path='fake_path', output_path='fake_path',
@ -1354,7 +1353,7 @@ class TestImage(BaseTestImage):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudHTTPError, exceptions.HttpException,
self._call_create_image, self._call_create_image,
self.image_name, self.image_name,
) )
@ -1470,7 +1469,7 @@ class TestImage(BaseTestImage):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudHTTPError, exceptions.HttpException,
self._call_create_image, self._call_create_image,
self.image_name, self.image_name,
) )
@ -1556,7 +1555,7 @@ class TestImage(BaseTestImage):
self.cloud.image_api_use_tasks = False self.cloud.image_api_use_tasks = False
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self._call_create_image, self._call_create_image,
self.image_name, self.image_name,
allow_duplicates=True, allow_duplicates=True,

View File

@ -14,7 +14,7 @@
import uuid import uuid
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -66,7 +66,7 @@ class TestImageSnapshot(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudTimeout, exceptions.ResourceTimeout,
self.cloud.create_image_snapshot, self.cloud.create_image_snapshot,
snapshot_name, snapshot_name,
dict(id=self.server_id), dict(id=self.server_id),

View File

@ -13,7 +13,7 @@
import fixtures import fixtures
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -83,7 +83,7 @@ class TestKeypair(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_keypair, self.cloud.create_keypair,
self.keyname, self.keyname,
self.key['public_key'], self.key['public_key'],
@ -195,7 +195,5 @@ class TestKeypair(base.TestCase):
), ),
] ]
) )
self.assertRaises( self.assertRaises(exceptions.SDKException, self.cloud.list_keypairs)
exc.OpenStackCloudException, self.cloud.list_keypairs
)
self.assert_calls() self.assert_calls()

View File

@ -15,8 +15,6 @@ from unittest import mock
import testtools import testtools
import openstack
import openstack.cloud
from openstack import exceptions from openstack import exceptions
from openstack.network.v2 import network as _network from openstack.network.v2 import network as _network
from openstack.tests.unit import base from openstack.tests.unit import base
@ -468,7 +466,7 @@ class TestNetworks(base.TestCase):
def test_create_network_wrong_availability_zone_hints_type(self): def test_create_network_wrong_availability_zone_hints_type(self):
azh_opts = "invalid" azh_opts = "invalid"
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Parameter 'availability_zone_hints' must be a list", "Parameter 'availability_zone_hints' must be a list",
): ):
self.cloud.create_network( self.cloud.create_network(
@ -478,7 +476,7 @@ class TestNetworks(base.TestCase):
def test_create_network_provider_wrong_type(self): def test_create_network_provider_wrong_type(self):
provider_opts = "invalid" provider_opts = "invalid"
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Parameter 'provider' must be a dict", "Parameter 'provider' must be a dict",
): ):
self.cloud.create_network("netname", provider=provider_opts) self.cloud.create_network("netname", provider=provider_opts)
@ -543,14 +541,14 @@ class TestNetworks(base.TestCase):
def test_create_network_with_wrong_mtu_size(self): def test_create_network_with_wrong_mtu_size(self):
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Parameter 'mtu_size' must be greater than 67.", "Parameter 'mtu_size' must be greater than 67.",
): ):
self.cloud.create_network("netname", mtu_size=42) self.cloud.create_network("netname", mtu_size=42)
def test_create_network_with_wrong_mtu_type(self): def test_create_network_with_wrong_mtu_type(self):
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Parameter 'mtu_size' must be an integer.", "Parameter 'mtu_size' must be an integer.",
): ):
self.cloud.create_network("netname", mtu_size="fourty_two") self.cloud.create_network("netname", mtu_size="fourty_two")
@ -658,7 +656,7 @@ class TestNetworks(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_network, self.cloud.delete_network,
network_name, network_name,
) )

View File

@ -17,8 +17,6 @@ from unittest import mock
import testtools import testtools
import openstack.cloud
from openstack.cloud import exc
import openstack.cloud.openstackcloud as oc_oc import openstack.cloud.openstackcloud as oc_oc
from openstack import exceptions from openstack import exceptions
from openstack.object_store.v1 import _proxy from openstack.object_store.v1 import _proxy
@ -198,7 +196,7 @@ class TestObject(BaseTestObject):
] ]
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_container, self.cloud.delete_container,
self.container, self.container,
) )
@ -231,7 +229,7 @@ class TestObject(BaseTestObject):
[dict(method='POST', uri=self.container_endpoint, status_code=409)] [dict(method='POST', uri=self.container_endpoint, status_code=409)]
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_container, self.cloud.update_container,
self.container, self.container,
dict(foo='bar'), dict(foo='bar'),
@ -284,7 +282,7 @@ class TestObject(BaseTestObject):
def test_set_container_access_invalid(self): def test_set_container_access_invalid(self):
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.set_container_access, self.cloud.set_container_access,
self.container, self.container,
'invalid', 'invalid',
@ -319,7 +317,7 @@ class TestObject(BaseTestObject):
) )
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Could not determine container access for ACL: invalid", "Could not determine container access for ACL: invalid",
): ):
self.cloud.get_container_access(self.container) self.cloud.get_container_access(self.container)
@ -329,7 +327,7 @@ class TestObject(BaseTestObject):
[dict(method='HEAD', uri=self.container_endpoint, status_code=404)] [dict(method='HEAD', uri=self.container_endpoint, status_code=404)]
) )
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Container not found: %s" % self.container, "Container not found: %s" % self.container,
): ):
self.cloud.get_container_access(self.container) self.cloud.get_container_access(self.container)
@ -368,9 +366,7 @@ class TestObject(BaseTestObject):
] ]
) )
self.assertRaises( self.assertRaises(exceptions.SDKException, self.cloud.list_containers)
exc.OpenStackCloudException, self.cloud.list_containers
)
self.assert_calls() self.assert_calls()
@mock.patch.object(_proxy, '_get_expiration', return_value=13345) @mock.patch.object(_proxy, '_get_expiration', return_value=13345)
@ -660,7 +656,7 @@ class TestObject(BaseTestObject):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.list_objects, self.cloud.list_objects,
self.container, self.container,
) )
@ -798,7 +794,7 @@ class TestObject(BaseTestObject):
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_object, self.cloud.get_object,
self.container, self.container,
self.object, self.object,
@ -1511,7 +1507,7 @@ class TestObjectUploads(BaseTestObject):
self.cloud.image_api_use_tasks = True self.cloud.image_api_use_tasks = True
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_object, self.cloud.create_object,
container=self.container, container=self.container,
name=self.object, name=self.object,
@ -1594,7 +1590,7 @@ class TestObjectUploads(BaseTestObject):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_object, self.cloud.create_object,
container=self.container, container=self.container,
name=self.object, name=self.object,

View File

@ -15,8 +15,8 @@ import uuid
import testtools import testtools
from openstack.cloud import exc
from openstack.config import cloud_region from openstack.config import cloud_region
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -90,7 +90,7 @@ class TestOperatorCloud(base.TestCase):
self.cloud.name = 'testcloud' self.cloud.name = 'testcloud'
self.cloud.config.config['region_name'] = 'testregion' self.cloud.config.config['region_name'] = 'testregion'
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Error getting image endpoint on testcloud:testregion:" "Error getting image endpoint on testcloud:testregion:"
" No service", " No service",
): ):

View File

@ -19,7 +19,7 @@ test_port
Test port resource (managed by neutron) Test port resource (managed by neutron)
""" """
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.network.v2 import port as _port from openstack.network.v2 import port as _port
from openstack.tests.unit import base from openstack.tests.unit import base
@ -203,7 +203,7 @@ class TestPort(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
OpenStackCloudException, exceptions.SDKException,
self.cloud.create_port, self.cloud.create_port,
network_id='test-net-id', network_id='test-net-id',
name='test-port-name', name='test-port-name',
@ -312,7 +312,7 @@ class TestPort(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
OpenStackCloudException, exceptions.SDKException,
self.cloud.update_port, self.cloud.update_port,
name_or_id='d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b', name_or_id='d80b1a3b-4fc1-49f3-952e-1e2ab7081d8b',
name='test-port-name-updated', name='test-port-name-updated',
@ -368,7 +368,7 @@ class TestPort(base.TestCase):
) )
] ]
) )
self.assertRaises(OpenStackCloudException, self.cloud.list_ports) self.assertRaises(exceptions.SDKException, self.cloud.list_ports)
def test_search_ports_by_id(self): def test_search_ports_by_id(self):
port_id = 'f71a6703-d6de-4be1-a91a-a570ede1d159' port_id = 'f71a6703-d6de-4be1-a91a-a570ede1d159'
@ -514,7 +514,7 @@ class TestPort(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
OpenStackCloudException, self.cloud.delete_port, port_name exceptions.SDKException, self.cloud.delete_port, port_name
) )
self.assert_calls() self.assert_calls()

View File

@ -15,8 +15,7 @@ import uuid
import testtools import testtools
from testtools import matchers from testtools import matchers
import openstack.cloud from openstack import exceptions
import openstack.cloud._utils
from openstack.tests.unit import base from openstack.tests.unit import base
@ -129,7 +128,7 @@ class TestProject(base.TestCase):
# shade will raise an attribute error instead of the proper # shade will raise an attribute error instead of the proper
# project not found exception. # project not found exception.
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Project %s not found." % project_data.project_id, "Project %s not found." % project_data.project_id,
): ):
self.cloud.update_project(project_data.project_id) self.cloud.update_project(project_data.project_id)

View File

@ -15,7 +15,7 @@
import copy import copy
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import qos_bandwidth_limit_rule from openstack.network.v2 import qos_bandwidth_limit_rule
from openstack.tests.unit import base from openstack.tests.unit import base
@ -164,7 +164,7 @@ class TestQosBandwidthLimitRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudResourceNotFound, exceptions.NotFoundException,
self.cloud.get_qos_bandwidth_limit_rule, self.cloud.get_qos_bandwidth_limit_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -184,7 +184,7 @@ class TestQosBandwidthLimitRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_bandwidth_limit_rule, self.cloud.get_qos_bandwidth_limit_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -256,7 +256,7 @@ class TestQosBandwidthLimitRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_qos_bandwidth_limit_rule, self.cloud.create_qos_bandwidth_limit_rule,
self.policy_name, self.policy_name,
max_kbps=100, max_kbps=100,
@ -403,7 +403,7 @@ class TestQosBandwidthLimitRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_qos_bandwidth_limit_rule, self.cloud.update_qos_bandwidth_limit_rule,
self.policy_id, self.policy_id,
self.rule_id, self.rule_id,
@ -558,7 +558,7 @@ class TestQosBandwidthLimitRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_qos_bandwidth_limit_rule, self.cloud.delete_qos_bandwidth_limit_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,

View File

@ -15,7 +15,7 @@
import copy import copy
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import qos_dscp_marking_rule from openstack.network.v2 import qos_dscp_marking_rule
from openstack.tests.unit import base from openstack.tests.unit import base
@ -147,7 +147,7 @@ class TestQosDscpMarkingRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudResourceNotFound, exceptions.NotFoundException,
self.cloud.get_qos_dscp_marking_rule, self.cloud.get_qos_dscp_marking_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -167,7 +167,7 @@ class TestQosDscpMarkingRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_dscp_marking_rule, self.cloud.get_qos_dscp_marking_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -239,7 +239,7 @@ class TestQosDscpMarkingRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_qos_dscp_marking_rule, self.cloud.create_qos_dscp_marking_rule,
self.policy_name, self.policy_name,
dscp_mark=16, dscp_mark=16,
@ -328,7 +328,7 @@ class TestQosDscpMarkingRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_qos_dscp_marking_rule, self.cloud.update_qos_dscp_marking_rule,
self.policy_id, self.policy_id,
self.rule_id, self.rule_id,
@ -403,7 +403,7 @@ class TestQosDscpMarkingRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_qos_dscp_marking_rule, self.cloud.delete_qos_dscp_marking_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,

View File

@ -15,7 +15,7 @@
import copy import copy
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import qos_minimum_bandwidth_rule from openstack.network.v2 import qos_minimum_bandwidth_rule
from openstack.tests.unit import base from openstack.tests.unit import base
@ -148,7 +148,7 @@ class TestQosMinimumBandwidthRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudResourceNotFound, exceptions.NotFoundException,
self.cloud.get_qos_minimum_bandwidth_rule, self.cloud.get_qos_minimum_bandwidth_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -168,7 +168,7 @@ class TestQosMinimumBandwidthRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_minimum_bandwidth_rule, self.cloud.get_qos_minimum_bandwidth_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,
@ -240,7 +240,7 @@ class TestQosMinimumBandwidthRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_qos_minimum_bandwidth_rule, self.cloud.create_qos_minimum_bandwidth_rule,
self.policy_name, self.policy_name,
min_kbps=100, min_kbps=100,
@ -328,7 +328,7 @@ class TestQosMinimumBandwidthRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_qos_minimum_bandwidth_rule, self.cloud.update_qos_minimum_bandwidth_rule,
self.policy_id, self.policy_id,
self.rule_id, self.rule_id,
@ -403,7 +403,7 @@ class TestQosMinimumBandwidthRule(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_qos_minimum_bandwidth_rule, self.cloud.delete_qos_minimum_bandwidth_rule,
self.policy_name, self.policy_name,
self.rule_id, self.rule_id,

View File

@ -15,7 +15,7 @@
import copy import copy
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import qos_policy as _policy from openstack.network.v2 import qos_policy as _policy
from openstack.tests.unit import base from openstack.tests.unit import base
@ -110,7 +110,7 @@ class TestQosPolicy(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_policy, self.cloud.get_qos_policy,
self.policy_name, self.policy_name,
) )
@ -154,7 +154,7 @@ class TestQosPolicy(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_qos_policy, self.cloud.create_qos_policy,
name=self.policy_name, name=self.policy_name,
) )
@ -256,7 +256,7 @@ class TestQosPolicy(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_qos_policy, self.cloud.delete_qos_policy,
self.policy_name, self.policy_name,
) )
@ -330,7 +330,7 @@ class TestQosPolicy(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_qos_policy, self.cloud.delete_qos_policy,
self.policy_name, self.policy_name,
) )
@ -420,7 +420,7 @@ class TestQosPolicy(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_qos_policy, self.cloud.update_qos_policy,
self.policy_id, self.policy_id,
name="goofy", name="goofy",

View File

@ -13,7 +13,7 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import qos_rule_type from openstack.network.v2 import qos_rule_type
from openstack.tests.unit import base from openstack.tests.unit import base
@ -117,7 +117,7 @@ class TestQosRuleType(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, self.cloud.list_qos_rule_types exceptions.SDKException, self.cloud.list_qos_rule_types
) )
self.assert_calls() self.assert_calls()
@ -184,7 +184,7 @@ class TestQosRuleType(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_rule_type_details, self.cloud.get_qos_rule_type_details,
self.rule_type_name, self.rule_type_name,
) )
@ -210,7 +210,7 @@ class TestQosRuleType(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.get_qos_rule_type_details, self.cloud.get_qos_rule_type_details,
self.rule_type_name, self.rule_type_name,
) )

View File

@ -10,7 +10,7 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import quota as _quota from openstack.network.v2 import quota as _quota
from openstack.tests.unit import base from openstack.tests.unit import base
@ -100,7 +100,7 @@ class TestQuotas(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.set_compute_quotas, self.cloud.set_compute_quotas,
project.project_id, project.project_id,
) )

View File

@ -21,7 +21,7 @@ Tests for the `rebuild_server` command.
import uuid import uuid
from openstack.cloud import exc from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -65,7 +65,7 @@ class TestRebuildServer(base.TestCase):
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.rebuild_server, self.cloud.rebuild_server,
self.fake_server['id'], self.fake_server['id'],
"a", "a",
@ -102,7 +102,7 @@ class TestRebuildServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.rebuild_server, self.cloud.rebuild_server,
self.fake_server['id'], self.fake_server['id'],
"a", "a",
@ -139,7 +139,7 @@ class TestRebuildServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudTimeout, exceptions.ResourceTimeout,
self.cloud.rebuild_server, self.cloud.rebuild_server,
self.fake_server['id'], self.fake_server['id'],
"a", "a",

View File

@ -14,7 +14,7 @@
import testtools import testtools
from testtools import matchers from testtools import matchers
from openstack.cloud import exc from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -1739,7 +1739,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Role {0} not found'.format(self.role_data.role_name), 'Role {0} not found'.format(self.role_data.role_name),
): ):
self.cloud.grant_role( self.cloud.grant_role(
@ -1779,7 +1779,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Role {0} not found'.format(self.role_data.role_name), 'Role {0} not found'.format(self.role_data.role_name),
): ):
self.cloud.revoke_role( self.cloud.revoke_role(
@ -1795,7 +1795,7 @@ class TestRoleAssignment(base.TestCase):
) )
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a user or a group', 'Must specify either a user or a group',
): ):
self.cloud.grant_role(self.role_data.role_name) self.cloud.grant_role(self.role_data.role_name)
@ -1807,7 +1807,7 @@ class TestRoleAssignment(base.TestCase):
) )
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a user or a group', 'Must specify either a user or a group',
): ):
self.cloud.revoke_role(self.role_data.role_name) self.cloud.revoke_role(self.role_data.role_name)
@ -1823,7 +1823,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a user or a group', 'Must specify either a user or a group',
): ):
self.cloud.grant_role( self.cloud.grant_role(
@ -1841,7 +1841,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a user or a group', 'Must specify either a user or a group',
): ):
self.cloud.revoke_role( self.cloud.revoke_role(
@ -1862,7 +1862,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Specify either a group or a user, not both', 'Specify either a group or a user, not both',
): ):
self.cloud.grant_role( self.cloud.grant_role(
@ -1885,7 +1885,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Specify either a group or a user, not both', 'Specify either a group or a user, not both',
): ):
self.cloud.revoke_role( self.cloud.revoke_role(
@ -2017,7 +2017,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a domain, project or system', 'Must specify either a domain, project or system',
): ):
self.cloud.grant_role( self.cloud.grant_role(
@ -2036,7 +2036,7 @@ class TestRoleAssignment(base.TestCase):
self.register_uris(uris) self.register_uris(uris)
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
'Must specify either a domain, project or system', 'Must specify either a domain, project or system',
): ):
self.cloud.revoke_role( self.cloud.revoke_role(
@ -2063,7 +2063,7 @@ class TestRoleAssignment(base.TestCase):
), ),
] ]
) )
with testtools.ExpectedException(exc.OpenStackCloudURINotFound): with testtools.ExpectedException(exceptions.NotFoundException):
self.cloud.grant_role( self.cloud.grant_role(
self.role_data.role_name, self.role_data.role_name,
user=self.user_data.name, user=self.user_data.name,
@ -2090,7 +2090,7 @@ class TestRoleAssignment(base.TestCase):
), ),
] ]
) )
with testtools.ExpectedException(exc.OpenStackCloudURINotFound): with testtools.ExpectedException(exceptions.NotFoundException):
self.cloud.revoke_role( self.cloud.revoke_role(
self.role_data.role_name, self.role_data.role_name,
user=self.user_data.name, user=self.user_data.name,

View File

@ -17,7 +17,7 @@ import copy
import testtools import testtools
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import port as _port from openstack.network.v2 import port as _port
from openstack.network.v2 import router as _router from openstack.network.v2 import router as _router
from openstack.tests.unit import base from openstack.tests.unit import base
@ -315,7 +315,7 @@ class TestRouter(base.TestCase):
def test_create_router_wrong_availability_zone_hints_type(self): def test_create_router_wrong_availability_zone_hints_type(self):
azh_opts = "invalid" azh_opts = "invalid"
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, exceptions.SDKException,
"Parameter 'availability_zone_hints' must be a list", "Parameter 'availability_zone_hints' must be a list",
): ):
self.cloud.create_router( self.cloud.create_router(
@ -522,7 +522,7 @@ class TestRouter(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, self.cloud.delete_router, 'mickey' exceptions.SDKException, self.cloud.delete_router, 'mickey'
) )
self.assert_calls() self.assert_calls()

View File

@ -14,6 +14,7 @@
import copy import copy
import openstack.cloud import openstack.cloud
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -786,7 +787,7 @@ class TestSecurityGroups(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_security_group_rule, self.cloud.create_security_group_rule,
secgroup_name_or_id='nova-sec-group', secgroup_name_or_id='nova-sec-group',
direction='egress', direction='egress',

View File

@ -19,7 +19,7 @@ Tests for the `delete_server_metadata` command.
import uuid import uuid
from openstack.cloud.exc import OpenStackCloudURINotFound from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -65,7 +65,7 @@ class TestServerDeleteMetadata(base.TestCase):
) )
self.assertRaises( self.assertRaises(
OpenStackCloudURINotFound, exceptions.NotFoundException,
self.cloud.delete_server_metadata, self.cloud.delete_server_metadata,
self.server_name, self.server_name,
['key'], ['key'],

View File

@ -19,7 +19,7 @@ Tests for the `set_server_metadata` command.
import uuid import uuid
from openstack.cloud.exc import OpenStackCloudBadRequest from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -59,7 +59,7 @@ class TestServerSetMetadata(base.TestCase):
) )
self.assertRaises( self.assertRaises(
OpenStackCloudBadRequest, exceptions.BadRequestException,
self.cloud.set_server_metadata, self.cloud.set_server_metadata,
self.server_name, self.server_name,
{'meta': 'data'}, {'meta': 'data'},

View File

@ -21,7 +21,7 @@ Tests Keystone services commands.
from testtools import matchers from testtools import matchers
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -203,7 +203,7 @@ class CloudServices(base.TestCase):
# Multiple matches # Multiple matches
# test we are getting an Exception # test we are getting an Exception
self.assertRaises( self.assertRaises(
OpenStackCloudException, exceptions.SDKException,
self.cloud.get_service, self.cloud.get_service,
name_or_id=None, name_or_id=None,
filters={'type': 'type2'}, filters={'type': 'type2'},

View File

@ -14,7 +14,7 @@ import tempfile
import testtools import testtools
import openstack.cloud from openstack import exceptions
from openstack.orchestration.v1 import stack from openstack.orchestration.v1 import stack
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -95,9 +95,7 @@ class TestStack(base.TestCase):
) )
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.NotFoundException):
openstack.cloud.OpenStackCloudURINotFound
):
self.cloud.list_stacks() self.cloud.list_stacks()
self.assert_calls() self.assert_calls()
@ -160,9 +158,7 @@ class TestStack(base.TestCase):
) )
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.NotFoundException):
openstack.cloud.OpenStackCloudURINotFound
):
self.cloud.search_stacks() self.cloud.search_stacks()
def test_delete_stack(self): def test_delete_stack(self):
@ -264,9 +260,7 @@ class TestStack(base.TestCase):
), ),
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.BadRequestException):
openstack.cloud.OpenStackCloudBadRequest
):
self.cloud.delete_stack(self.stack_id) self.cloud.delete_stack(self.stack_id)
self.assert_calls() self.assert_calls()
@ -550,9 +544,7 @@ class TestStack(base.TestCase):
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(exceptions.SDKException):
openstack.cloud.OpenStackCloudException
):
self.cloud.delete_stack(self.stack_id, wait=True) self.cloud.delete_stack(self.stack_id, wait=True)
self.assert_calls() self.assert_calls()

View File

@ -17,7 +17,7 @@ import copy
import testtools import testtools
from openstack.cloud import exc from openstack import exceptions
from openstack.network.v2 import subnet as _subnet from openstack.network.v2 import subnet as _subnet
from openstack.tests.unit import base from openstack.tests.unit import base
@ -253,7 +253,7 @@ class TestSubnet(base.TestCase):
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(
exc.OpenStackCloudException, "ip_version must be an integer" exceptions.SDKException, "ip_version must be an integer"
): ):
self.cloud.create_subnet( self.cloud.create_subnet(
self.network_name, self.subnet_cidr, ip_version='4x' self.network_name, self.subnet_cidr, ip_version='4x'
@ -407,7 +407,7 @@ class TestSubnet(base.TestCase):
) )
gateway = '192.168.200.3' gateway = '192.168.200.3'
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_subnet, self.cloud.create_subnet,
'kooky', 'kooky',
self.subnet_cidr, self.subnet_cidr,
@ -441,7 +441,7 @@ class TestSubnet(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_subnet, self.cloud.create_subnet,
'duck', 'duck',
self.subnet_cidr, self.subnet_cidr,
@ -475,7 +475,7 @@ class TestSubnet(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.create_subnet, self.cloud.create_subnet,
self.network_name, self.network_name,
self.subnet_cidr, self.subnet_cidr,
@ -731,7 +731,7 @@ class TestSubnet(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.delete_subnet, self.cloud.delete_subnet,
self.subnet_name, self.subnet_name,
) )
@ -859,7 +859,7 @@ class TestSubnet(base.TestCase):
def test_update_subnet_conflict_gw_ops(self): def test_update_subnet_conflict_gw_ops(self):
self.assertRaises( self.assertRaises(
exc.OpenStackCloudException, exceptions.SDKException,
self.cloud.update_subnet, self.cloud.update_subnet,
self.subnet_id, self.subnet_id,
gateway_ip="192.168.199.3", gateway_ip="192.168.199.3",

View File

@ -19,7 +19,7 @@ Tests for the `update_server` command.
import uuid import uuid
from openstack.cloud.exc import OpenStackCloudException from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -74,7 +74,7 @@ class TestUpdateServer(base.TestCase):
] ]
) )
self.assertRaises( self.assertRaises(
OpenStackCloudException, exceptions.SDKException,
self.cloud.update_server, self.cloud.update_server,
self.server_name, self.server_name,
name=self.updated_server_name, name=self.updated_server_name,

View File

@ -14,7 +14,7 @@ import uuid
import testtools import testtools
import openstack.cloud from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -83,7 +83,7 @@ class TestUsers(base.TestCase):
domain_id=uuid.uuid4().hex, email='test@example.com' domain_id=uuid.uuid4().hex, email='test@example.com'
) )
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"User or project creation requires an explicit" "User or project creation requires an explicit"
" domain_id argument.", " domain_id argument.",
): ):

View File

@ -14,9 +14,9 @@
import testtools import testtools
from openstack.block_storage.v3 import volume from openstack.block_storage.v3 import volume
import openstack.cloud
from openstack.cloud import meta from openstack.cloud import meta
from openstack.compute.v2 import volume_attachment from openstack.compute.v2 import volume_attachment
from openstack import exceptions
from openstack.tests import fakes from openstack.tests import fakes
from openstack.tests.unit import base from openstack.tests.unit import base
@ -105,7 +105,7 @@ class TestVolume(base.TestCase):
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudURINotFound exceptions.NotFoundException,
): ):
self.cloud.attach_volume(server, volume, wait=False) self.cloud.attach_volume(server, volume, wait=False)
self.assert_calls() self.assert_calls()
@ -225,7 +225,7 @@ class TestVolume(base.TestCase):
] ]
) )
with testtools.ExpectedException(openstack.exceptions.ResourceFailure): with testtools.ExpectedException(exceptions.ResourceFailure):
self.cloud.attach_volume(server, volume) self.cloud.attach_volume(server, volume)
self.assert_calls() self.assert_calls()
@ -234,7 +234,7 @@ class TestVolume(base.TestCase):
volume = dict(id='volume001', status='error', attachments=[]) volume = dict(id='volume001', status='error', attachments=[])
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Volume %s is not available. Status is '%s'" "Volume %s is not available. Status is '%s'"
% (volume['id'], volume['status']), % (volume['id'], volume['status']),
): ):
@ -250,7 +250,7 @@ class TestVolume(base.TestCase):
) )
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"Volume %s already attached to server %s on device %s" "Volume %s already attached to server %s on device %s"
% (volume['id'], server['id'], device_id), % (volume['id'], server['id'], device_id),
): ):
@ -324,7 +324,7 @@ class TestVolume(base.TestCase):
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudURINotFound exceptions.NotFoundException,
): ):
self.cloud.detach_volume(server, volume, wait=False) self.cloud.detach_volume(server, volume, wait=False)
self.assert_calls() self.assert_calls()
@ -433,7 +433,7 @@ class TestVolume(base.TestCase):
), ),
] ]
) )
with testtools.ExpectedException(openstack.exceptions.ResourceFailure): with testtools.ExpectedException(exceptions.ResourceFailure):
self.cloud.detach_volume(server, volume) self.cloud.detach_volume(server, volume)
self.assert_calls() self.assert_calls()

View File

@ -12,10 +12,9 @@
# License for the specific language governing permissions and limitations # License for the specific language governing permissions and limitations
# under the License. # under the License.
import testtools import testtools
import openstack.cloud from openstack import exceptions
from openstack.tests.unit import base from openstack.tests.unit import base
@ -297,7 +296,7 @@ class TestVolumeAccess(base.TestCase):
] ]
) )
with testtools.ExpectedException( with testtools.ExpectedException(
openstack.cloud.OpenStackCloudException, exceptions.SDKException,
"VolumeType not found: MISSING", "VolumeType not found: MISSING",
): ):
self.cloud.add_volume_type_access( self.cloud.add_volume_type_access(