Add _() to fix i18N compliance (part 1)

In heat, almost 200 log message and at least 30 exception
message are not processed by _(), and will not been translated.
We should use '_("STRING ...")' to enable i18n support.

I will split to two parts for review easier because the files
lost of _() are too much.

Closes-Bug: #1249217

Change-Id: I2c86dc7770a7f6f107ba16711b9cba363ef9b906
This commit is contained in:
chenxiao 2013-11-14 16:57:01 +08:00
parent 161ae8154f
commit c7c4901c80
19 changed files with 159 additions and 113 deletions

View File

@ -30,6 +30,7 @@ import webob
from heat.api.aws import exception from heat.api.aws import exception
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -130,10 +131,10 @@ class EC2Token(wsgi.Middleware):
last_failure = None last_failure = None
for auth_uri in self._conf_get('allowed_auth_uris'): for auth_uri in self._conf_get('allowed_auth_uris'):
try: try:
logger.debug("Attempt authorize on %s" % auth_uri) logger.debug(_("Attempt authorize on %s") % auth_uri)
return self._authorize(req, auth_uri) return self._authorize(req, auth_uri)
except HeatAPIException as e: except HeatAPIException as e:
logger.debug("Authorize failed: %s" % e.__class__) logger.debug(_("Authorize failed: %s") % e.__class__)
last_failure = e last_failure = e
raise last_failure or exception.HeatAccessDeniedError() raise last_failure or exception.HeatAccessDeniedError()
@ -143,14 +144,14 @@ class EC2Token(wsgi.Middleware):
# here so that we can use both authentication methods. # here so that we can use both authentication methods.
# Returning here just means the user didn't supply AWS # Returning here just means the user didn't supply AWS
# authentication and we'll let the app try native keystone next. # authentication and we'll let the app try native keystone next.
logger.info("Checking AWS credentials..") logger.info(_("Checking AWS credentials.."))
signature = self._get_signature(req) signature = self._get_signature(req)
if not signature: if not signature:
if 'X-Auth-User' in req.headers: if 'X-Auth-User' in req.headers:
return self.application return self.application
else: else:
logger.info("No AWS Signature found.") logger.info(_("No AWS Signature found."))
raise exception.HeatIncompleteSignatureError() raise exception.HeatIncompleteSignatureError()
access = self._get_access(req) access = self._get_access(req)
@ -158,14 +159,14 @@ class EC2Token(wsgi.Middleware):
if 'X-Auth-User' in req.headers: if 'X-Auth-User' in req.headers:
return self.application return self.application
else: else:
logger.info("No AWSAccessKeyId/Authorization Credential") logger.info(_("No AWSAccessKeyId/Authorization Credential"))
raise exception.HeatMissingAuthenticationTokenError() raise exception.HeatMissingAuthenticationTokenError()
logger.info("AWS credentials found, checking against keystone.") logger.info(_("AWS credentials found, checking against keystone."))
if not auth_uri: if not auth_uri:
logger.error("Ec2Token authorization failed, no auth_uri " logger.error(_("Ec2Token authorization failed, no auth_uri "
"specified in config file") "specified in config file"))
raise exception.HeatInternalFailureError(_('Service ' raise exception.HeatInternalFailureError(_('Service '
'misconfigured')) 'misconfigured'))
# Make a copy of args for authentication and signature verification. # Make a copy of args for authentication and signature verification.
@ -189,7 +190,7 @@ class EC2Token(wsgi.Middleware):
headers = {'Content-Type': 'application/json'} headers = {'Content-Type': 'application/json'}
keystone_ec2_uri = self._conf_get_keystone_ec2_uri(auth_uri) keystone_ec2_uri = self._conf_get_keystone_ec2_uri(auth_uri)
logger.info('Authenticating with %s' % keystone_ec2_uri) logger.info(_('Authenticating with %s') % keystone_ec2_uri)
response = requests.post(keystone_ec2_uri, data=creds_json, response = requests.post(keystone_ec2_uri, data=creds_json,
headers=headers) headers=headers)
result = response.json() result = response.json()
@ -197,9 +198,9 @@ class EC2Token(wsgi.Middleware):
token_id = result['access']['token']['id'] token_id = result['access']['token']['id']
tenant = result['access']['token']['tenant']['name'] tenant = result['access']['token']['tenant']['name']
tenant_id = result['access']['token']['tenant']['id'] tenant_id = result['access']['token']['tenant']['id']
logger.info("AWS authentication successful.") logger.info(_("AWS authentication successful."))
except (AttributeError, KeyError): except (AttributeError, KeyError):
logger.info("AWS authentication failure.") logger.info(_("AWS authentication failure."))
# Try to extract the reason for failure so we can return the # Try to extract the reason for failure so we can return the
# appropriate AWS error via raising an exception # appropriate AWS error via raising an exception
try: try:

View File

@ -19,6 +19,7 @@
import webob.exc import webob.exc
from heat.common import wsgi from heat.common import wsgi
from heat.openstack.common.gettextutils import _
import heat.openstack.common.rpc.common as rpc_common import heat.openstack.common.rpc.common as rpc_common
@ -31,7 +32,8 @@ class HeatAPIException(webob.exc.HTTPError):
''' '''
code = 400 code = 400
title = "HeatAPIException" title = "HeatAPIException"
explanation = "Generic HeatAPIException, please use specific subclasses!" explanation = _("Generic HeatAPIException, please use specific "
"subclasses!")
err_type = "Sender" err_type = "Sender"
def __init__(self, detail=None): def __init__(self, detail=None):
@ -72,7 +74,7 @@ class HeatIncompleteSignatureError(HeatAPIException):
''' '''
code = 400 code = 400
title = "IncompleteSignature" title = "IncompleteSignature"
explanation = "The request signature does not conform to AWS standards" explanation = _("The request signature does not conform to AWS standards")
class HeatInternalFailureError(HeatAPIException): class HeatInternalFailureError(HeatAPIException):
@ -81,7 +83,8 @@ class HeatInternalFailureError(HeatAPIException):
''' '''
code = 500 code = 500
title = "InternalFailure" title = "InternalFailure"
explanation = "The request processing has failed due to an internal error" explanation = _("The request processing has failed due to an "
"internal error")
err_type = "Server" err_type = "Server"
@ -91,7 +94,7 @@ class HeatInvalidActionError(HeatAPIException):
''' '''
code = 400 code = 400
title = "InvalidAction" title = "InvalidAction"
explanation = "The action or operation requested is invalid" explanation = _("The action or operation requested is invalid")
class HeatInvalidClientTokenIdError(HeatAPIException): class HeatInvalidClientTokenIdError(HeatAPIException):
@ -100,7 +103,7 @@ class HeatInvalidClientTokenIdError(HeatAPIException):
''' '''
code = 403 code = 403
title = "InvalidClientTokenId" title = "InvalidClientTokenId"
explanation = "The certificate or AWS Key ID provided does not exist" explanation = _("The certificate or AWS Key ID provided does not exist")
class HeatInvalidParameterCombinationError(HeatAPIException): class HeatInvalidParameterCombinationError(HeatAPIException):
@ -109,7 +112,7 @@ class HeatInvalidParameterCombinationError(HeatAPIException):
''' '''
code = 400 code = 400
title = "InvalidParameterCombination" title = "InvalidParameterCombination"
explanation = "Incompatible parameters were used together" explanation = _("Incompatible parameters were used together")
class HeatInvalidParameterValueError(HeatAPIException): class HeatInvalidParameterValueError(HeatAPIException):
@ -118,7 +121,7 @@ class HeatInvalidParameterValueError(HeatAPIException):
''' '''
code = 400 code = 400
title = "InvalidParameterValue" title = "InvalidParameterValue"
explanation = "A bad or out-of-range value was supplied" explanation = _("A bad or out-of-range value was supplied")
class HeatInvalidQueryParameterError(HeatAPIException): class HeatInvalidQueryParameterError(HeatAPIException):
@ -127,7 +130,8 @@ class HeatInvalidQueryParameterError(HeatAPIException):
''' '''
code = 400 code = 400
title = "InvalidQueryParameter" title = "InvalidQueryParameter"
explanation = "AWS query string is malformed, does not adhere to AWS spec" explanation = _("AWS query string is malformed, does not adhere to "
"AWS spec")
class HeatMalformedQueryStringError(HeatAPIException): class HeatMalformedQueryStringError(HeatAPIException):
@ -136,7 +140,7 @@ class HeatMalformedQueryStringError(HeatAPIException):
''' '''
code = 404 code = 404
title = "MalformedQueryString" title = "MalformedQueryString"
explanation = "The query string is malformed" explanation = _("The query string is malformed")
class HeatMissingActionError(HeatAPIException): class HeatMissingActionError(HeatAPIException):
@ -145,7 +149,7 @@ class HeatMissingActionError(HeatAPIException):
''' '''
code = 400 code = 400
title = "MissingAction" title = "MissingAction"
explanation = "The request is missing an action or operation parameter" explanation = _("The request is missing an action or operation parameter")
class HeatMissingAuthenticationTokenError(HeatAPIException): class HeatMissingAuthenticationTokenError(HeatAPIException):
@ -155,7 +159,7 @@ class HeatMissingAuthenticationTokenError(HeatAPIException):
''' '''
code = 403 code = 403
title = "MissingAuthenticationToken" title = "MissingAuthenticationToken"
explanation = "Does not contain a valid AWS Access Key or certificate" explanation = _("Does not contain a valid AWS Access Key or certificate")
class HeatMissingParameterError(HeatAPIException): class HeatMissingParameterError(HeatAPIException):
@ -164,7 +168,7 @@ class HeatMissingParameterError(HeatAPIException):
''' '''
code = 400 code = 400
title = "MissingParameter" title = "MissingParameter"
explanation = "A mandatory input parameter is missing" explanation = _("A mandatory input parameter is missing")
class HeatOptInRequiredError(HeatAPIException): class HeatOptInRequiredError(HeatAPIException):
@ -173,7 +177,8 @@ class HeatOptInRequiredError(HeatAPIException):
''' '''
code = 403 code = 403
title = "OptInRequired" title = "OptInRequired"
explanation = "The AWS Access Key ID needs a subscription for the service" explanation = _("The AWS Access Key ID needs a subscription for the "
"service")
class HeatRequestExpiredError(HeatAPIException): class HeatRequestExpiredError(HeatAPIException):
@ -183,7 +188,7 @@ class HeatRequestExpiredError(HeatAPIException):
''' '''
code = 400 code = 400
title = "RequestExpired" title = "RequestExpired"
explanation = "Request expired or more than 15mins in the future" explanation = _("Request expired or more than 15mins in the future")
class HeatServiceUnavailableError(HeatAPIException): class HeatServiceUnavailableError(HeatAPIException):
@ -192,7 +197,7 @@ class HeatServiceUnavailableError(HeatAPIException):
''' '''
code = 503 code = 503
title = "ServiceUnavailable" title = "ServiceUnavailable"
explanation = "Service temporarily unvavailable" explanation = _("Service temporarily unvavailable")
err_type = "Server" err_type = "Server"
@ -202,7 +207,7 @@ class HeatThrottlingError(HeatAPIException):
''' '''
code = 400 code = 400
title = "Throttling" title = "Throttling"
explanation = "Request was denied due to request throttling" explanation = _("Request was denied due to request throttling")
class AlreadyExistsError(HeatAPIException): class AlreadyExistsError(HeatAPIException):
@ -211,7 +216,7 @@ class AlreadyExistsError(HeatAPIException):
''' '''
code = 400 code = 400
title = 'AlreadyExists' title = 'AlreadyExists'
explanation = "Resource with the name requested already exists" explanation = _("Resource with the name requested already exists")
# Not documented in the AWS docs, authentication failure errors # Not documented in the AWS docs, authentication failure errors
@ -222,7 +227,7 @@ class HeatAccessDeniedError(HeatAPIException):
''' '''
code = 403 code = 403
title = "AccessDenied" title = "AccessDenied"
explanation = "User is not authorized to perform action" explanation = _("User is not authorized to perform action")
class HeatSignatureError(HeatAPIException): class HeatSignatureError(HeatAPIException):
@ -232,8 +237,8 @@ class HeatSignatureError(HeatAPIException):
''' '''
code = 403 code = 403
title = "SignatureDoesNotMatch" title = "SignatureDoesNotMatch"
explanation = ("The request signature we calculated does not match the " + explanation = _("The request signature we calculated does not match the "
"signature you provided") "signature you provided")
# Heat-specific errors # Heat-specific errors
@ -243,7 +248,7 @@ class HeatAPINotImplementedError(HeatAPIException):
''' '''
code = 500 code = 500
title = "APINotImplemented" title = "APINotImplemented"
explanation = ("The requested action is not yet implemented") explanation = _("The requested action is not yet implemented")
err_type = "Server" err_type = "Server"

View File

@ -22,6 +22,7 @@ import itertools
from heat.api.aws import exception from heat.api.aws import exception
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -103,7 +104,7 @@ def get_param_value(params, key):
try: try:
return params[key] return params[key]
except KeyError: except KeyError:
LOG.error("Request does not contain %s parameter!" % key) LOG.error(_("Request does not contain %s parameter!") % key)
raise exception.HeatMissingParameterError(key) raise exception.HeatMissingParameterError(key)

View File

@ -26,6 +26,7 @@ from heat.rpc import api as engine_api
import heat.openstack.common.rpc.common as rpc_common import heat.openstack.common.rpc.common as rpc_common
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -213,7 +214,7 @@ class WatchController(object):
# Filter criteria not met, return None # Filter criteria not met, return None
return return
except KeyError: except KeyError:
logger.warning("Invalid filter key %s, ignoring" % f) logger.warning(_("Invalid filter key %s, ignoring") % f)
return result return result
@ -222,7 +223,7 @@ class WatchController(object):
# FIXME : Don't yet handle filtering by Dimensions # FIXME : Don't yet handle filtering by Dimensions
filter_result = dict((k, v) for (k, v) in parms.iteritems() if k in filter_result = dict((k, v) for (k, v) in parms.iteritems() if k in
("MetricName", "Namespace")) ("MetricName", "Namespace"))
logger.debug("filter parameters : %s" % filter_result) logger.debug(_("filter parameters : %s") % filter_result)
try: try:
# Engine does not currently support query by namespace/metric # Engine does not currently support query by namespace/metric
@ -268,7 +269,7 @@ class WatchController(object):
# need to process (each dict) for dimensions # need to process (each dict) for dimensions
metric_data = api_utils.extract_param_list(parms, prefix='MetricData') metric_data = api_utils.extract_param_list(parms, prefix='MetricData')
if not len(metric_data): if not len(metric_data):
logger.error("Request does not contain required MetricData") logger.error(_("Request does not contain required MetricData"))
return exception.HeatMissingParameterError("MetricData list") return exception.HeatMissingParameterError("MetricData list")
watch_name = None watch_name = None
@ -335,7 +336,8 @@ class WatchController(object):
if 'StateReasonData' in parms: if 'StateReasonData' in parms:
state_reason_data = parms['StateReasonData'] state_reason_data = parms['StateReasonData']
logger.debug("setting %s to %s" % (name, state_map[state])) logger.debug(_("setting %(name)s to %(state)s") % {
'name': name, 'state': state_map[state]})
try: try:
self.engine_rpcapi.set_watch_state(con, watch_name=name, self.engine_rpcapi.set_watch_state(con, watch_name=name,
state=state_map[state]) state=state_map[state])

View File

@ -21,6 +21,7 @@ Middleware for authenticating against custom backends.
import logging import logging
from heat.openstack.common.gettextutils import _
from heat.openstack.common import local from heat.openstack.common import local
from heat.rpc import client as rpc_client from heat.rpc import client as rpc_client
import webob.exc import webob.exc
@ -41,7 +42,7 @@ class AuthProtocol(object):
Authenticate send downstream on success. Reject request if Authenticate send downstream on success. Reject request if
we can't authenticate. we can't authenticate.
""" """
LOG.debug('Authenticating user token') LOG.debug(_('Authenticating user token'))
context = local.store.context context = local.store.context
engine = rpc_client.EngineClient() engine = rpc_client.EngineClient()
authenticated = engine.authenticated_to_backend(context) authenticated = engine.authenticated_to_backend(context)
@ -58,7 +59,8 @@ class AuthProtocol(object):
:param start_response: wsgi response callback :param start_response: wsgi response callback
:returns HTTPUnauthorized http response :returns HTTPUnauthorized http response
""" """
resp = webob.exc.HTTPUnauthorized("Backend authentication failed", []) resp = webob.exc.HTTPUnauthorized(_("Backend authentication failed"),
[])
return resp(env, start_response) return resp(env, start_response)

View File

@ -24,6 +24,7 @@ from oslo.config import cfg
from heat.openstack.common import importutils from heat.openstack.common import importutils
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
logger = logging.getLogger('heat.common.keystoneclient') logger = logging.getLogger('heat.common.keystoneclient')
@ -97,8 +98,8 @@ class KeystoneClient(object):
kwargs['tenant_name'] = self.context.tenant kwargs['tenant_name'] = self.context.tenant
kwargs['tenant_id'] = self.context.tenant_id kwargs['tenant_id'] = self.context.tenant_id
else: else:
logger.error("Keystone v2 API connection failed, no password or " logger.error(_("Keystone v2 API connection failed, no password "
"auth_token!") "or auth_token!"))
raise exception.AuthorizationFailure() raise exception.AuthorizationFailure()
client_v2 = kc.Client(**kwargs) client_v2 = kc.Client(**kwargs)
@ -108,7 +109,7 @@ class KeystoneClient(object):
if auth_kwargs: if auth_kwargs:
# Sanity check # Sanity check
if not client_v2.auth_ref.trust_scoped: if not client_v2.auth_ref.trust_scoped:
logger.error("v2 trust token re-scoping failed!") logger.error(_("v2 trust token re-scoping failed!"))
raise exception.AuthorizationFailure() raise exception.AuthorizationFailure()
# All OK so update the context with the token # All OK so update the context with the token
self.context.auth_token = client_v2.auth_ref.auth_token self.context.auth_token = client_v2.auth_ref.auth_token
@ -157,8 +158,8 @@ class KeystoneClient(object):
kwargs['auth_url'] = self.context.auth_url.replace('v2.0', 'v3') kwargs['auth_url'] = self.context.auth_url.replace('v2.0', 'v3')
kwargs['endpoint'] = kwargs['auth_url'] kwargs['endpoint'] = kwargs['auth_url']
else: else:
logger.error("Keystone v3 API connection failed, no password or " logger.error(_("Keystone v3 API connection failed, no password "
"auth_token!") "or auth_token!"))
raise exception.AuthorizationFailure() raise exception.AuthorizationFailure()
client = kc_v3.Client(**kwargs) client = kc_v3.Client(**kwargs)
@ -216,8 +217,8 @@ class KeystoneClient(object):
Returns the keystone ID of the resulting user Returns the keystone ID of the resulting user
""" """
if(len(username) > 64): if(len(username) > 64):
logger.warning("Truncating the username %s to the last 64 " logger.warning(_("Truncating the username %s to the last 64 "
"characters." % username) "characters.") % username)
#get the last 64 characters of the username #get the last 64 characters of the username
username = username[-64:] username = username[-64:]
user = self.client_v2.users.create(username, user = self.client_v2.users.create(username,
@ -236,12 +237,14 @@ class KeystoneClient(object):
if r.name == cfg.CONF.heat_stack_user_role] if r.name == cfg.CONF.heat_stack_user_role]
if len(stack_user_role) == 1: if len(stack_user_role) == 1:
role_id = stack_user_role[0] role_id = stack_user_role[0]
logger.debug("Adding user %s to role %s" % (user.id, role_id)) logger.debug(_("Adding user %(user)s to role %(role)s") % {
'user': user.id, 'role': role_id})
self.client_v2.roles.add_user_role(user.id, role_id, self.client_v2.roles.add_user_role(user.id, role_id,
self.context.tenant_id) self.context.tenant_id)
else: else:
logger.error("Failed to add user %s to role %s, check role exists!" logger.error(_("Failed to add user %(user)s to role %(role)s, "
% (username, cfg.CONF.heat_stack_user_role)) "check role exists!") % {'user': username,
'role': cfg.CONF.heat_stack_user_role})
return user.id return user.id
@ -265,8 +268,9 @@ class KeystoneClient(object):
status = 'DELETED' status = 'DELETED'
except Exception as ce: except Exception as ce:
reason = str(ce) reason = str(ce)
logger.warning("Problem deleting user %s: %s" % logger.warning(_("Problem deleting user %(user)s: "
(user_id, reason)) "%(reason)s") % {'user': user_id,
'reason': reason})
eventlet.sleep(1) eventlet.sleep(1)
except eventlet.Timeout as t: except eventlet.Timeout as t:
if t is not tmo: if t is not tmo:
@ -294,8 +298,9 @@ class KeystoneClient(object):
if len(cred) == 1: if len(cred) == 1:
return cred[0] return cred[0]
else: else:
logger.error("Unexpected number of ec2 credentials %s for %s" % logger.error(_("Unexpected number of ec2 credentials %(len)s "
(len(cred), user_id)) "for %(user)s") % {'len': len(cred),
'user': user_id})
def disable_stack_user(self, user_id): def disable_stack_user(self, user_id):
# FIXME : This won't work with the v3 keystone API # FIXME : This won't work with the v3 keystone API

View File

@ -716,7 +716,8 @@ class Resource(object):
err_body = action_result.get_unserialized_body() err_body = action_result.get_unserialized_body()
serializer.default(action_result, err_body) serializer.default(action_result, err_body)
except Exception: except Exception:
logging.warning("Unable to serialize exception response") logging.warning(_("Unable to serialize exception "
"response"))
return action_result return action_result

View File

@ -73,7 +73,7 @@ def raw_template_get(context, template_id):
result = model_query(context, models.RawTemplate).get(template_id) result = model_query(context, models.RawTemplate).get(template_id)
if not result: if not result:
raise exception.NotFound('raw template with id %s not found' % raise exception.NotFound(_('raw template with id %s not found') %
template_id) template_id)
return result return result
@ -90,7 +90,8 @@ def resource_get(context, resource_id):
result = model_query(context, models.Resource).get(resource_id) result = model_query(context, models.Resource).get(resource_id)
if not result: if not result:
raise exception.NotFound("resource with id %s not found" % resource_id) raise exception.NotFound(_("resource with id %s not found") %
resource_id)
return result return result
@ -119,7 +120,7 @@ def resource_get_all(context):
results = model_query(context, models.Resource).all() results = model_query(context, models.Resource).all()
if not results: if not results:
raise exception.NotFound('no resources were found') raise exception.NotFound(_('no resources were found'))
return results return results
@ -156,7 +157,7 @@ def resource_data_get_by_key(context, resource_id, key):
.filter_by(key=key).first()) .filter_by(key=key).first())
if not result: if not result:
raise exception.NotFound('No resource data found') raise exception.NotFound(_('No resource data found'))
return result return result
@ -206,8 +207,8 @@ def resource_get_all_by_stack(context, stack_id):
filter_by(stack_id=stack_id).all() filter_by(stack_id=stack_id).all()
if not results: if not results:
raise exception.NotFound("no resources for stack_id %s were found" % raise exception.NotFound(_("no resources for stack_id %s were found")
stack_id) % stack_id)
return results return results
@ -272,8 +273,10 @@ def stack_update(context, stack_id, values):
stack = stack_get(context, stack_id) stack = stack_get(context, stack_id)
if not stack: if not stack:
raise exception.NotFound('Attempt to update a stack with id: %s %s' % raise exception.NotFound(_('Attempt to update a stack with id: '
(stack_id, 'that does not exist')) '%(id)s %(msg)s') % {
'id': stack_id,
'msg': 'that does not exist'})
old_template_id = stack.raw_template_id old_template_id = stack.raw_template_id
@ -284,8 +287,10 @@ def stack_update(context, stack_id, values):
def stack_delete(context, stack_id): def stack_delete(context, stack_id):
s = stack_get(context, stack_id) s = stack_get(context, stack_id)
if not s: if not s:
raise exception.NotFound('Attempt to delete a stack with id: %s %s' % raise exception.NotFound(_('Attempt to delete a stack with id: '
(stack_id, 'that does not exist')) '%(id)s %(msg)s') % {
'id': stack_id,
'msg': 'that does not exist'})
session = Session.object_session(s) session = Session.object_session(s)
@ -432,8 +437,10 @@ def watch_rule_update(context, watch_id, values):
wr = watch_rule_get(context, watch_id) wr = watch_rule_get(context, watch_id)
if not wr: if not wr:
raise exception.NotFound('Attempt to update a watch with id: %s %s' % raise exception.NotFound(_('Attempt to update a watch with id: '
(watch_id, 'that does not exist')) '%(id)s %(msg)s') % {
'id': watch_id,
'msg': 'that does not exist'})
wr.update(values) wr.update(values)
wr.save(_session(context)) wr.save(_session(context))
@ -442,9 +449,10 @@ def watch_rule_update(context, watch_id, values):
def watch_rule_delete(context, watch_id): def watch_rule_delete(context, watch_id):
wr = watch_rule_get(context, watch_id) wr = watch_rule_get(context, watch_id)
if not wr: if not wr:
raise exception.NotFound('Attempt to delete watch_rule: %s %s' % raise exception.NotFound(_('Attempt to delete watch_rule: '
(watch_id, 'that does not exist')) '%(id)s %(msg)s') % {
'id': watch_id,
'msg': 'that does not exist'})
session = Session.object_session(wr) session = Session.object_session(wr)
for d in wr.watch_data: for d in wr.watch_data:

View File

@ -43,7 +43,8 @@ def patched_with_engine(f, *a, **kw):
return f(*a, **kw) return f(*a, **kw)
finally: finally:
if isinstance(engine, migrate_util.Engine) and engine is not url: if isinstance(engine, migrate_util.Engine) and engine is not url:
migrate_util.log.debug('Disposing SQLAlchemy engine %s', engine) migrate_util.log.debug(_('Disposing SQLAlchemy engine %s') %
engine)
engine.dispose() engine.dispose()

View File

@ -64,7 +64,7 @@ def _list_environment_files(env_dir):
try: try:
return os.listdir(env_dir) return os.listdir(env_dir)
except OSError as osex: except OSError as osex:
LOG.error('Failed to read %s' % (env_dir)) LOG.error(_('Failed to read %s') % env_dir)
LOG.exception(osex) LOG.exception(osex)
return [] return []
@ -83,15 +83,17 @@ def _load_global_environment(env, env_dir=None):
try: try:
file_path = os.path.join(env_dir, env_name) file_path = os.path.join(env_dir, env_name)
with open(file_path) as env_fd: with open(file_path) as env_fd:
LOG.info('Loading %s' % file_path) LOG.info(_('Loading %s') % file_path)
env_body = environment_format.parse(env_fd.read()) env_body = environment_format.parse(env_fd.read())
environment_format.default_for_missing(env_body) environment_format.default_for_missing(env_body)
env.load(env_body) env.load(env_body)
except ValueError as vex: except ValueError as vex:
LOG.error('Failed to parse %s/%s' % (env_dir, env_name)) LOG.error(_('Failed to parse %(dir)s/%(name)s') % {
'dir': env_dir, 'name': env_name})
LOG.exception(vex) LOG.exception(vex)
except IOError as ioex: except IOError as ioex:
LOG.error('Failed to read %s/%s' % (env_dir, env_name)) LOG.error(_('Failed to read %(dir)s/%(name)s') % {
'dir': env_dir, 'name': env_name})
LOG.exception(ioex) LOG.exception(ioex)

View File

@ -498,8 +498,10 @@ class AutoScalingGroup(InstanceGroup, CooldownMixin):
Adjust the size of the scaling group if the cooldown permits. Adjust the size of the scaling group if the cooldown permits.
""" """
if self._cooldown_inprogress(): if self._cooldown_inprogress():
logger.info("%s NOT performing scaling adjustment, cooldown %s" % logger.info(_("%(name)s NOT performing scaling adjustment, "
(self.name, self.properties['Cooldown'])) "cooldown %(cooldown)s") % {
'name': self.name,
'cooldown': self.properties['Cooldown']})
return return
capacity = len(self.get_instances()) capacity = len(self.get_instances())
@ -519,14 +521,15 @@ class AutoScalingGroup(InstanceGroup, CooldownMixin):
new_capacity = capacity + rounded new_capacity = capacity + rounded
if new_capacity > int(self.properties['MaxSize']): if new_capacity > int(self.properties['MaxSize']):
logger.warn('can not exceed %s' % self.properties['MaxSize']) logger.warn(_('can not exceed %s') % self.properties['MaxSize'])
return return
if new_capacity < int(self.properties['MinSize']): if new_capacity < int(self.properties['MinSize']):
logger.warn('can not be less than %s' % self.properties['MinSize']) logger.warn(_('can not be less than %s') %
self.properties['MinSize'])
return return
if new_capacity == capacity: if new_capacity == capacity:
logger.debug('no change in capacity %d' % capacity) logger.debug(_('no change in capacity %d') % capacity)
return return
result = self.resize(new_capacity) result = self.resize(new_capacity)
@ -664,21 +667,25 @@ class ScalingPolicy(signal_responder.SignalResponder, CooldownMixin):
alarm_state = details.get('current', alarm_state = details.get('current',
details.get('state', 'alarm')).lower() details.get('state', 'alarm')).lower()
logger.info('%s Alarm, new state %s' % (self.name, alarm_state)) logger.info(_('%(name)s Alarm, new state %(state)s') % {
'name': self.name, 'state': alarm_state})
if alarm_state != 'alarm': if alarm_state != 'alarm':
return return
if self._cooldown_inprogress(): if self._cooldown_inprogress():
logger.info("%s NOT performing scaling action, cooldown %s" % logger.info(_("%(name)s NOT performing scaling action, "
(self.name, self.properties['Cooldown'])) "cooldown %(cooldown)s") % {
'name': self.name,
'cooldown': self.properties['Cooldown']})
return return
asgn_id = self.properties['AutoScalingGroupName'] asgn_id = self.properties['AutoScalingGroupName']
group = self.stack.resource_by_refid(asgn_id) group = self.stack.resource_by_refid(asgn_id)
logger.info('%s Alarm, adjusting Group %s by %s' % logger.info(_('%(name)s Alarm, adjusting Group %(group)s '
(self.name, group.name, 'by %(filter)s') % {
self.properties['ScalingAdjustment'])) 'name': self.name, 'group': group.name,
'filter': self.properties['ScalingAdjustment']})
group.adjust(int(self.properties['ScalingAdjustment']), group.adjust(int(self.properties['ScalingAdjustment']),
self.properties['AdjustmentType']) self.properties['AdjustmentType'])

View File

@ -20,6 +20,7 @@ from heat.common import exception
from heat.openstack.common import excutils from heat.openstack.common import excutils
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -52,14 +53,14 @@ class ElasticIp(resource.Resource):
ips = self.neutron().show_floatingip(self.resource_id) ips = self.neutron().show_floatingip(self.resource_id)
except ne as e: except ne as e:
if e.status_code == 404: if e.status_code == 404:
logger.warn("Floating IPs not found: %s" % str(e)) logger.warn(_("Floating IPs not found: %s") % str(e))
else: else:
self.ipaddress = ips['floatingip']['floating_ip_address'] self.ipaddress = ips['floatingip']['floating_ip_address']
else: else:
try: try:
ips = self.nova().floating_ips.get(self.resource_id) ips = self.nova().floating_ips.get(self.resource_id)
except clients.novaclient.exceptions.NotFound as ex: except clients.novaclient.exceptions.NotFound as ex:
logger.warn("Floating IPs not found: %s" % str(ex)) logger.warn(_("Floating IPs not found: %s") % str(ex))
else: else:
self.ipaddress = ips.ip self.ipaddress = ips.ip
return self.ipaddress or '' return self.ipaddress or ''
@ -76,24 +77,24 @@ class ElasticIp(resource.Resource):
'floatingip': props})['floatingip'] 'floatingip': props})['floatingip']
self.ipaddress = ips['floating_ip_address'] self.ipaddress = ips['floating_ip_address']
self.resource_id_set(ips['id']) self.resource_id_set(ips['id'])
logger.info('ElasticIp create %s' % str(ips)) logger.info(_('ElasticIp create %s') % str(ips))
else: else:
if self.properties['Domain']: if self.properties['Domain']:
raise exception.Error('Domain property can not be set on ' raise exception.Error(_('Domain property can not be set on '
'resource %s without Neutron available' % 'resource %s without Neutron available')
self.name) % self.name)
try: try:
ips = self.nova().floating_ips.create() ips = self.nova().floating_ips.create()
except clients.novaclient.exceptions.NotFound: except clients.novaclient.exceptions.NotFound:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
msg = ("No default floating IP pool configured." msg = _("No default floating IP pool configured. "
"Set 'default_floating_pool' in nova.conf.") "Set 'default_floating_pool' in nova.conf.")
logger.error(msg) logger.error(msg)
if ips: if ips:
self.ipaddress = ips.ip self.ipaddress = ips.ip
self.resource_id_set(ips.id) self.resource_id_set(ips.id)
logger.info('ElasticIp create %s' % str(ips)) logger.info(_('ElasticIp create %s') % str(ips))
if self.properties['InstanceId']: if self.properties['InstanceId']:
server = self.nova().servers.get(self.properties['InstanceId']) server = self.nova().servers.get(self.properties['InstanceId'])
@ -160,7 +161,8 @@ class ElasticIpAssociation(resource.Resource):
if self.properties['EIP']: if self.properties['EIP']:
if not self.properties['InstanceId']: if not self.properties['InstanceId']:
logger.warn('Skipping association, InstanceId not specified') logger.warn(_('Skipping association, InstanceId not '
'specified'))
return return
server = self.nova().servers.get(self.properties['InstanceId']) server = self.nova().servers.get(self.properties['InstanceId'])
server.add_floating_ip(self.properties['EIP']) server.add_floating_ip(self.properties['EIP'])
@ -181,7 +183,7 @@ class ElasticIpAssociation(resource.Resource):
port_rsrc = ports['ports'][0] port_rsrc = ports['ports'][0]
port_id = port_rsrc['id'] port_id = port_rsrc['id']
else: else:
logger.warn('Skipping association, resource not specified') logger.warn(_('Skipping association, resource not specified'))
return return
float_id = self.properties['AllocationId'] float_id = self.properties['AllocationId']

View File

@ -56,19 +56,21 @@ class Restarter(signal_responder.SignalResponder):
else: else:
alarm_state = details.get('state', 'alarm').lower() alarm_state = details.get('state', 'alarm').lower()
logger.info('%s Alarm, new state %s' % (self.name, alarm_state)) logger.info(_('%(name)s Alarm, new state %(state)s') % {
'name': self.name, 'state': alarm_state})
if alarm_state != 'alarm': if alarm_state != 'alarm':
return return
victim = self._find_resource(self.properties['InstanceId']) victim = self._find_resource(self.properties['InstanceId'])
if victim is None: if victim is None:
logger.info('%s Alarm, can not find instance %s' % logger.info(_('%(name)s Alarm, can not find instance '
(self.name, self.properties['InstanceId'])) '%(instance)s') % {'name': self.name,
'instance': self.properties['InstanceId']})
return return
logger.info('%s Alarm, restarting resource: %s' % logger.info(_('%(name)s Alarm, restarting resource: %(victim)s') % {
(self.name, victim.name)) 'name': self.name, 'victim': victim.name})
self.stack.restart_resource(victim.name) self.stack.restart_resource(victim.name)
def _resolve_attribute(self, name): def _resolve_attribute(self, name):
@ -536,7 +538,7 @@ class Instance(resource.Resource):
raise exception.NotFound(_('Failed to find instance %s') % raise exception.NotFound(_('Failed to find instance %s') %
self.resource_id) self.resource_id)
else: else:
logger.debug("suspending instance %s" % self.resource_id) logger.debug(_("suspending instance %s") % self.resource_id)
# We want the server.suspend to happen after the volume # We want the server.suspend to happen after the volume
# detachement has finished, so pass both tasks and the server # detachement has finished, so pass both tasks and the server
suspend_runner = scheduler.TaskRunner(server.suspend) suspend_runner = scheduler.TaskRunner(server.suspend)
@ -590,7 +592,7 @@ class Instance(resource.Resource):
raise exception.NotFound(_('Failed to find instance %s') % raise exception.NotFound(_('Failed to find instance %s') %
self.resource_id) self.resource_id)
else: else:
logger.debug("resuming instance %s" % self.resource_id) logger.debug(_("resuming instance %s") % self.resource_id)
server.resume() server.resume()
return server, scheduler.TaskRunner(self._attach_volumes_task()) return server, scheduler.TaskRunner(self._attach_volumes_task())

View File

@ -16,6 +16,7 @@
from heat.engine import clients from heat.engine import clients
from heat.common import exception from heat.common import exception
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
from heat.engine import resource from heat.engine import resource
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -49,7 +50,7 @@ class InternetGateway(resource.Resource):
# add a heat configuration variable to set the ID of # add a heat configuration variable to set the ID of
# the default one # the default one
raise exception.Error( raise exception.Error(
'Expected 1 external network, found %d' % len(ext_nets)) _('Expected 1 external network, found %d') % len(ext_nets))
external_network_id = ext_nets[0]['id'] external_network_id = ext_nets[0]['id']
return external_network_id return external_network_id

View File

@ -18,6 +18,7 @@ from heat.engine import stack_resource
from heat.engine.resources import nova_utils from heat.engine.resources import nova_utils
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -353,7 +354,7 @@ class LoadBalancer(stack_resource.StackResource):
client = self.nova() client = self.nova()
for i in instances: for i in instances:
ip = nova_utils.server_to_ipaddress(client, i) or '0.0.0.0' ip = nova_utils.server_to_ipaddress(client, i) or '0.0.0.0'
logger.debug('haproxy server:%s' % ip) logger.debug(_('haproxy server:%s') % ip)
servers.append('%sserver server%d %s:%s %s' % (spaces, n, servers.append('%sserver server%d %s:%s %s' % (spaces, n,
ip, inst_port, ip, inst_port,
check)) check))

View File

@ -80,7 +80,8 @@ class FloatingIP(neutron.NeutronResource):
attributes = self.neutron().show_floatingip( attributes = self.neutron().show_floatingip(
self.resource_id)['floatingip'] self.resource_id)['floatingip']
except NeutronClientException as ex: except NeutronClientException as ex:
logger.warn("failed to fetch resource attributes: %s" % str(ex)) logger.warn(_("failed to fetch resource attributes: %s") %
str(ex))
return None return None
return self.handle_get_attributes(self.name, key, attributes) return self.handle_get_attributes(self.name, key, attributes)

View File

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

View File

@ -144,7 +144,7 @@ class Port(neutron.NeutronResource):
self._prepare_list_properties(props) self._prepare_list_properties(props)
logger.debug('updating port with %s' % props) logger.debug(_('updating port with %s') % props)
self.neutron().update_port(self.resource_id, {'port': props}) self.neutron().update_port(self.resource_id, {'port': props})
def check_update_complete(self, *args): def check_update_complete(self, *args):

View File

@ -29,6 +29,7 @@ from heat.common import exception
from heat.engine import clients from heat.engine import clients
from heat.engine import scheduler from heat.engine import scheduler
from heat.openstack.common import log as logging from heat.openstack.common import log as logging
from heat.openstack.common.gettextutils import _
from heat.openstack.common import uuidutils from heat.openstack.common import uuidutils
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@ -60,7 +61,7 @@ def get_image_id(nova_client, image_identifier):
try: try:
image_id = nova_client.images.get(image_identifier).id image_id = nova_client.images.get(image_identifier).id
except clients.novaclient.exceptions.NotFound: except clients.novaclient.exceptions.NotFound:
logger.info("Image %s was not found in glance" logger.info(_("Image %s was not found in glance")
% image_identifier) % image_identifier)
raise exception.ImageNotFound(image_name=image_identifier) raise exception.ImageNotFound(image_name=image_identifier)
else: else:
@ -68,16 +69,17 @@ def get_image_id(nova_client, image_identifier):
image_list = nova_client.images.list() image_list = nova_client.images.list()
except clients.novaclient.exceptions.ClientException as ex: except clients.novaclient.exceptions.ClientException as ex:
raise exception.Error( raise exception.Error(
message="Error retrieving image list from nova: %s" % str(ex)) message=(_("Error retrieving image list from nova: %s") %
str(ex)))
image_names = dict( image_names = dict(
(o.id, o.name) (o.id, o.name)
for o in image_list if o.name == image_identifier) for o in image_list if o.name == image_identifier)
if len(image_names) == 0: if len(image_names) == 0:
logger.info("Image %s was not found in glance" % logger.info(_("Image %s was not found in glance") %
image_identifier) image_identifier)
raise exception.ImageNotFound(image_name=image_identifier) raise exception.ImageNotFound(image_name=image_identifier)
elif len(image_names) > 1: elif len(image_names) > 1:
logger.info("Mulitple images %s were found in glance with name" logger.info(_("Mulitple images %s were found in glance with name")
% image_identifier) % image_identifier)
raise exception.PhysicalResourceNameAmbiguity( raise exception.PhysicalResourceNameAmbiguity(
name=image_identifier) name=image_identifier)
@ -264,7 +266,8 @@ def server_to_ipaddress(client, server):
try: try:
server = client.servers.get(server) server = client.servers.get(server)
except clients.novaclient.exceptions.NotFound as ex: except clients.novaclient.exceptions.NotFound as ex:
logger.warn('Instance (%s) not found: %s' % (server, str(ex))) logger.warn(_('Instance (%(server)s) not found: %(ex)s') % {
'server': server, 'ex': str(ex)})
else: else:
for n in server.networks: for n in server.networks:
if len(server.networks[n]) > 0: if len(server.networks[n]) > 0: