Replace str with six.text_type

Replace str with six.text_type so that unicode exception messages can be
safely processed, and the change is PY3 compatible.

Closes-bug: #1295443

Change-Id: Ic27ec365b82797df37ae53f38d5d31e70cb65c67
This commit is contained in:
Liang Chen 2014-02-21 18:22:58 +08:00
parent cfcbc994d3
commit ca90c984ec
29 changed files with 91 additions and 71 deletions

View File

@ -16,6 +16,7 @@
"""Heat API exception subclasses - maps API response errors to AWS Errors"""
import six
import webob.exc
from heat.common import serializers
@ -293,13 +294,13 @@ def map_remote_error(ex):
ex_type = ex_type[:-len(rpc_common._REMOTE_POSTFIX)]
if ex_type in inval_param_errors:
return HeatInvalidParameterValueError(detail=str(ex))
return HeatInvalidParameterValueError(detail=six.text_type(ex))
elif ex_type in denied_errors:
return HeatAccessDeniedError(detail=str(ex))
return HeatAccessDeniedError(detail=six.text_type(ex))
elif ex_type in already_exists_errors:
return AlreadyExistsError(detail=str(ex))
return AlreadyExistsError(detail=six.text_type(ex))
elif ex_type in invalid_action_errors:
return HeatActionInProgressError(detail=str(ex))
return HeatActionInProgressError(detail=six.text_type(ex))
else:
# Map everything else to internal server error for now
return HeatInternalFailureError(detail=str(ex))
return HeatInternalFailureError(detail=six.text_type(ex))

View File

@ -254,7 +254,7 @@ class StackController(object):
try:
return urlfetch.get(url)
except IOError as exc:
msg = _('Failed to fetch template: %s') % str(exc)
msg = _('Failed to fetch template: %s') % exc
raise exception.HeatInvalidParameterValueError(detail=msg)
return None

View File

@ -97,7 +97,7 @@ class InstantiationData(object):
try:
template_data = urlfetch.get(url)
except IOError as ex:
err_reason = _('Could not retrieve template: %s') % str(ex)
err_reason = _('Could not retrieve template: %s') % ex
raise exc.HTTPBadRequest(err_reason)
else:
raise exc.HTTPBadRequest(_("No template specified"))
@ -181,7 +181,7 @@ class StackController(object):
filters=filter_params,
tenant_safe=tenant_safe)
except AttributeError as exc:
logger.warning("Old Engine Version: %s" % str(exc))
logger.warning(_("Old Engine Version: %s") % exc)
return stacks_view.collection(req, stacks=stacks, count=count,
tenant_safe=tenant_safe)

View File

@ -19,6 +19,7 @@
import functools
import sys
import six
from six.moves.urllib import parse as urlparse
from heat.openstack.common.gettextutils import _
@ -281,7 +282,7 @@ class ResourceFailure(HeatException):
self.action = action
exc_type = type(exception).__name__
super(ResourceFailure, self).__init__(exc_type=exc_type,
message=str(exception))
message=six.text_type(exception))
class NotSupported(HeatException):

View File

@ -18,6 +18,7 @@ Startup notification using a shell script or systemd NOTIFY_SOCKET
style notification
"""
from heat.openstack.common import importutils
from heat.openstack.common import log as logging
from heat.openstack.common import processutils
@ -34,6 +35,6 @@ def startup_notify(notify_param):
try:
processutils.execute(notify_param, shell=True)
except Exception as e:
logger.error(_('Failed to execute onready command: %s') % str(e))
logger.error(_('Failed to execute onready command: %s') % e)
else:
notifier.notify()

View File

@ -24,6 +24,7 @@ import datetime
import json
from lxml import etree
import six
from heat.openstack.common import log as logging
@ -73,7 +74,7 @@ class XMLResponseSerializer(object):
else:
self.object_to_element(value, subelement)
else:
element.text = str(obj)
element.text = six.text_type(obj)
def to_xml(self, data):
# Assumption : root node is dict with single key

View File

@ -49,7 +49,7 @@ def get(url, allowed_schemes=('http', 'https')):
try:
return urllib.request.urlopen(url).read()
except urllib.error.URLError as uex:
raise IOError(_('Failed to retrieve template: %s') % str(uex))
raise IOError(_('Failed to retrieve template: %s') % uex)
try:
resp = requests.get(url, stream=True)
@ -73,4 +73,4 @@ def get(url, allowed_schemes=('http', 'https')):
return result
except exceptions.RequestException as ex:
raise IOError(_('Failed to retrieve template: %s') % str(ex))
raise IOError(_('Failed to retrieve template: %s') % ex)

View File

@ -37,6 +37,7 @@ from oslo.config import cfg
from paste import deploy
import routes
import routes.middleware
import six
import webob.dec
import webob.exc
@ -556,7 +557,7 @@ class JSONRequestDeserializer(object):
raise exception.RequestLimitExceeded(message=msg)
return json.loads(datastring)
except ValueError as ex:
raise webob.exc.HTTPBadRequest(str(ex))
raise webob.exc.HTTPBadRequest(six.text_type(ex))
def default(self, request):
if self.has_body(request):
@ -616,7 +617,7 @@ class Resource(object):
action_result = self.dispatch(self.controller, action,
request, **action_args)
except TypeError as err:
logging.error(_('Exception handling resource: %s') % str(err))
logging.error(_('Exception handling resource: %s') % err)
msg = _('The server could not comply with the request since\r\n'
'it is either malformed or otherwise incorrect.\r\n')
err = webob.exc.HTTPBadRequest(msg)
@ -647,7 +648,6 @@ class Resource(object):
except Exception as err:
log_exception(err, sys.exc_info())
raise translate_exception(err, request.best_match_language())
# Here we support either passing in a serializer or detecting it
# based on the content type.
try:
@ -719,7 +719,7 @@ def log_exception(err, exc_info):
def translate_exception(exc, locale):
"""Translates all translatable elements of the given exception."""
exc.message = gettextutils.translate(str(exc), locale)
exc.message = gettextutils.translate(six.text_type(exc), locale)
if isinstance(exc, webob.exc.HTTPError):
# If the explanation is not a Message, that means that the
# explanation is the default, generic and not translatable explanation
@ -728,7 +728,7 @@ def translate_exception(exc, locale):
# message, since message is what gets passed in at construction time
# in the API
if not isinstance(exc.explanation, gettextutils.Message):
exc.explanation = str(exc)
exc.explanation = six.text_type(exc)
exc.detail = ''
else:
exc.explanation = \

View File

@ -14,6 +14,8 @@
import collections
import json
import six
from heat.api.aws import utils as aws_utils
from heat.common import exception
from heat.engine import function
@ -36,7 +38,7 @@ class FindInMap(function.Function):
try:
self._mapname, self._mapkey, self._mapvalue = self.args
except ValueError as ex:
raise KeyError(str(ex))
raise KeyError(six.text_type(ex))
def result(self):
mapping = self.stack.t.maps[function.resolve(self._mapname)]

View File

@ -15,6 +15,8 @@ import collections
import numbers
import re
import six
from heat.engine import resources
from heat.common import exception
@ -149,7 +151,7 @@ class Schema(collections.Mapping):
for constraint in self.constraints:
constraint.validate(value, context)
except ValueError as ex:
raise exception.StackValidationFailed(message=str(ex))
raise exception.StackValidationFailed(message=six.text_type(ex))
def __getitem__(self, key):
if key == self.TYPE:

View File

@ -11,6 +11,8 @@
# License for the specific language governing permissions and limitations
# under the License.
import six
from heat.common import exception
from heat.common import identifier
from heat.db import api as db_api
@ -42,7 +44,7 @@ class Event(object):
try:
self.resource_properties = dict(resource_properties)
except ValueError as ex:
self.resource_properties = {'Error': str(ex)}
self.resource_properties = {'Error': six.text_type(ex)}
self.uuid = uuid
self.timestamp = timestamp
self.id = id

View File

@ -15,6 +15,8 @@ import collections
import itertools
import json
import six
from heat.common import exception
from heat.engine import constraints as constr
@ -75,7 +77,7 @@ class Schema(constr.Schema):
except (KeyError, AttributeError) as err:
raise constr.InvalidSchemaError(_('Default must be a '
'comma-delimited list '
'string: %s') % str(err))
'string: %s') % err)
try:
self.validate_constraints(default_value)
except (ValueError, TypeError,
@ -298,7 +300,7 @@ class CommaDelimitedListParam(Parameter, collections.Sequence):
return value.split(',')
except (KeyError, AttributeError) as err:
message = _('Value must be a comma-delimited list string: %s')
raise ValueError(message % str(err))
raise ValueError(message % six.text_type(err))
return value
def value(self):
@ -333,7 +335,7 @@ class JsonParam(Parameter, collections.Mapping):
if val:
return json.loads(val)
except (ValueError, TypeError) as err:
message = _('Value must be valid JSON: %s') % str(err)
message = _('Value must be valid JSON: %s') % err
raise ValueError(message)
return value

View File

@ -366,7 +366,7 @@ class Stack(collections.Mapping):
try:
function.validate(snippet)
except Exception as ex:
reason = 'Output validation error: %s' % str(ex)
reason = 'Output validation error: %s' % six.text_type(ex)
raise StackValidationFailed(message=reason)
def requires_deferred_auth(self):
@ -473,7 +473,7 @@ class Stack(collections.Mapping):
yield action_task()
except exception.ResourceFailure as ex:
stack_status = self.FAILED
reason = 'Resource %s failed: %s' % (action, str(ex))
reason = 'Resource %s failed: %s' % (action, six.text_type(ex))
except scheduler.Timeout:
stack_status = self.FAILED
reason = '%s timed out' % action.title()
@ -590,7 +590,7 @@ class Stack(collections.Mapping):
stack_status = self.FAILED
reason = 'Timed out'
except exception.ResourceFailure as e:
reason = str(e)
reason = six.text_type(e)
stack_status = self.FAILED
if action == self.UPDATE:
@ -650,7 +650,7 @@ class Stack(collections.Mapping):
scheduler.TaskRunner(action_task)(timeout=self.timeout_secs())
except exception.ResourceFailure as ex:
stack_status = self.FAILED
reason = 'Resource %s failed: %s' % (action, str(ex))
reason = 'Resource %s failed: %s' % (action, six.text_type(ex))
except scheduler.Timeout:
stack_status = self.FAILED
reason = '%s timed out' % action.title()
@ -668,7 +668,7 @@ class Stack(collections.Mapping):
except Exception as ex:
logger.exception(ex)
stack_status = self.FAILED
reason = "Error deleting trust: %s" % str(ex)
reason = "Error deleting trust: %s" % six.text_type(ex)
# Delete the stored credentials
db_api.user_creds_delete(self.context, self.user_creds_id)
@ -683,7 +683,7 @@ class Stack(collections.Mapping):
except Exception as ex:
logger.exception(ex)
stack_status = self.FAILED
reason = "Error deleting project: %s" % str(ex)
reason = "Error deleting project: %s" % six.text_type(ex)
self.state_set(action, stack_status, reason)
@ -753,7 +753,7 @@ class Stack(collections.Mapping):
scheduler.TaskRunner(res.destroy)()
except exception.ResourceFailure as ex:
failed = True
logger.error(_('delete: %s') % str(ex))
logger.error(_('delete: %s') % ex)
for res in deps:
if not failed:

View File

@ -13,6 +13,8 @@
import collections
import six
from heat.common import exception
from heat.engine import constraints as constr
from heat.engine import parameters
@ -308,7 +310,7 @@ class Properties(collections.Mapping):
try:
self[key]
except ValueError as e:
msg = _("Property error : %s") % str(e)
msg = _("Property error : %s") % e
raise exception.StackValidationFailed(message=msg)
# are there unimplemented Properties
@ -335,7 +337,8 @@ class Properties(collections.Mapping):
# the resolver function could raise any number of exceptions,
# so handle this generically
except Exception as e:
raise ValueError('%s%s %s' % (self.error_prefix, key, str(e)))
raise ValueError('%s%s %s' % (self.error_prefix, key,
six.text_type(e)))
elif prop.has_default():
return prop.default()
elif prop.required():

View File

@ -15,6 +15,8 @@ import base64
import copy
from datetime import datetime
import six
from heat.common import exception
from heat.common import identifier
from heat.common import short_id
@ -410,7 +412,7 @@ class Resource(object):
except Exception as ex:
logger.exception('%s : %s' % (action, str(self)))
failure = exception.ResourceFailure(ex, self, action)
self.state_set(action, self.FAILED, str(failure))
self.state_set(action, self.FAILED, six.text_type(failure))
raise failure
except:
with excutils.save_and_reraise_exception():
@ -554,9 +556,10 @@ class Resource(object):
logger.debug(_("Resource %s update requires replacement") %
self.name)
except Exception as ex:
logger.exception('update %s : %s' % (str(self), str(ex)))
logger.exception(_('update %(resource)s : %(err)s') %
{'resource': str(self), 'err': ex})
failure = exception.ResourceFailure(ex, self, action)
self.state_set(action, self.FAILED, str(failure))
self.state_set(action, self.FAILED, six.text_type(failure))
raise failure
else:
self.json_snippet = copy.deepcopy(after)
@ -688,9 +691,9 @@ class Resource(object):
yield
except Exception as ex:
logger.exception(_('Delete %s'), str(self))
logger.exception(_('Delete %s') % str(self))
failure = exception.ResourceFailure(ex, self, self.action)
self.state_set(action, self.FAILED, str(failure))
self.state_set(action, self.FAILED, six.text_type(failure))
raise failure
except:
with excutils.save_and_reraise_exception():
@ -729,7 +732,7 @@ class Resource(object):
rs = db_api.resource_get(self.context, self.id)
rs.update_and_save({'nova_instance': self.resource_id})
except Exception as ex:
logger.warn(_('db error %s') % str(ex))
logger.warn(_('db error %s') % ex)
def _store(self):
'''Create the resource in the database.'''
@ -748,7 +751,7 @@ class Resource(object):
self.id = new_rs.id
self.created_time = new_rs.created_at
except Exception as ex:
logger.error(_('DB error %s') % str(ex))
logger.error(_('DB error %s') % ex)
def _add_event(self, action, status, reason):
'''Add a state change event to the database.'''
@ -759,7 +762,7 @@ class Resource(object):
try:
ev.store()
except Exception as ex:
logger.error(_('DB error %s') % str(ex))
logger.error(_('DB error %s') % ex)
def _store_or_update(self, action, status, reason):
self.action = action
@ -776,7 +779,7 @@ class Resource(object):
'updated_at': self.updated_time,
'nova_instance': self.resource_id})
except Exception as ex:
logger.error(_('DB error %s') % str(ex))
logger.error(_('DB error %s') % ex)
# store resource in DB on transition to CREATE_IN_PROGRESS
# all other transistions (other than to DELETE_COMPLETE)
@ -888,7 +891,7 @@ class Resource(object):
self.handle_signal(details)
except Exception as ex:
logger.exception(_('signal %(name)s : %(msg)s') %
{'name': str(self), 'msg': str(ex)})
{'name': str(self), 'msg': ex})
failure = exception.ResourceFailure(ex, self)
raise failure

View File

@ -15,6 +15,8 @@ import functools
import json
import math
import six
from heat.common import exception
from heat.common import timeutils as iso8601utils
from heat.engine import constraints
@ -678,7 +680,7 @@ class AutoScalingGroup(InstanceGroup, CooldownMixin):
with excutils.save_and_reraise_exception():
try:
notif.update({'suffix': 'error',
'message': str(resize_ex),
'message': six.text_type(resize_ex),
})
notification.send(**notif)
except Exception:

View File

@ -64,14 +64,14 @@ class ElasticIp(resource.Resource):
ips = self.neutron().show_floatingip(self.resource_id)
except ne as e:
if e.status_code == 404:
logger.warn(_("Floating IPs not found: %s") % str(e))
logger.warn(_("Floating IPs not found: %s") % e)
else:
self.ipaddress = ips['floatingip']['floating_ip_address']
else:
try:
ips = self.nova().floating_ips.get(self.resource_id)
except clients.novaclient.exceptions.NotFound as ex:
logger.warn(_("Floating IPs not found: %s") % str(ex))
logger.warn(_("Floating IPs not found: %s") % ex)
else:
self.ipaddress = ips.ip
return self.ipaddress or ''

View File

@ -120,8 +120,7 @@ class NeutronResource(resource.Resource):
try:
attributes = self._show_resource()
except NeutronClientException as ex:
logger.warn(_("failed to fetch resource attributes: %s") %
str(ex))
logger.warn(_("failed to fetch resource attributes: %s") % ex)
return None
return self.handle_get_attributes(self.name, name, attributes)

View File

@ -57,14 +57,14 @@ def refresh_server(server):
"response during server.get(): %(exception)s")
logger.warning(msg % {'name': server.name,
'id': server.id,
'exception': str(exc)})
'exception': exc})
except clients.novaclient.exceptions.ClientException as exc:
if exc.code in (500, 503):
msg = _('Server "%(name)s" (%(id)s) received the following '
'exception during server.get(): %(exception)s')
logger.warning(msg % {'name': server.name,
'id': server.id,
'exception': str(exc)})
'exception': exc})
else:
raise
@ -90,8 +90,7 @@ def get_image_id(nova_client, image_identifier):
image_list = nova_client.images.list()
except clients.novaclient.exceptions.ClientException as ex:
raise exception.Error(
message=(_("Error retrieving image list from nova: %s") %
str(ex)))
message=(_("Error retrieving image list from nova: %s") % ex))
image_names = dict(
(o.id, o.name)
for o in image_list if o.name == image_identifier)
@ -370,7 +369,7 @@ def server_to_ipaddress(client, server):
server = client.servers.get(server)
except clients.novaclient.exceptions.NotFound as ex:
logger.warn(_('Instance (%(server)s) not found: %(ex)s') % {
'server': server, 'ex': str(ex)})
'server': server, 'ex': ex})
else:
for n in server.networks:
if len(server.networks[n]) > 0:

View File

@ -226,7 +226,7 @@ class OSDBInstance(resource.Resource):
"response during instance.get(): %(exception)s")
logger.warning(msg % {'name': self.stack.name,
'id': self.stack.id,
'exception': str(exc)})
'exception': exc})
def check_create_complete(self, instance):
'''

View File

@ -145,7 +145,7 @@ class S3Bucket(resource.Resource):
try:
self.swift().delete_container(self.resource_id)
except clients.swiftclient.ClientException as ex:
logger.warn(_("Delete container failed: %s") % str(ex))
logger.warn(_("Delete container failed: %s") % ex)
def FnGetRefId(self):
return unicode(self.resource_id)

View File

@ -637,7 +637,7 @@ class Server(stack_user.StackUser):
server = self.nova().servers.get(self.resource_id)
except clients.novaclient.exceptions.NotFound as ex:
logger.warn(_('Instance (%(server)s) not found: %(ex)s') % {
'server': self.resource_id, 'ex': str(ex)})
'server': self.resource_id, 'ex': ex})
return ''
if name == 'addresses':
return self._add_port_for_address(server)

View File

@ -127,7 +127,7 @@ class SwiftContainer(resource.Resource):
try:
self.swift().delete_container(self.resource_id)
except clients.swiftclient.ClientException as ex:
logger.warn(_("Delete container failed: %s") % str(ex))
logger.warn(_("Delete container failed: %s") % ex)
def FnGetRefId(self):
return unicode(self.resource_id)
@ -146,7 +146,7 @@ class SwiftContainer(resource.Resource):
try:
headers = self.swift().head_container(self.resource_id)
except clients.swiftclient.ClientException as ex:
logger.warn(_("Head container failed: %s") % str(ex))
logger.warn(_("Head container failed: %s") % ex)
return None
else:
if key == 'ObjectCount':

View File

@ -15,6 +15,7 @@ import hashlib
import json
from requests import exceptions
import six
from heat.common import exception
from heat.common import template_format
@ -214,13 +215,13 @@ class TemplateResource(stack_resource.StackResource):
def validate(self):
if self.validation_exception is not None:
msg = str(self.validation_exception)
msg = six.text_type(self.validation_exception)
raise exception.StackValidationFailed(message=msg)
try:
self.template_data()
except ValueError as ex:
msg = _("Failed to retrieve template data: %s") % str(ex)
msg = _("Failed to retrieve template data: %s") % ex
raise exception.StackValidationFailed(message=msg)
cri = self.stack.env.get_resource_info(
self.type(),

View File

@ -238,7 +238,7 @@ class AccessKey(resource.Resource):
_('could not get secret for %(username)s '
'Error:%(msg)s') % {
'username': self.properties[self.USER_NAME],
'msg': str(ex)})
'msg': ex})
return self._secret or '000-000-000'

View File

@ -273,8 +273,8 @@ class VolumeDetachTask(object):
server_api.delete_server_volume(self.server_id, self.attachment_id)
except (clients.novaclient.exceptions.BadRequest,
clients.novaclient.exceptions.NotFound) as e:
logger.warning('%(res)s - %(err)s' % {'res': str(self),
'err': str(e)})
logger.warning(_('%(res)s - %(err)s') % {'res': str(self),
'err': e})
yield

View File

@ -60,7 +60,7 @@ class Timeout(BaseException):
"""
Initialise with the TaskRunner and a timeout period in seconds.
"""
message = _('%s Timed out') % task_runner
message = _('%s Timed out') % str(task_runner)
super(Timeout, self).__init__(message)
# Note that we don't attempt to handle leap seconds or large clock

View File

@ -14,6 +14,7 @@
import functools
import json
import six
from oslo.config import cfg
import webob
@ -210,8 +211,8 @@ class StackWatch(object):
try:
wrs = db_api.watch_rule_get_all_by_stack(stack_context, sid)
except Exception as ex:
logger.warn(_('periodic_task db error (%(msg)s) %(ex)s') % {
'msg': 'watch rule removed?', 'ex': str(ex)})
logger.warn(_('periodic_task db error watch rule removed? %(ex)s')
% ex)
return
def run_alarm_action(actions, details):
@ -599,7 +600,7 @@ class EngineService(service.Service):
try:
tmpl_resources = tmpl['Resources']
except KeyError as ex:
return {'Error': str(ex)}
return {'Error': six.text_type(ex)}
# validate overall template (top-level structure)
tmpl.validate()
@ -637,7 +638,7 @@ class EngineService(service.Service):
ResourceClass.validate_deletion_policy(res)
props.validate(with_value=False)
except Exception as ex:
return {'Error': str(ex)}
return {'Error': six.text_type(ex)}
tmpl_params = tmpl.parameters(None, {}, validate_value=False)
is_real_param = lambda p: p.name not in tmpl_params.PSEUDO_PARAMETERS
@ -1042,7 +1043,7 @@ class EngineService(service.Service):
try:
wrn = [w.name for w in db_api.watch_rule_get_all(cnxt)]
except Exception as ex:
logger.warn(_('show_watch (all) db error %s') % str(ex))
logger.warn(_('show_watch (all) db error %s') % ex)
return
wrs = [watchrule.WatchRule.load(cnxt, w) for w in wrn]
@ -1071,7 +1072,7 @@ class EngineService(service.Service):
try:
wds = db_api.watch_data_get_all(cnxt)
except Exception as ex:
logger.warn(_('show_metric (all) db error %s') % str(ex))
logger.warn(_('show_metric (all) db error %s') % ex)
return
result = [api.format_watch_data(w) for w in wds]

View File

@ -77,7 +77,7 @@ class WatchRule(object):
except Exception as ex:
logger.warn(_('WatchRule.load (%(watch_name)s) db error '
'%(ex)s') % {
'watch_name': watch_name, 'ex': str(ex)})
'watch_name': watch_name, 'ex': ex})
if watch is None:
raise exception.WatchRuleNotFound(watch_name=watch_name)
else: