Browse Source

Remove six.text_type (1/2)

Replace six.text_type with str.
A subsequent patch will replace other six.text_type.

Change-Id: I23bb9e539d08f5c6202909054c2dd49b6c7a7a0e
Implements: blueprint six-removal
Signed-off-by: Takashi Natsume <takanattie@gmail.com>
changes/09/728109/39
Takashi Natsume 2 years ago
parent
commit
383e2a8bdc
  1. 4
      nova/accelerator/cyborg.py
  2. 3
      nova/api/metadata/base.py
  3. 9
      nova/api/metadata/handler.py
  4. 5
      nova/api/openstack/common.py
  5. 5
      nova/api/openstack/compute/aggregates.py
  6. 3
      nova/api/openstack/compute/assisted_volume_snapshots.py
  7. 3
      nova/api/openstack/compute/flavors_extraspecs.py
  8. 3
      nova/api/openstack/compute/servers.py
  9. 3
      nova/api/openstack/compute/services.py
  10. 3
      nova/api/openstack/compute/simple_tenant_usage.py
  11. 13
      nova/api/openstack/wsgi.py
  12. 7
      nova/api/validation/validators.py
  13. 17
      nova/cmd/manage.py
  14. 5
      nova/cmd/status.py
  15. 9
      nova/compute/api.py
  16. 3
      nova/compute/flavors.py
  17. 49
      nova/compute/manager.py
  18. 3
      nova/compute/utils.py
  19. 7
      nova/conductor/manager.py
  20. 4
      nova/conductor/tasks/live_migrate.py
  21. 3
      nova/console/rfb/authvencrypt.py
  22. 7
      nova/console/securityproxy/rfb.py
  23. 5
      nova/db/sqlalchemy/api.py
  24. 3
      nova/exception.py
  25. 15
      nova/image/glance.py
  26. 13
      nova/network/neutron.py
  27. 28
      nova/network/security_group_api.py
  28. 7
      nova/objects/image_meta.py
  29. 3
      nova/objects/instance_mapping.py
  30. 3
      nova/pci/request.py
  31. 4
      nova/privsep/fs.py
  32. 5
      nova/rpc.py
  33. 3
      nova/scheduler/client/report.py
  34. 3
      nova/scheduler/manager.py
  35. 15
      nova/utils.py
  36. 3
      nova/virt/configdrive.py
  37. 5
      nova/virt/disk/mount/nbd.py
  38. 4
      nova/virt/disk/vfs/guestfs.py
  39. 5
      nova/virt/driver.py
  40. 5
      nova/virt/hardware.py
  41. 3
      nova/virt/hyperv/pathutils.py
  42. 3
      nova/virt/hyperv/serialconsoleops.py
  43. 35
      nova/virt/ironic/driver.py
  44. 3
      nova/virt/libvirt/config.py
  45. 5
      nova/virt/libvirt/driver.py
  46. 3
      nova/virt/libvirt/imagebackend.py
  47. 3
      nova/virt/libvirt/storage/lvm.py
  48. 3
      nova/virt/libvirt/volume/mount.py
  49. 3
      nova/virt/libvirt/volume/quobyte.py
  50. 5
      nova/virt/libvirt/volume/remotefs.py
  51. 3
      nova/virt/powervm/driver.py
  52. 3
      nova/virt/powervm/vif.py
  53. 7
      nova/virt/powervm/vm.py
  54. 3
      nova/virt/powervm/volume/fcvscsi.py
  55. 3
      nova/virt/zvm/driver.py
  56. 7
      nova/virt/zvm/utils.py
  57. 17
      nova/volume/cinder.py

4
nova/accelerator/cyborg.py

@ -12,8 +12,6 @@
# License for the specific language governing permissions and limitations
# under the License.
import six
from oslo_log import log as logging
from keystoneauth1 import exceptions as ks_exc
@ -95,7 +93,7 @@ class _CyborgClient(object):
err_msg = msg + str(resp)
except ks_exc.ClientException as exc:
err_msg = _('Could not communicate with Cyborg.')
LOG.exception('%s: %s', err_msg, six.text_type(exc))
LOG.exception('%s: %s', err_msg, str(exc))
return resp, err_msg

3
nova/api/metadata/base.py

@ -24,7 +24,6 @@ from oslo_log import log as logging
from oslo_serialization import base64
from oslo_serialization import jsonutils
from oslo_utils import timeutils
import six
from nova.api.metadata import password
from nova.api.metadata import vendordata_dynamic
@ -718,7 +717,7 @@ def ec2_md_print(data):
return output[:-1]
elif isinstance(data, list):
return '\n'.join(data)
elif isinstance(data, (bytes, six.text_type)):
elif isinstance(data, (bytes, str)):
return data
else:
return str(data)

9
nova/api/metadata/handler.py

@ -23,7 +23,6 @@ from oslo_log import log as logging
from oslo_utils import encodeutils
from oslo_utils import secretutils as secutils
from oslo_utils import strutils
import six
import webob.dec
import webob.exc
@ -151,8 +150,7 @@ class MetadataRequestHandler(wsgi.Application):
remote_address)
msg = _('An unknown error has occurred. '
'Please try your request again.')
raise webob.exc.HTTPInternalServerError(
explanation=six.text_type(msg))
raise webob.exc.HTTPInternalServerError(explanation=str(msg))
if meta_data is None:
LOG.error('Failed to get metadata for IP %s: no metadata',
@ -262,7 +260,7 @@ class MetadataRequestHandler(wsgi.Application):
# instance_data is unicode-encoded, while cache_utils doesn't like
# that. Therefore we convert to str
if isinstance(instance_id, six.text_type):
if isinstance(instance_id, str):
instance_id = instance_id.encode('utf-8')
return instance_id, tenant_id
@ -329,8 +327,7 @@ class MetadataRequestHandler(wsgi.Application):
instance_id)
msg = _('An unknown error has occurred. '
'Please try your request again.')
raise webob.exc.HTTPInternalServerError(
explanation=six.text_type(msg))
raise webob.exc.HTTPInternalServerError(explanation=str(msg))
if meta_data is None:
LOG.error('Failed to get metadata for instance id: %s',

5
nova/api/openstack/common.py

@ -20,7 +20,6 @@ from urllib import parse as urlparse
from oslo_log import log as logging
from oslo_utils import strutils
import six
import webob
from webob import exc
@ -508,7 +507,7 @@ def is_all_tenants(search_opts):
try:
all_tenants = strutils.bool_from_string(all_tenants, True)
except ValueError as err:
raise exception.InvalidInput(six.text_type(err))
raise exception.InvalidInput(str(err))
else:
# The empty string is considered enabling all_tenants
all_tenants = 'all_tenants' in search_opts
@ -526,7 +525,7 @@ def is_locked(search_opts):
try:
locked = strutils.bool_from_string(locked, strict=True)
except ValueError as err:
raise exception.InvalidInput(six.text_type(err))
raise exception.InvalidInput(str(err))
return locked

5
nova/api/openstack/compute/aggregates.py

@ -18,7 +18,6 @@
import datetime
from oslo_log import log as logging
import six
from webob import exc
from nova.api.openstack import api_version_request
@ -211,14 +210,14 @@ class AggregateController(wsgi.Controller):
exception.AggregateHostNotFound,
exception.ComputeHostNotFound) as e:
LOG.error('Failed to remove host %s from aggregate %s. Error: %s',
host, id, six.text_type(e))
host, id, str(e))
msg = _('Cannot remove host %(host)s in aggregate %(id)s') % {
'host': host, 'id': id}
raise exc.HTTPNotFound(explanation=msg)
except (exception.InvalidAggregateAction,
exception.ResourceProviderUpdateConflict) as e:
LOG.error('Failed to remove host %s from aggregate %s. Error: %s',
host, id, six.text_type(e))
host, id, str(e))
msg = _('Cannot remove host %(host)s in aggregate %(id)s') % {
'host': host, 'id': id}
raise exc.HTTPConflict(explanation=msg)

3
nova/api/openstack/compute/assisted_volume_snapshots.py

@ -17,7 +17,6 @@
"""The Assisted volume snapshots extension."""
from oslo_serialization import jsonutils
import six
from webob import exc
from nova.api.openstack.compute.schemas import assisted_volume_snapshots
@ -79,7 +78,7 @@ class AssistedVolumeSnapshotsController(wsgi.Controller):
delete_info = jsonutils.loads(delete_metadata['delete_info'])
volume_id = delete_info['volume_id']
except (KeyError, ValueError) as e:
raise exc.HTTPBadRequest(explanation=six.text_type(e))
raise exc.HTTPBadRequest(explanation=str(e))
try:
self.compute_api.volume_snapshot_delete(context, volume_id,

3
nova/api/openstack/compute/flavors_extraspecs.py

@ -13,7 +13,6 @@
# License for the specific language governing permissions and limitations
# under the License.
import six
import webob
from nova.api.openstack import api_version_request
@ -45,7 +44,7 @@ class FlavorExtraSpecsController(wsgi.Controller):
# explicitly as json schema cannot have max length check for
# numeric value
if isinstance(value, (int, float)):
value = six.text_type(value)
value = str(value)
try:
utils.check_string_length(value, 'extra_specs value',
max_length=255)

3
nova/api/openstack/compute/servers.py

@ -21,7 +21,6 @@ import oslo_messaging as messaging
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
import six
import webob
from webob import exc
@ -662,7 +661,7 @@ class ServersController(wsgi.Controller):
availability_zone, host, node = parse_az(context,
availability_zone)
except exception.InvalidInput as err:
raise exc.HTTPBadRequest(explanation=six.text_type(err))
raise exc.HTTPBadRequest(explanation=str(err))
if host or node:
context.can(server_policies.SERVERS % 'create:forced_host',
target=target)

3
nova/api/openstack/compute/services.py

@ -16,7 +16,6 @@ from keystoneauth1 import exceptions as ks_exc
from oslo_log import log as logging
from oslo_utils import strutils
from oslo_utils import uuidutils
import six
import webob.exc
from nova.api.openstack import api_version_request
@ -290,7 +289,7 @@ class ServiceController(wsgi.Controller):
LOG.error(
"Failed to delete compute node resource provider "
"for compute node %s: %s",
compute_node.uuid, six.text_type(e))
compute_node.uuid, str(e))
# remove the host_mapping of this host.
try:
hm = objects.HostMapping.get_by_host(context, service.host)

3
nova/api/openstack/compute/simple_tenant_usage.py

@ -19,7 +19,6 @@ from urllib import parse as urlparse
import iso8601
from oslo_utils import timeutils
import six
from webob import exc
from nova.api.openstack import common
@ -41,7 +40,7 @@ def parse_strtime(dstr, fmt):
try:
return timeutils.parse_strtime(dstr, fmt)
except (TypeError, ValueError) as e:
raise exception.InvalidStrTime(reason=six.text_type(e))
raise exception.InvalidStrTime(reason=str(e))
class SimpleTenantUsageController(wsgi.Controller):

13
nova/api/openstack/wsgi.py

@ -21,7 +21,6 @@ from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import strutils
import six
import webob
from nova.api.openstack import api_version_request as api_version
@ -220,7 +219,7 @@ class JSONDictSerializer(ActionDispatcher):
return self.dispatch(data, action=action)
def default(self, data):
return six.text_type(jsonutils.dumps(data))
return str(jsonutils.dumps(data))
def response(code):
@ -293,8 +292,8 @@ class ResponseObject(object):
response.headers[hdr] = encodeutils.safe_decode(
encodeutils.safe_encode(val))
# Deal with content_type
if not isinstance(content_type, six.text_type):
content_type = six.text_type(content_type)
if not isinstance(content_type, str):
content_type = str(content_type)
# In Py3.X Headers must be a str.
response.headers['Content-Type'] = encodeutils.safe_decode(
encodeutils.safe_encode(content_type))
@ -506,7 +505,7 @@ class Resource(wsgi.Application):
if body:
msg = _("Action: '%(action)s', calling method: %(meth)s, body: "
"%(body)s") % {'action': action,
'body': six.text_type(body, 'utf-8'),
'body': str(body, 'utf-8'),
'meth': str(meth)}
LOG.debug(strutils.mask_password(msg))
else:
@ -562,8 +561,8 @@ class Resource(wsgi.Application):
if hasattr(response, 'headers'):
for hdr, val in list(response.headers.items()):
if not isinstance(val, six.text_type):
val = six.text_type(val)
if not isinstance(val, str):
val = str(val)
# In Py3.X Headers must be a string
response.headers[hdr] = encodeutils.safe_decode(
encodeutils.safe_encode(val))

7
nova/api/validation/validators.py

@ -25,7 +25,6 @@ from oslo_serialization import base64
from oslo_utils import timeutils
from oslo_utils import uuidutils
import rfc3986
import six
from nova.api.validation import parameter_types
from nova import exception
@ -34,7 +33,7 @@ from nova.i18n import _
@jsonschema.FormatChecker.cls_checks('regex')
def _validate_regex_format(instance):
if not instance or not isinstance(instance, six.text_type):
if not instance or not isinstance(instance, str):
return False
try:
re.compile(instance)
@ -56,7 +55,7 @@ def _validate_datetime_format(instance):
@jsonschema.FormatChecker.cls_checks('base64')
def _validate_base64_format(instance):
try:
if isinstance(instance, six.text_type):
if isinstance(instance, str):
instance = instance.encode('utf-8')
base64.decode_as_bytes(instance)
except TypeError:
@ -310,7 +309,7 @@ class _SchemaValidator(object):
except TypeError as ex:
# NOTE: If passing non string value to patternProperties parameter,
# TypeError happens. Here is for catching the TypeError.
detail = six.text_type(ex)
detail = str(ex)
raise exception.ValidationError(detail=detail)
def _number_from_str(self, instance):

17
nova/cmd/manage.py

@ -40,7 +40,6 @@ from oslo_serialization import jsonutils
from oslo_utils import encodeutils
from oslo_utils import uuidutils
import prettytable
import six
from sqlalchemy.engine import url as sqla_url
from nova.cmd import common as cmd_common
@ -157,7 +156,7 @@ class DbCommands(object):
for k, v in sorted(dct.items(), key=sort_key):
# convert dict to str to check length
if isinstance(v, dict):
v = six.text_type(v)
v = str(v)
# if value has a newline, add in multiple rows
# e.g. fault with stacktrace
if v and isinstance(v, str) and r'\n' in v:
@ -197,7 +196,7 @@ Has "nova-manage api_db sync" been run?
Has "nova-manage cell_v2 map_cell0" been run?
Is [api_database]/connection set in nova.conf?
Is the cell0 database connection URL correct?
Error: %s""") % six.text_type(e))
Error: %s""") % str(e))
return 1
return migration.db_sync(version)
@ -718,7 +717,7 @@ class CellV2Commands(object):
url=objects.CellMapping.format_mq_url(
transport_url))
except (messaging.InvalidTransportURL, ValueError) as e:
print(_('Invalid transport URL: %s') % six.text_type(e))
print(_('Invalid transport URL: %s') % str(e))
return None
return transport_url
@ -1527,7 +1526,7 @@ class PlacementCommands(object):
)['ports']
except neutron_client_exc.NeutronClientException as e:
raise exception.UnableToQueryPorts(
instance_uuid=instance.uuid, error=six.text_type(e))
instance_uuid=instance.uuid, error=str(e))
@staticmethod
def _has_request_but_no_allocation(port):
@ -1752,13 +1751,13 @@ class PlacementCommands(object):
except neutron_client_exc.NeutronClientException as e:
output(
_('Updating port %(port_uuid)s failed: %(error)s') %
{'port_uuid': port['id'], 'error': six.text_type(e)})
{'port_uuid': port['id'], 'error': str(e)})
# one of the port updates failed. We need to roll back the updates
# that succeeded before
self._rollback_port_updates(neutron, succeeded, output)
# we failed to heal so we need to stop but we successfully rolled
# back the partial updates so the admin can retry the healing.
raise exception.UnableToUpdatePorts(error=six.text_type(e))
raise exception.UnableToUpdatePorts(error=str(e))
@staticmethod
def _rollback_port_updates(neutron, ports_to_rollback, output):
@ -1782,7 +1781,7 @@ class PlacementCommands(object):
output(
_('Rolling back update for port %(port_uuid)s failed: '
'%(error)s') % {'port_uuid': port['id'],
'error': six.text_type(e)})
'error': str(e)})
# TODO(gibi): We could implement a retry mechanism with
# back off.
manual_rollback_needed.append(port['id'])
@ -1793,7 +1792,7 @@ class PlacementCommands(object):
# back. There are partial updates in neutron. Human intervention
# needed.
raise exception.UnableToRollbackPortUpdates(
error=six.text_type(last_exc),
error=str(last_exc),
port_uuids=manual_rollback_needed)
def _heal_missing_alloc(self, ctxt, instance, node_cache):

5
nova/cmd/status.py

@ -27,7 +27,6 @@ from oslo_serialization import jsonutils
from oslo_upgradecheck import upgradecheck
from oslo_utils import fileutils
import pkg_resources
import six
from sqlalchemy import func as sqlfunc
from sqlalchemy import MetaData, Table, and_, select
@ -343,7 +342,7 @@ class UpgradeCommands(upgradecheck.UpgradeCommands):
return upgradecheck.Result(
upgradecheck.Code.WARNING,
_('Unable to determine Cinder API version due to error: %s') %
six.text_type(ex))
str(ex))
return upgradecheck.Result(upgradecheck.Code.SUCCESS)
def _check_policy(self):
@ -404,7 +403,7 @@ class UpgradeCommands(upgradecheck.UpgradeCommands):
status = upgradecheck.Result(
upgradecheck.Code.WARNING,
_('Unable to perform policy checks due to error: %s') %
six.text_type(ex))
str(ex))
# reset the policy state so that it can be initialized from fresh if
# operator changes policy file after running this upgrade checks.
policy.reset()

9
nova/compute/api.py

@ -34,7 +34,6 @@ from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units
from oslo_utils import uuidutils
import six
from nova.accelerator import cyborg
from nova import availability_zones
@ -286,7 +285,7 @@ def _get_image_meta_obj(image_meta_dict):
except ValueError as e:
# there must be invalid values in the image meta properties so
# consider this an invalid request
msg = _('Invalid image metadata. Error: %s') % six.text_type(e)
msg = _('Invalid image metadata. Error: %s') % str(e)
raise exception.InvalidRequest(msg)
return image_meta
@ -3049,7 +3048,7 @@ class API(base.Base):
LOG.error('An error occurred while listing ports '
'with an ip_address filter value of "%s". '
'Error: %s',
address, six.text_type(e))
address, str(e))
return uuids
def update_instance(self, context, instance, updates):
@ -3193,7 +3192,7 @@ class API(base.Base):
LOG.warning("Error while trying to clean up image %(img_id)s: "
"%(error_msg)s",
{"img_id": image_meta['id'],
"error_msg": six.text_type(exc)})
"error_msg": str(exc)})
attr = 'task_state'
state = task_states.DELETING
if type(ex) == exception.InstanceNotFound:
@ -3303,7 +3302,7 @@ class API(base.Base):
with excutils.save_and_reraise_exception():
LOG.error("An error occurred during quiesce of instance. "
"Unquiescing to ensure instance is thawed. "
"Error: %s", six.text_type(ex),
"Error: %s", str(ex),
instance=instance)
self.compute_rpcapi.unquiesce_instance(context, instance,
mapping=None)

3
nova/compute/flavors.py

@ -22,7 +22,6 @@ import re
from oslo_utils import strutils
from oslo_utils import uuidutils
import six
import nova.conf
from nova import context
@ -83,7 +82,7 @@ def create(name, memory, vcpus, root_gb, ephemeral_gb=0, flavorid=None,
# NOTE(vish): Internally, flavorid is stored as a string but it comes
# in through json as an integer, so we convert it here.
flavorid = six.text_type(flavorid)
flavorid = str(flavorid)
# NOTE(wangbo): validate attributes of the creating flavor.
# ram and vcpus should be positive ( > 0) integers.

49
nova/compute/manager.py

@ -54,7 +54,6 @@ from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import timeutils
from oslo_utils import units
import six
from nova.accelerator import cyborg
from nova import block_device
@ -1493,7 +1492,7 @@ class ComputeManager(manager.Manager):
LOG.error(
"Could not retrieve compute node resource provider %s and "
"therefore unable to error out any instances stuck in "
"BUILDING state. Error: %s", cn_uuid, six.text_type(e))
"BUILDING state. Error: %s", cn_uuid, str(e))
continue
not_handled_consumers = (set(allocations) -
@ -1972,7 +1971,7 @@ class ComputeManager(manager.Manager):
# booting from volume, and will be recorded as an instance fault.
# Maintain the original exception message which most likely has
# useful details which the standard InvalidBDM error message lacks.
raise exception.InvalidBDM(six.text_type(ex))
raise exception.InvalidBDM(str(ex))
def _update_instance_after_spawn(self, instance,
vm_state=vm_states.ACTIVE):
@ -2347,7 +2346,7 @@ class ComputeManager(manager.Manager):
exception.UnexpectedResourceProviderNameForPCIRequest
) as e:
raise exception.BuildAbortException(
reason=six.text_type(e), instance_uuid=instance.uuid)
reason=str(e), instance_uuid=instance.uuid)
# TODO(Luyao) cut over to get_allocs_for_consumer
allocs = self.reportclient.get_allocations_for_consumer(
@ -2479,7 +2478,7 @@ class ComputeManager(manager.Manager):
phase=fields.NotificationPhase.ERROR, exception=e,
bdms=block_device_mapping)
raise exception.RescheduledException(
instance_uuid=instance.uuid, reason=six.text_type(e))
instance_uuid=instance.uuid, reason=str(e))
# NOTE(alaski): This is only useful during reschedules, remove it now.
instance.system_metadata.pop('network_allocated', None)
@ -2637,10 +2636,10 @@ class ComputeManager(manager.Manager):
ctxt.reraise = False
LOG.warning('Could not clean up failed build,'
' not rescheduling. Error: %s',
six.text_type(exc2))
str(exc2))
raise exception.BuildAbortException(
instance_uuid=instance.uuid,
reason=six.text_type(exc))
reason=str(exc))
finally:
# Call Cyborg to delete accelerator requests
compute_utils.delete_arqs_if_needed(context, instance)
@ -2715,7 +2714,7 @@ class ComputeManager(manager.Manager):
LOG.warning(
'Failed to update network info cache when cleaning up '
'allocated networks. Stale VIFs may be left on this host.'
'Error: %s', six.text_type(exc)
'Error: %s', str(exc)
)
return
@ -2733,7 +2732,7 @@ class ComputeManager(manager.Manager):
# mostly ignored
LOG.warning(
'Cleaning up VIFs failed for instance. Error: %s',
six.text_type(exc), instance=instance,
str(exc), instance=instance,
)
else:
LOG.debug('Unplugged VIFs for instance', instance=instance)
@ -2771,7 +2770,7 @@ class ComputeManager(manager.Manager):
# Provide a warning that something is amiss.
with excutils.save_and_reraise_exception():
LOG.warning('Failed to deallocate network for instance; '
'retrying. Error: %s', six.text_type(e),
'retrying. Error: %s', str(e),
instance=instance)
try:
@ -4529,7 +4528,7 @@ class ComputeManager(manager.Manager):
# Do not let this stop us from cleaning up since the guest
# is already gone.
LOG.error('Failed to delete port bindings from source host. '
'Error: %s', six.text_type(e), instance=instance)
'Error: %s', str(e), instance=instance)
def _delete_volume_attachments(self, ctxt, bdms):
"""Deletes volume attachment records for the given bdms.
@ -4548,7 +4547,7 @@ class ComputeManager(manager.Manager):
self.volume_api.attachment_delete(ctxt, bdm.attachment_id)
except Exception as e:
LOG.error('Failed to delete volume attachment with ID %s. '
'Error: %s', bdm.attachment_id, six.text_type(e),
'Error: %s', bdm.attachment_id, str(e),
instance_uuid=bdm.instance_uuid)
@wrap_exception()
@ -4642,7 +4641,7 @@ class ComputeManager(manager.Manager):
# Do not let this stop us from cleaning up since the guest
# is already gone.
LOG.error('Failed to delete port bindings from target host. '
'Error: %s', six.text_type(e), instance=instance)
'Error: %s', str(e), instance=instance)
# Delete any volume attachments remaining for this target host.
LOG.debug('Deleting volume attachments for target host.',
@ -5125,7 +5124,7 @@ class ComputeManager(manager.Manager):
exception.UnexpectedResourceProviderNameForPCIRequest
) as e:
raise exception.BuildAbortException(
reason=six.text_type(e), instance_uuid=instance.uuid)
reason=str(e), instance_uuid=instance.uuid)
limits = filter_properties.get('limits', {})
allocs = self.reportclient.get_allocations_for_consumer(
@ -5360,7 +5359,7 @@ class ComputeManager(manager.Manager):
ctxt, instance, flavor, nodename, migration, allocations,
image_meta=instance.image_meta, limits=limits)
except Exception as ex:
err = six.text_type(ex)
err = str(ex)
LOG.warning(
'Cross-cell resize pre-checks failed for this host (%s). '
'Cleaning up. Failure: %s', self.host, err,
@ -5457,7 +5456,7 @@ class ComputeManager(manager.Manager):
self._power_off_instance(instance)
except Exception as e:
LOG.exception('Failed to power off instance.', instance=instance)
raise exception.InstancePowerOffFailure(reason=six.text_type(e))
raise exception.InstancePowerOffFailure(reason=str(e))
instance.power_state = self._get_power_state(instance)
# If a snapshot image ID was provided, we need to snapshot the guest
@ -6645,7 +6644,7 @@ class ComputeManager(manager.Manager):
LOG.info("Get console output", instance=instance)
output = self.driver.get_console_output(context, instance)
if type(output) is six.text_type:
if type(output) is str:
output = output.encode("latin-1")
if tail_length is not None:
@ -8491,12 +8490,12 @@ class ComputeManager(manager.Manager):
LOG.error('Connection for volume %s not terminated on '
'source host %s during post_live_migration: '
'%s', bdm.volume_id, self.host,
six.text_type(e), instance=instance)
str(e), instance=instance)
else:
LOG.error('Volume attachment %s not deleted on source '
'host %s during post_live_migration: %s',
bdm.attachment_id, self.host,
six.text_type(e), instance=instance)
str(e), instance=instance)
@wrap_exception()
@wrap_instance_fault
@ -8755,7 +8754,7 @@ class ComputeManager(manager.Manager):
LOG.error('Network cleanup failed for source host %s during post '
'live migration. You may need to manually clean up '
'resources in the network service. Error: %s',
prev_host, six.text_type(e))
prev_host, str(e))
# NOTE(vish): this is necessary to update dhcp for nova-network
# NOTE(mriedem): This is a no-op for neutron.
self.network_api.setup_networks_on_host(context, instance, self.host)
@ -8917,7 +8916,7 @@ class ComputeManager(manager.Manager):
'Network cleanup failed for destination host %s '
'during live migration rollback. You may need to '
'manually clean up resources in the network service. '
'Error: %s', dest, six.text_type(e))
'Error: %s', dest, str(e))
except Exception:
with excutils.save_and_reraise_exception():
LOG.exception(
@ -9018,7 +9017,7 @@ class ComputeManager(manager.Manager):
'Network cleanup failed for destination host %s '
'during live migration rollback. You may need to '
'manually clean up resources in the network service. '
'Error: %s', self.host, six.text_type(e))
'Error: %s', self.host, str(e))
except Exception:
with excutils.save_and_reraise_exception():
# NOTE(tdurakov): even if teardown networks fails driver
@ -9813,7 +9812,7 @@ class ComputeManager(manager.Manager):
except keystone_exception.ClientException as e:
LOG.error(
"Failed to delete compute node resource provider "
"for compute node %s: %s", cn.uuid, six.text_type(e))
"for compute node %s: %s", cn.uuid, str(e))
for nodename in nodenames:
self._update_available_resource_for_node(context, nodename,
@ -10257,7 +10256,7 @@ class ComputeManager(manager.Manager):
except exception.NotFound as e:
LOG.info('Failed to process external instance event '
'%(event)s due to: %(error)s',
{'event': event.key, 'error': six.text_type(e)},
{'event': event.key, 'error': str(e)},
instance=instance)
elif event.name == 'network-vif-deleted':
try:
@ -10267,7 +10266,7 @@ class ComputeManager(manager.Manager):
except exception.NotFound as e:
LOG.info('Failed to process external instance event '
'%(event)s due to: %(error)s',
{'event': event.key, 'error': six.text_type(e)},
{'event': event.key, 'error': str(e)},
instance=instance)
elif event.name == 'volume-extended':
self.extend_volume(context, instance, event.tag)

3
nova/compute/utils.py

@ -25,7 +25,6 @@ import netifaces
from oslo_log import log
from oslo_serialization import jsonutils
from oslo_utils import excutils
import six
from nova.accelerator import cyborg
from nova import block_device
@ -131,7 +130,7 @@ def _get_fault_details(exc_info, error_code):
# exceptions (see exception_to_dict).
details = ''.join(traceback.format_exception(
exc_info[0], exc_info[1], exc_info[2]))
return six.text_type(details)
return str(details)
def add_instance_fault_from_exc(context, instance, fault, exc_info=None,

7
nova/conductor/manager.py

@ -29,7 +29,6 @@ from oslo_serialization import jsonutils
from oslo_utils import excutils
from oslo_utils import timeutils
from oslo_utils import versionutils
import six
from nova.accelerator import cyborg
from nova import availability_zones
@ -498,7 +497,7 @@ class ComputeTaskManager(base.Base):
task_state=None)
migration.status = 'error'
migration.save()
raise exception.MigrationError(reason=six.text_type(ex))
raise exception.MigrationError(reason=str(ex))
def _build_live_migrate_task(self, context, instance, destination,
block_migration, disk_over_commit, migration,
@ -1122,7 +1121,7 @@ class ComputeTaskManager(base.Base):
{'vm_state': vm_states.ERROR,
'task_state': None}, ex, request_spec)
LOG.warning('Rebuild failed: %s',
six.text_type(ex), instance=instance)
str(ex), instance=instance)
except exception.NoValidHost:
with excutils.save_and_reraise_exception():
if migration:
@ -1214,7 +1213,7 @@ class ComputeTaskManager(base.Base):
{'vm_state': vm_states.ERROR,
'task_state': None}, ex, request_spec)
LOG.warning('Rebuild failed: %s',
six.text_type(ex), instance=instance)
str(ex), instance=instance)
compute_utils.notify_about_instance_usage(
self.notifier, context, instance, "rebuild.scheduled")

4
nova/conductor/tasks/live_migrate.py

@ -13,7 +13,6 @@
from oslo_log import log as logging
import oslo_messaging as messaging
from oslo_utils import excutils
import six
from nova import availability_zones
from nova.compute import power_state
@ -533,8 +532,7 @@ class LiveMigrationTask(base.TaskBase):
# Note(ShaoHe Feng) There are types of RemoteError, such as
# NoSuchMethod, UnsupportedVersion, we can distinguish it by
# ex.exc_type.
raise exception.MigrationSchedulerRPCError(
reason=six.text_type(ex))
raise exception.MigrationSchedulerRPCError(reason=str(ex))
scheduler_utils.fill_provider_mapping(request_spec, selection)

3
nova/console/rfb/authvencrypt.py

@ -18,7 +18,6 @@ import struct
from oslo_config import cfg
from oslo_log import log as logging
import six
from nova.console.rfb import auth
from nova import exception
@ -147,5 +146,5 @@ class RFBAuthSchemeVeNCrypt(auth.RFBAuthScheme):
except ssl.SSLError as e:
reason = _("Error establishing TLS connection to server: %s") % (
six.text_type(e))
str(e))
raise exception.RFBAuthHandshakeFailed(reason=reason)

7
nova/console/securityproxy/rfb.py

@ -16,7 +16,6 @@
import struct
from oslo_log import log as logging
import six
from nova.console.rfb import auth
from nova.console.rfb import auths
@ -53,7 +52,7 @@ class RFBSecurityProxy(base.SecurityProxy):
self.auth_schemes = auths.RFBAuthSchemeList()
def _make_var_str(self, message):
message_str = six.text_type(message)
message_str = str(message)
message_bytes = message_str.encode('utf-8')
message_len = struct.pack("!I", len(message_bytes))
return message_len + message_bytes
@ -170,7 +169,7 @@ class RFBSecurityProxy(base.SecurityProxy):
self._fail(tenant_sock, compute_sock,
_("Unable to negotiate security with server"))
raise exception.SecurityProxyNegotiationFailed(
reason=_("No compute auth available: %s") % six.text_type(e))
reason=_("No compute auth available: %s") % str(e))
compute_sock.sendall(bytes((scheme.security_type(),)))
@ -184,7 +183,7 @@ class RFBSecurityProxy(base.SecurityProxy):
# as that's information leakage
self._fail(tenant_sock, None,
_("Unable to negotiate security with server"))
LOG.debug("Auth failed %s", six.text_type(e))
LOG.debug("Auth failed %s", str(e))
raise exception.SecurityProxyNegotiationFailed(
reason=_("Auth handshake failed"))

5
nova/db/sqlalchemy/api.py

@ -34,7 +34,6 @@ from oslo_utils import excutils
from oslo_utils import importutils
from oslo_utils import timeutils
from oslo_utils import uuidutils
import six
import sqlalchemy as sa
from sqlalchemy import and_
from sqlalchemy import Boolean
@ -4091,7 +4090,7 @@ def _archive_if_instance_deleted(table, shadow_table, instances, conn,
except db_exc.DBReferenceError as ex:
LOG.warning('Failed to archive %(table)s: %(error)s',
{'table': table.name,
'error': six.text_type(ex)})
'error': str(ex)})
return 0
@ -4167,7 +4166,7 @@ def _archive_deleted_rows_for_table(metadata, tablename, max_rows, before):
# skip this table for now; we'll come back to it later.
LOG.warning("IntegrityError detected when archiving table "
"%(tablename)s: %(error)s",
{'tablename': tablename, 'error': six.text_type(ex)})
{'tablename': tablename, 'error': str(ex)})
# NOTE(jake): instance_actions_events doesn't have a instance_uuid column
# but still needs to be archived as it is a FK constraint

3
nova/exception.py

@ -23,7 +23,6 @@ SHOULD include dedicated exception logging.
"""
from oslo_log import log as logging
import six
import webob.exc
from webob import util as woutil
@ -82,7 +81,7 @@ class NovaException(Exception):
if not message:
message = self.msg_fmt % kwargs
else:
message = six.text_type(message)
message = str(message)
except Exception:
# NOTE(melwitt): This is done in a separate method so it can be
# monkey-patched during testing to make it a hard failure.

15
nova/image/glance.py

@ -39,7 +39,6 @@ from oslo_log import log as logging
from oslo_serialization import jsonutils
from oslo_utils import excutils
from oslo_utils import timeutils
import six
import nova.conf
from nova import exception
@ -207,7 +206,7 @@ class GlanceClientWrapper(object):
'method': method, 'extra': extra})
if attempt == num_attempts:
raise exception.GlanceConnectionFailed(
server=str(self.api_server), reason=six.text_type(e))
server=str(self.api_server), reason=str(e))
time.sleep(1)
@ -729,7 +728,7 @@ class GlanceImageServiceV2(object):
except glanceclient.exc.HTTPForbidden:
raise exception.ImageNotAuthorized(image_id=image_id)
except glanceclient.exc.HTTPConflict as exc:
raise exception.ImageDeleteConflict(reason=six.text_type(exc))
raise exception.ImageDeleteConflict(reason=str(exc))
return True
def image_import_copy(self, context, image_id, stores):
@ -1048,7 +1047,7 @@ def _translate_image_exception(image_id, exc_value):
return exception.ImageNotFound(image_id=image_id)
if isinstance(exc_value, glanceclient.exc.BadRequest):
return exception.ImageBadRequest(image_id=image_id,
response=six.text_type(exc_value))
response=str(exc_value))
if isinstance(exc_value, glanceclient.exc.HTTPOverLimit):
return exception.ImageQuotaExceeded(image_id=image_id)
return exc_value
@ -1057,11 +1056,11 @@ def _translate_image_exception(image_id, exc_value):
def _translate_plain_exception(exc_value):
if isinstance(exc_value, (glanceclient.exc.Forbidden,
glanceclient.exc.Unauthorized)):
return exception.Forbidden(six.text_type(exc_value))
return exception.Forbidden(str(exc_value))
if isinstance(exc_value, glanceclient.exc.NotFound):
return exception.NotFound(six.text_type(exc_value))
return exception.NotFound(str(exc_value))
if isinstance(exc_value, glanceclient.exc.BadRequest):
return exception.Invalid(six.text_type(exc_value))
return exception.Invalid(str(exc_value))
return exc_value
@ -1079,7 +1078,7 @@ def _verify_certs(context, img_sig_cert_uuid, trusted_certs):
'failed for certificate: %s',
img_sig_cert_uuid)
raise exception.CertificateValidationFailed(
cert_uuid=img_sig_cert_uuid, reason=six.text_type(e))
cert_uuid=img_sig_cert_uuid, reason=str(e))
def get_remote_image_service(context, image_href):

13
nova/network/neutron.py

@ -30,7 +30,6 @@ from oslo_log import log as logging
from oslo_utils import excutils
from oslo_utils import strutils
from oslo_utils import uuidutils
import six
from nova.compute import utils as compute_utils
import nova.conf
@ -197,7 +196,7 @@ class ClientWrapper(clientv20.Client):
"admin credential located in nova.conf")
raise exception.NeutronAdminCredentialConfigurationInvalid()
except neutron_client_exc.Forbidden as e:
raise exception.Forbidden(six.text_type(e))
raise exception.Forbidden(str(e))
return ret
return wrapper
@ -2168,7 +2167,7 @@ class API(base.Base):
return True
except neutron_client_exc.Conflict as ex:
LOG.debug('Unable to auto-allocate networks. %s',
six.text_type(ex))
str(ex))
return False
def _auto_allocate_network(self, instance, neutron):
@ -2420,7 +2419,7 @@ class API(base.Base):
try:
client.update_floatingip(fip['id'], {'floatingip': param})
except neutron_client_exc.Conflict as e:
raise exception.FloatingIpAssociateFailed(six.text_type(e))
raise exception.FloatingIpAssociateFailed(str(e))
# If the floating IP was associated with another server, try to refresh
# the cache for that instance to avoid a window of time where multiple
@ -2694,11 +2693,11 @@ class API(base.Base):
fip = client.create_floatingip(param)
except (neutron_client_exc.IpAddressGenerationFailureClient,
neutron_client_exc.ExternalIpAddressExhaustedClient) as e:
raise exception.NoMoreFloatingIps(six.text_type(e))
raise exception.NoMoreFloatingIps(str(e))
except neutron_client_exc.OverQuotaClient as e:
raise exception.FloatingIpLimitExceeded(six.text_type(e))
raise exception.FloatingIpLimitExceeded(str(e))
except neutron_client_exc.BadRequest as e:
raise exception.FloatingIpBadRequest(six.text_type(e))
raise exception.FloatingIpBadRequest(str(e))
return fip['floatingip']['floating_ip_address']

28
nova/network/security_group_api.py

@ -27,7 +27,6 @@ from oslo_utils import encodeutils
from oslo_utils import excutils
from oslo_utils import netutils
from oslo_utils import uuidutils
import six
from webob import exc
from nova import context as nova_context
@ -69,11 +68,11 @@ def validate_name(
return neutronv20.find_resourceid_by_name_or_id(
neutron, 'security_group', name, context.project_id)
except n_exc.NeutronClientNoUniqueMatch as e:
raise exception.NoUniqueMatch(six.text_type(e))
raise exception.NoUniqueMatch(str(e))
except n_exc.NeutronClientException as e:
if e.status_code == 404:
LOG.debug('Neutron security group %s not found', name)
raise exception.SecurityGroupNotFound(six.text_type(e))
raise exception.SecurityGroupNotFound(str(e))
else:
LOG.error('Neutron Error: %s', e)
raise e
@ -237,7 +236,7 @@ def create_security_group(context, name, description):
security_group = neutron.create_security_group(
body).get('security_group')
except n_exc.BadRequest as e:
raise exception.Invalid(six.text_type(e))
raise exception.Invalid(str(e))
except n_exc.NeutronClientException as e:
LOG.exception("Neutron Error creating security group %s", name)
if e.status_code == 401:
@ -246,7 +245,7 @@ def create_security_group(context, name, description):
# quota
raise exc.HTTPBadRequest()
elif e.status_code == 409:
raise exception.SecurityGroupLimitExceeded(six.text_type(e))
raise exception.SecurityGroupLimitExceeded(str(e))
raise e
return _convert_to_nova_security_group_format(security_group)
@ -312,7 +311,7 @@ def get(context, id):
except n_exc.NeutronClientException as e:
if e.status_code == 404:
LOG.debug('Neutron security group %s not found', id)
raise exception.SecurityGroupNotFound(six.text_type(e))
raise exception.SecurityGroupNotFound(str(e))
else:
LOG.error("Neutron Error: %s", e)
raise e
@ -360,9 +359,9 @@ def destroy(context, security_group):
neutron.delete_security_group(security_group['id'])
except n_exc.NeutronClientException as e:
if e.status_code == 404:
raise exception.SecurityGroupNotFound(six.text_type(e))
raise exception.SecurityGroupNotFound(str(e))
elif e.status_code == 409:
raise exception.Invalid(six.text_type(e))
raise exception.Invalid(str(e))
else:
LOG.error("Neutron Error: %s", e)
raise e
@ -385,14 +384,14 @@ def add_rules(context, id, name, vals):
except n_exc.NeutronClientException as e:
if e.status_code == 404:
LOG.exception("Neutron Error getting security group %s", name)
raise exception.SecurityGroupNotFound(six.text_type(e))
raise exception.SecurityGroupNotFound(str(e))
elif e.status_code == 409:
LOG.exception("Neutron Error adding rules to security "
"group %s", name)
raise exception.SecurityGroupLimitExceeded(six.text_type(e))
raise exception.SecurityGroupLimitExceeded(str(e))
elif e.status_code == 400:
LOG.exception("Neutron Error: %s", e)
raise exception.Invalid(six.text_type(e))
raise exception.Invalid(str(e))
else:
raise e
converted_rules = []
@ -462,7 +461,7 @@ def get_rule(context, id):
except n_exc.NeutronClientException as e:
if e.status_code == 404:
LOG.debug("Neutron security group rule %s not found", id)
raise exception.SecurityGroupNotFound(six.text_type(e))
raise exception.SecurityGroupNotFound(str(e))
else:
LOG.error("Neutron Error: %s", e)
raise e
@ -606,7 +605,7 @@ def add_to_instance(context, instance, security_group_name):
security_group_name,
context.project_id)
except n_exc.NeutronClientNoUniqueMatch as e:
raise exception.NoUniqueMatch(six.text_type(e))
raise exception.NoUniqueMatch(str(e))
except n_exc.NeutronClientException as e:
if e.status_code == 404:
msg = (_("Security group %(name)s is not found for "
@ -649,8 +648,7 @@ def add_to_instance(context, instance, security_group_name):
neutron.update_port(port['id'], {'port': updated_port})
except n_exc.NeutronClientException as e:
if e.status_code == 400:
raise exception.SecurityGroupCannotBeApplied(
six.text_type(e))
raise exception.SecurityGroupCannotBeApplied(str(e))
else:
raise e
except Exception:

7
nova/objects/image_meta.py

@ -15,7 +15,6 @@
import copy
from oslo_utils import versionutils
import six
from nova import exception
from nova import objects
@ -624,9 +623,9 @@ class ImageMetaProps(base.NovaObject):
setattr(self, key, image_props[key])
def _set_attr_from_trait_names(self, image_props):
for trait in [six.text_type(k[6:]) for k, v in image_props.items()
if six.text_type(k).startswith("trait:") and
six.text_type(v) == six.text_type('required')]:
for trait in [str(k[6:]) for k, v in image_props.items()
if str(k).startswith("trait:") and
str(v) == 'required']:
if 'traits_required' not in self:
self.traits_required = []
self.traits_required.append(trait)

3
nova/objects/instance_mapping.py

@ -14,7 +14,6 @@ import collections
from oslo_log import log as logging
from oslo_utils import versionutils
import six
from sqlalchemy.orm import exc as orm_exc
from sqlalchemy.orm import joinedload
from sqlalchemy.sql import false