From ca90c984ec656df512647a26114cc7095acff617 Mon Sep 17 00:00:00 2001 From: Liang Chen Date: Fri, 21 Feb 2014 18:22:58 +0800 Subject: [PATCH] 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 --- heat/api/aws/exception.py | 11 ++++++----- heat/api/cfn/v1/stacks.py | 2 +- heat/api/openstack/v1/stacks.py | 4 ++-- heat/common/exception.py | 3 ++- heat/common/notify.py | 3 ++- heat/common/serializers.py | 3 ++- heat/common/urlfetch.py | 4 ++-- heat/common/wsgi.py | 10 +++++----- heat/engine/cfn/functions.py | 4 +++- heat/engine/constraints.py | 4 +++- heat/engine/event.py | 4 +++- heat/engine/parameters.py | 8 +++++--- heat/engine/parser.py | 14 ++++++------- heat/engine/properties.py | 7 +++++-- heat/engine/resource.py | 23 ++++++++++++---------- heat/engine/resources/autoscaling.py | 4 +++- heat/engine/resources/eip.py | 4 ++-- heat/engine/resources/neutron/neutron.py | 3 +-- heat/engine/resources/nova_utils.py | 9 ++++----- heat/engine/resources/os_database.py | 2 +- heat/engine/resources/s3.py | 2 +- heat/engine/resources/server.py | 2 +- heat/engine/resources/swift.py | 4 ++-- heat/engine/resources/template_resource.py | 5 +++-- heat/engine/resources/user.py | 2 +- heat/engine/resources/volume.py | 4 ++-- heat/engine/scheduler.py | 2 +- heat/engine/service.py | 13 ++++++------ heat/engine/watchrule.py | 2 +- 29 files changed, 91 insertions(+), 71 deletions(-) diff --git a/heat/api/aws/exception.py b/heat/api/aws/exception.py index 1a8834339..444f5a4b3 100644 --- a/heat/api/aws/exception.py +++ b/heat/api/aws/exception.py @@ -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)) diff --git a/heat/api/cfn/v1/stacks.py b/heat/api/cfn/v1/stacks.py index 77cbf3d61..245c04fd8 100644 --- a/heat/api/cfn/v1/stacks.py +++ b/heat/api/cfn/v1/stacks.py @@ -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 diff --git a/heat/api/openstack/v1/stacks.py b/heat/api/openstack/v1/stacks.py index 78cba7e30..8c69ab003 100644 --- a/heat/api/openstack/v1/stacks.py +++ b/heat/api/openstack/v1/stacks.py @@ -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) diff --git a/heat/common/exception.py b/heat/common/exception.py index 2d0762d4d..bceed3dfd 100644 --- a/heat/common/exception.py +++ b/heat/common/exception.py @@ -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): diff --git a/heat/common/notify.py b/heat/common/notify.py index 530ded816..7b37b4d11 100644 --- a/heat/common/notify.py +++ b/heat/common/notify.py @@ -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() diff --git a/heat/common/serializers.py b/heat/common/serializers.py index 03e4004af..f8ad7c592 100644 --- a/heat/common/serializers.py +++ b/heat/common/serializers.py @@ -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 diff --git a/heat/common/urlfetch.py b/heat/common/urlfetch.py index ea0914a7a..4e4a39b46 100644 --- a/heat/common/urlfetch.py +++ b/heat/common/urlfetch.py @@ -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) diff --git a/heat/common/wsgi.py b/heat/common/wsgi.py index 86301cfe7..ed5067c16 100644 --- a/heat/common/wsgi.py +++ b/heat/common/wsgi.py @@ -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 = \ diff --git a/heat/engine/cfn/functions.py b/heat/engine/cfn/functions.py index ee0eec724..09c5c8984 100644 --- a/heat/engine/cfn/functions.py +++ b/heat/engine/cfn/functions.py @@ -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)] diff --git a/heat/engine/constraints.py b/heat/engine/constraints.py index 3c00d815e..32fbc7f1f 100644 --- a/heat/engine/constraints.py +++ b/heat/engine/constraints.py @@ -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: diff --git a/heat/engine/event.py b/heat/engine/event.py index 92ddcc635..b8c29e14f 100644 --- a/heat/engine/event.py +++ b/heat/engine/event.py @@ -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 diff --git a/heat/engine/parameters.py b/heat/engine/parameters.py index c0ddc0772..04b4a2239 100644 --- a/heat/engine/parameters.py +++ b/heat/engine/parameters.py @@ -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 diff --git a/heat/engine/parser.py b/heat/engine/parser.py index 6f6425ba9..d04498145 100644 --- a/heat/engine/parser.py +++ b/heat/engine/parser.py @@ -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: diff --git a/heat/engine/properties.py b/heat/engine/properties.py index 38cf2434e..2b560e853 100644 --- a/heat/engine/properties.py +++ b/heat/engine/properties.py @@ -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(): diff --git a/heat/engine/resource.py b/heat/engine/resource.py index 269ab21f7..d29ef7d5e 100644 --- a/heat/engine/resource.py +++ b/heat/engine/resource.py @@ -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 diff --git a/heat/engine/resources/autoscaling.py b/heat/engine/resources/autoscaling.py index 09f1a74a9..84ccf363c 100644 --- a/heat/engine/resources/autoscaling.py +++ b/heat/engine/resources/autoscaling.py @@ -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: diff --git a/heat/engine/resources/eip.py b/heat/engine/resources/eip.py index d9c965b16..d1a1c5275 100644 --- a/heat/engine/resources/eip.py +++ b/heat/engine/resources/eip.py @@ -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 '' diff --git a/heat/engine/resources/neutron/neutron.py b/heat/engine/resources/neutron/neutron.py index b3e9e0b9f..98268c006 100644 --- a/heat/engine/resources/neutron/neutron.py +++ b/heat/engine/resources/neutron/neutron.py @@ -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) diff --git a/heat/engine/resources/nova_utils.py b/heat/engine/resources/nova_utils.py index 1b506a558..64b054ad2 100644 --- a/heat/engine/resources/nova_utils.py +++ b/heat/engine/resources/nova_utils.py @@ -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: diff --git a/heat/engine/resources/os_database.py b/heat/engine/resources/os_database.py index 573e9797d..16294c067 100644 --- a/heat/engine/resources/os_database.py +++ b/heat/engine/resources/os_database.py @@ -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): ''' diff --git a/heat/engine/resources/s3.py b/heat/engine/resources/s3.py index e344c9bc3..2d0bfdb92 100644 --- a/heat/engine/resources/s3.py +++ b/heat/engine/resources/s3.py @@ -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) diff --git a/heat/engine/resources/server.py b/heat/engine/resources/server.py index b38298054..16b1c02d1 100644 --- a/heat/engine/resources/server.py +++ b/heat/engine/resources/server.py @@ -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) diff --git a/heat/engine/resources/swift.py b/heat/engine/resources/swift.py index 7092c259c..e134cda33 100644 --- a/heat/engine/resources/swift.py +++ b/heat/engine/resources/swift.py @@ -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': diff --git a/heat/engine/resources/template_resource.py b/heat/engine/resources/template_resource.py index a43836ae9..f2a938519 100644 --- a/heat/engine/resources/template_resource.py +++ b/heat/engine/resources/template_resource.py @@ -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(), diff --git a/heat/engine/resources/user.py b/heat/engine/resources/user.py index f73071319..47d1e3d74 100644 --- a/heat/engine/resources/user.py +++ b/heat/engine/resources/user.py @@ -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' diff --git a/heat/engine/resources/volume.py b/heat/engine/resources/volume.py index 5f261ca4e..b4e829a4b 100644 --- a/heat/engine/resources/volume.py +++ b/heat/engine/resources/volume.py @@ -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 diff --git a/heat/engine/scheduler.py b/heat/engine/scheduler.py index 2175fada1..52c16d8eb 100644 --- a/heat/engine/scheduler.py +++ b/heat/engine/scheduler.py @@ -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 diff --git a/heat/engine/service.py b/heat/engine/service.py index 8bad1c77d..f53803cff 100644 --- a/heat/engine/service.py +++ b/heat/engine/service.py @@ -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] diff --git a/heat/engine/watchrule.py b/heat/engine/watchrule.py index f7c67507e..6c1015ef5 100644 --- a/heat/engine/watchrule.py +++ b/heat/engine/watchrule.py @@ -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: