Remove log translations

Log messages are no longer being translated. This removes all use of
the _LE, _LI, and _LW translation markers to simplify logging and to
avoid confusion with new contributions.

See:
http://lists.openstack.org/pipermail/openstack-i18n/2016-November/002574.html
http://lists.openstack.org/pipermail/openstack-dev/2017-March/113365.html

Change-Id: If1f4bd2f6be967368f52fb367c5a428d3eb58a9d
Closes-Bug:#1674551
This commit is contained in:
yuanpeng 2017-03-21 21:46:39 +08:00
parent c6656672e2
commit 71d25456d2
33 changed files with 149 additions and 247 deletions

View File

@ -20,7 +20,6 @@ from magnum.api import config as api_config
from magnum.api import middleware
from magnum.common import config as common_config
import magnum.conf
from magnum.i18n import _LI
CONF = magnum.conf.CONF
@ -60,7 +59,7 @@ def load_app():
if not cfg_file:
raise cfg.ConfigFilesNotFoundError([CONF.api.api_paste_config])
LOG.info(_LI("Full WSGI config used: %s"), cfg_file)
LOG.info("Full WSGI config used: %s" % cfg_file)
return deploy.loadapp("config:" + cfg_file)

View File

@ -33,7 +33,6 @@ from magnum.common import clients
from magnum.common import exception
from magnum.common import name_generator
from magnum.common import policy
from magnum.i18n import _LW
from magnum import objects
from magnum.objects import fields
@ -355,9 +354,9 @@ class BaysController(base.Controller):
bay.stack_id, nested_depth=2, filters=filters)
except Exception as e:
failed_resources = []
LOG.warning(_LW("Failed to retrieve failed resources for "
"bay %(bay)s from Heat stack %(stack)s "
"due to error: %(e)s"),
LOG.warning("Failed to retrieve failed resources for "
"bay %(bay)s from Heat stack %(stack)s "
"due to error: %(e)s" %
{'bay': bay.uuid, 'stack': bay.stack_id, 'e': e},
exc_info=True)

View File

@ -35,7 +35,6 @@ from magnum.common import name_generator
from magnum.common import policy
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LW
from magnum import objects
from magnum.objects import fields
@ -328,9 +327,9 @@ class ClustersController(base.Controller):
cluster.stack_id, nested_depth=2, filters=filters)
except Exception as e:
failed_resources = []
LOG.warning(_LW("Failed to retrieve failed resources for "
"cluster %(cluster)s from Heat stack "
"%(stack)s due to error: %(e)s"),
LOG.warning("Failed to retrieve failed resources for "
"cluster %(cluster)s from Heat stack "
"%(stack)s due to error: %(e)s" %
{'cluster': cluster.uuid,
'stack': cluster.stack_id, 'e': e},
exc_info=True)

View File

@ -22,7 +22,6 @@ from magnum.common import exception
from magnum.common import utils
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LE
from magnum import objects
CONF = magnum.conf.CONF
@ -120,10 +119,10 @@ def get_openstack_resource(manager, resource_ident, resource_type):
raise exception.ResourceNotFound(name=resource_type,
id=resource_ident)
if len(matches) > 1:
msg = _LE("Multiple %(resource_type)s exist with same name "
"%(resource_ident)s. Please use the resource id "
"instead.") % {'resource_type': resource_type,
'resource_ident': resource_ident}
msg = ("Multiple %(resource_type)s exist with same name "
"%(resource_ident)s. Please use the resource id "
"instead." % {'resource_type': resource_type,
'resource_ident': resource_ident})
raise exception.Conflict(msg)
resource_data = matches[0]
return resource_data

View File

@ -27,7 +27,6 @@ from magnum.common import profiler
from magnum.common import service
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LI
from magnum.objects import base
from magnum import version
@ -73,17 +72,17 @@ def main():
# Create the WSGI server and start it
host, port = CONF.api.host, CONF.api.port
LOG.info(_LI('Starting server in PID %s'), os.getpid())
LOG.info('Starting server in PID %s' % os.getpid())
LOG.debug("Configuration:")
CONF.log_opt_values(LOG, logging.DEBUG)
LOG.info(_LI('Serving on %(proto)s://%(host)s:%(port)s'),
LOG.info('Serving on %(proto)s://%(host)s:%(port)s' %
dict(proto="https" if use_ssl else "http", host=host, port=port))
workers = CONF.api.workers
if not workers:
workers = processutils.get_worker_count()
LOG.info(_LI('Server will handle each request in a new process up to'
' %s concurrent processes'), workers)
LOG.info('Server will handle each request in a new process up to'
' %s concurrent processes' % workers)
serving.run_simple(host, port, app, processes=workers,
ssl_context=_get_ssl_configs(use_ssl))

View File

@ -29,7 +29,6 @@ from magnum.conductor.handlers import cluster_conductor
from magnum.conductor.handlers import conductor_listener
from magnum.conductor.handlers import indirection_api
import magnum.conf
from magnum.i18n import _LI
from magnum import version
CONF = magnum.conf.CONF
@ -41,7 +40,7 @@ def main():
gmr.TextGuruMeditation.setup_autorun(version)
LOG.info(_LI('Starting server in PID %s'), os.getpid())
LOG.info('Starting server in PID %s' % os.getpid())
LOG.debug("Configuration:")
CONF.log_opt_values(LOG, logging.DEBUG)

View File

@ -22,9 +22,6 @@ from magnum.common import clients
from magnum.common import context
from magnum.common import exception as magnum_exc
from magnum.i18n import _
from magnum.i18n import _LE
from magnum.i18n import _LI
from magnum.i18n import _LW
LOG = logging.getLogger(__name__)
@ -90,9 +87,8 @@ class CertManager(cert_manager.CertManager):
"""
connection = get_admin_clients().barbican()
LOG.info(_LI(
"Storing certificate container '{0}' in Barbican."
).format(name))
LOG.info("Storing certificate container '{0}' in Barbican."
.format(name))
certificate_secret = None
private_key_secret = None
@ -143,16 +139,15 @@ class CertManager(cert_manager.CertManager):
old_ref = secret.secret_ref
try:
secret.delete()
LOG.info(_LI(
"Deleted secret {0} ({1}) during rollback."
).format(secret.name, old_ref))
LOG.info("Deleted secret {0} ({1}) during rollback."
.format(secret.name, old_ref))
except Exception:
LOG.warning(_LW(
"Failed to delete {0} ({1}) during rollback. This "
"is probably not a problem."
).format(secret.name, old_ref))
LOG.warning(
"Failed to delete {0} ({1}) during rollback. "
"This is probably not a problem."
.format(secret.name, old_ref))
with excutils.save_and_reraise_exception():
LOG.exception(_LE("Error storing certificate data"))
LOG.exception("Error storing certificate data")
@staticmethod
def get_cert(cert_ref, service_name='Magnum', resource_ref=None,
@ -170,9 +165,9 @@ class CertManager(cert_manager.CertManager):
"""
connection = get_admin_clients().barbican()
LOG.info(_LI(
LOG.info(
"Loading certificate container {0} from Barbican."
).format(cert_ref))
.format(cert_ref))
try:
if check_only:
cert_container = connection.containers.get(
@ -187,7 +182,7 @@ class CertManager(cert_manager.CertManager):
return Cert(cert_container)
except barbican_exc.HTTPClientError:
with excutils.save_and_reraise_exception():
LOG.exception(_LE("Error getting {0}").format(cert_ref))
LOG.exception("Error getting {0}".format(cert_ref))
@staticmethod
def delete_cert(cert_ref, service_name='Magnum', resource_ref=None,
@ -199,9 +194,9 @@ class CertManager(cert_manager.CertManager):
"""
connection = get_admin_clients().barbican()
LOG.info(_LI(
LOG.info(
"Recursively deleting certificate container {0} from Barbican."
).format(cert_ref))
.format(cert_ref))
try:
certificate_container = connection.containers.get(cert_ref)
certificate_container.certificate.delete()
@ -213,6 +208,6 @@ class CertManager(cert_manager.CertManager):
certificate_container.delete()
except barbican_exc.HTTPClientError:
with excutils.save_and_reraise_exception():
LOG.exception(_LE(
LOG.exception(
"Error recursively deleting certificate container {0}"
).format(cert_ref))
.format(cert_ref))

View File

@ -22,8 +22,6 @@ from magnum.common.cert_manager import cert_manager
from magnum.common import exception
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LE
from magnum.i18n import _LW
LOG = logging.getLogger(__name__)
@ -77,10 +75,10 @@ class CertManager(cert_manager.CertManager):
cert_ref = str(uuid.uuid4())
filename_base = os.path.join(CONF.certificates.storage_path, cert_ref)
LOG.warning(_LW(
LOG.warning(
"Storing certificate data on the local filesystem. "
"CertManager type 'local' should be used for testing purpose."
))
)
try:
filename_certificate = "{0}.crt".format(filename_base)
with open(filename_certificate, 'w') as cert_file:
@ -100,7 +98,7 @@ class CertManager(cert_manager.CertManager):
with open(filename_pkp, 'w') as pass_file:
pass_file.write(private_key_passphrase)
except IOError as ioe:
LOG.error(_LE("Failed to store certificate."))
LOG.error("Failed to store certificate.")
raise exception.CertificateStorageException(msg=str(ioe))
return cert_ref
@ -115,10 +113,10 @@ class CertManager(cert_manager.CertManager):
representation of the certificate data
:raises CertificateStorageException: if certificate retrieval fails
"""
LOG.warning(_LW(
LOG.warning(
"Loading certificate {0} from the local filesystem. "
"CertManager type 'local' should be used for testing purpose."
).format(cert_ref))
.format(cert_ref))
filename_base = os.path.join(CONF.certificates.storage_path, cert_ref)
@ -133,9 +131,9 @@ class CertManager(cert_manager.CertManager):
with open(filename_certificate, 'r') as cert_file:
cert_data['certificate'] = cert_file.read()
except IOError:
LOG.error(_LE(
LOG.error(
"Failed to read certificate for {0}."
).format(cert_ref))
.format(cert_ref))
raise exception.CertificateStorageException(
msg=_("Certificate could not be read.")
)
@ -143,9 +141,9 @@ class CertManager(cert_manager.CertManager):
with open(filename_private_key, 'r') as key_file:
cert_data['private_key'] = key_file.read()
except IOError:
LOG.error(_LE(
LOG.error(
"Failed to read private key for {0}."
).format(cert_ref))
.format(cert_ref))
raise exception.CertificateStorageException(
msg=_("Private Key could not be read.")
)
@ -155,7 +153,7 @@ class CertManager(cert_manager.CertManager):
with open(filename_intermediates, 'r') as int_file:
cert_data['intermediates'] = int_file.read()
except IOError as ioe:
LOG.error(_LE("Failed to read certificate."))
LOG.error("Failed to read certificate.")
raise exception.CertificateStorageException(msg=str(ioe))
try:
@ -163,7 +161,7 @@ class CertManager(cert_manager.CertManager):
with open(filename_pkp, 'r') as pass_file:
cert_data['private_key_passphrase'] = pass_file.read()
except IOError as ioe:
LOG.error(_LE("Failed to read certificate."))
LOG.error("Failed to read certificate.")
raise exception.CertificateStorageException(msg=str(ioe))
return Cert(**cert_data)
@ -176,10 +174,10 @@ class CertManager(cert_manager.CertManager):
:raises CertificateStorageException: if certificate deletion fails
"""
LOG.warning(_LW(
LOG.warning(
"Deleting certificate {0} from the local filesystem. "
"CertManager type 'local' should be used for testing purpose."
).format(cert_ref))
.format(cert_ref))
filename_base = os.path.join(CONF.certificates.storage_path, cert_ref)
@ -196,7 +194,7 @@ class CertManager(cert_manager.CertManager):
if path.isfile(filename_pkp):
os.remove(filename_pkp)
except IOError as ioe:
LOG.error(_LE(
LOG.error(
"Failed to delete certificate {0}."
).format(cert_ref))
.format(cert_ref))
raise exception.CertificateStorageException(msg=str(ioe))

View File

@ -23,7 +23,6 @@ from oslo_log import log as logging
from magnum.common import exception
from magnum.common import keystone
import magnum.conf
from magnum.i18n import _LW
CONF = magnum.conf.CONF
LOG = logging.getLogger(__name__)
@ -55,8 +54,8 @@ class OpenStackClients(object):
url = self.url_for(service_type='container',
interface=endpoint_type,
region_name=region_name)
LOG.warning(_LW('Service type "container" is deprecated and will '
'be removed in a subsequent release'))
LOG.warning('Service type "container" is deprecated and will '
'be removed in a subsequent release')
return url
def cinder_region_name(self):

View File

@ -28,7 +28,6 @@ import six
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LE
LOG = logging.getLogger(__name__)
@ -92,8 +91,8 @@ class MagnumException(Exception):
except Exception:
# kwargs doesn't match a variable in the message
# log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation, '
'kwargs: %s') % kwargs)
LOG.exception('Exception in string format operation, '
'kwargs: %s' % kwargs)
try:
if CONF.fatal_exception_format_errors:
raise

View File

@ -23,8 +23,6 @@ from magnum.common import exception
import magnum.conf
from magnum.conf import keystone as ksconf
from magnum.i18n import _
from magnum.i18n import _LE
from magnum.i18n import _LW
CONF = magnum.conf.CONF
LOG = logging.getLogger(__name__)
@ -92,8 +90,8 @@ class KeystoneClientV3(object):
except ka_exception.MissingRequiredOptions:
auth = self._get_legacy_auth()
else:
msg = _LE('Keystone API connection failed: no password, '
'trust_id or token found.')
msg = ('Keystone API connection failed: no password, '
'trust_id or token found.')
LOG.error(msg)
raise exception.AuthorizationFailure(client='keystone',
message='reason %s' % msg)
@ -101,11 +99,11 @@ class KeystoneClientV3(object):
return auth
def _get_legacy_auth(self):
LOG.warning(_LW('Auth plugin and its options for service user '
'must be provided in [%(new)s] section. '
'Using values from [%(old)s] section is '
'deprecated.'), {'new': ksconf.CFG_GROUP,
'old': ksconf.CFG_LEGACY_GROUP})
LOG.warning('Auth plugin and its options for service user '
'must be provided in [%(new)s] section. '
'Using values from [%(old)s] section is '
'deprecated.' % {'new': ksconf.CFG_GROUP,
'old': ksconf.CFG_LEGACY_GROUP})
conf = getattr(CONF, ksconf.CFG_LEGACY_GROUP)
@ -182,7 +180,7 @@ class KeystoneClientV3(object):
self.domain_admin_session
)
except kc_exception.Unauthorized:
msg = _LE("Keystone client authentication failed")
msg = "Keystone client authentication failed"
LOG.error(msg)
raise exception.AuthorizationFailure(client='keystone',
message='reason: %s' %
@ -211,7 +209,7 @@ class KeystoneClientV3(object):
delegation_depth=0,
role_names=roles)
except Exception:
LOG.exception(_LE('Failed to create trust'))
LOG.exception('Failed to create trust')
raise exception.TrustCreateFailed(
trustee_user_id=trustee_user)
return trust
@ -244,7 +242,7 @@ class KeystoneClientV3(object):
except kc_exception.NotFound:
pass
except Exception:
LOG.exception(_LE('Failed to delete trust'))
LOG.exception('Failed to delete trust')
raise exception.TrustDeleteFailed(trust_id=cluster.trust_id)
def create_trustee(self, username, password):
@ -255,7 +253,7 @@ class KeystoneClientV3(object):
password=password,
domain=domain_id)
except Exception:
LOG.exception(_LE('Failed to create trustee'))
LOG.exception('Failed to create trustee')
raise exception.TrusteeCreateFailed(username=username,
domain_id=domain_id)
return user
@ -266,7 +264,7 @@ class KeystoneClientV3(object):
except kc_exception.NotFound:
pass
except Exception:
LOG.exception(_LE('Failed to delete trustee'))
LOG.exception('Failed to delete trustee')
raise exception.TrusteeDeleteFailed(trustee_id=trustee_id)
def get_validate_region_name(self, region_name):
@ -280,7 +278,7 @@ class KeystoneClientV3(object):
except kc_exception.NotFound:
pass
except Exception:
LOG.exception(_LE('Failed to list regions'))
LOG.exception('Failed to list regions')
raise exception.RegionsListFailed()
region_list = []
for region in regions:

View File

@ -23,7 +23,6 @@ import webob.dec
from magnum.common import context
import magnum.conf
from magnum.i18n import _LI
profiler = importutils.try_import("osprofiler.profiler")
profiler_initializer = importutils.try_import("osprofiler.initializer")
@ -64,7 +63,7 @@ def setup(binary, host):
project="magnum",
service=binary,
host=host)
LOG.info(_LI("OSprofiler is enabled."))
LOG.info("OSprofiler is enabled.")
def trace_cls(name, **kwargs):

View File

@ -21,8 +21,6 @@ from six.moves import urllib
from magnum.common import exception
import magnum.conf
from magnum.i18n import _
from magnum.i18n import _LE
from magnum.i18n import _LI
CONF = magnum.conf.CONF
LOG = logging.getLogger(__name__)
@ -40,7 +38,7 @@ def get(url, allowed_schemes=('http', 'https')):
the allowed_schemes argument.
Raise an IOError if getting the data fails.
"""
LOG.info(_LI('Fetching data from %s'), url)
LOG.info('Fetching data from %s' % url)
components = urllib.parse.urlparse(url)
@ -70,8 +68,8 @@ def get(url, allowed_schemes=('http', 'https')):
for chunk in reader:
result += chunk
if len(result) > CONF.max_manifest_size:
raise URLFetchError(_LE("Manifest exceeds maximum allowed"
"size (%s bytes)") %
raise URLFetchError("Manifest exceeds maximum allowed"
"size (%s bytes)" %
CONF.max_manifest_size)
return result

View File

@ -32,8 +32,6 @@ import six
from magnum.common import exception
import magnum.conf
from magnum.i18n import _LE
from magnum.i18n import _LW
CONF = magnum.conf.CONF
LOG = logging.getLogger(__name__)
@ -87,10 +85,10 @@ def execute(*cmd, **kwargs):
if kwargs.get('run_as_root') and 'root_helper' not in kwargs:
kwargs['root_helper'] = _get_root_helper()
result = processutils.execute(*cmd, **kwargs)
LOG.debug('Execution completed, command line is "%s"',
LOG.debug('Execution completed, command line is "%s"' %
' '.join(map(str, cmd)))
LOG.debug('Command stdout is: "%s"', result[0])
LOG.debug('Command stderr is: "%s"', result[1])
LOG.debug('Command stdout is: "%s"' % result[0])
LOG.debug('Command stderr is: "%s"' % result[1])
return result
@ -127,7 +125,7 @@ def tempdir(**kwargs):
try:
shutil.rmtree(tmpdir)
except OSError as e:
LOG.error(_LE('Could not remove tmpdir: %s'), e)
LOG.error('Could not remove tmpdir: %s' % e)
def rmtree_without_raise(path):
@ -135,7 +133,7 @@ def rmtree_without_raise(path):
if os.path.isdir(path):
shutil.rmtree(path)
except OSError as e:
LOG.warning(_LW("Failed to remove dir %(path)s, error: %(e)s"),
LOG.warning("Failed to remove dir %(path)s, error: %(e)s" %
{'path': path, 'e': e})
@ -148,10 +146,9 @@ def safe_rstrip(value, chars=None):
"""
if not isinstance(value, six.string_types):
LOG.warning(_LW(
"Failed to remove trailing character. Returning original object. "
"Supplied object is not a string: %s,"
), value)
LOG.warning("Failed to remove trailing character. "
"Returning original object. "
"Supplied object is not a string: %s," % value)
return value
return value.rstrip(chars) or value

View File

@ -26,7 +26,6 @@ from oslo_log import log as logging
from magnum.common import exception
from magnum.common.x509 import validator
import magnum.conf
from magnum.i18n import _LE
LOG = logging.getLogger(__name__)
@ -189,7 +188,7 @@ def sign(csr, issuer_name, ca_key, ca_key_password=None,
try:
csr = x509.load_pem_x509_csr(csr, backend=default_backend())
except ValueError:
LOG.exception(_LE("Received invalid csr {0}.").format(csr))
LOG.exception("Received invalid csr {0}.".format(csr))
raise exception.InvalidCsr(csr=csr)
term_of_validity = CONF.x509.term_of_validity

View File

@ -27,7 +27,6 @@ from magnum.conductor import utils as conductor_utils
import magnum.conf
from magnum.drivers.common import driver
from magnum.i18n import _
from magnum.i18n import _LI
from magnum import objects
from magnum.objects import fields
@ -151,15 +150,15 @@ class Handler(object):
cluster.status = fields.ClusterStatus.DELETE_IN_PROGRESS
cluster.status_reason = None
except exc.HTTPNotFound:
LOG.info(_LI('The cluster %s was not found during cluster'
' deletion.'), cluster.id)
LOG.info('The cluster %s was not found during cluster'
' deletion.' % cluster.id)
try:
trust_manager.delete_trustee_and_trust(osc, context, cluster)
cert_manager.delete_certificates_from_cluster(cluster,
context=context)
cluster.destroy()
except exception.ClusterNotFound:
LOG.info(_LI('The cluster %s has been deleted by others.'),
LOG.info('The cluster %s has been deleted by others.' %
uuid)
conductor_utils.notify_about_cluster_operation(
context, taxonomy.ACTION_DELETE, taxonomy.OUTCOME_SUCCESS)

View File

@ -21,8 +21,6 @@ from magnum.common import cert_manager
from magnum.common import exception
from magnum.common import short_id
from magnum.common.x509 import operations as x509
from magnum.i18n import _LE
from magnum.i18n import _LW
CONDUCTOR_CLIENT_NAME = six.u('Magnum-Conductor')
@ -45,7 +43,7 @@ def _generate_ca_cert(issuer_name, context=None):
name=issuer_name,
context=context,
)
LOG.debug('CA cert is created: %s', ca_cert_ref)
LOG.debug('CA cert is created: %s' % ca_cert_ref)
return ca_cert_ref, ca_cert, ca_password
@ -72,7 +70,7 @@ def _generate_client_cert(issuer_name, ca_cert, ca_password, context=None):
name=CONDUCTOR_CLIENT_NAME,
context=context
)
LOG.debug('Magnum client cert is created: %s', magnum_cert_ref)
LOG.debug('Magnum client cert is created: %s' % magnum_cert_ref)
return magnum_cert_ref
@ -94,7 +92,7 @@ def generate_certificates_to_cluster(cluster, context=None):
try:
issuer_name = _get_issuer_name(cluster)
LOG.debug('Start to generate certificates: %s', issuer_name)
LOG.debug('Start to generate certificates: %s' % issuer_name)
ca_cert_ref, ca_cert, ca_password = _generate_ca_cert(issuer_name,
context=context)
@ -106,7 +104,7 @@ def generate_certificates_to_cluster(cluster, context=None):
cluster.ca_cert_ref = ca_cert_ref
cluster.magnum_cert_ref = magnum_cert_ref
except Exception:
LOG.exception(_LE('Failed to generate certificates for Cluster: %s'),
LOG.exception('Failed to generate certificates for Cluster: %s' %
cluster.uuid)
raise exception.CertificatesToClusterFailed(cluster_uuid=cluster.uuid)
@ -176,5 +174,5 @@ def delete_certificates_from_cluster(cluster, context=None):
cert_manager.get_backend().CertManager.delete_cert(
cert_ref, resource_ref=cluster.uuid, context=context)
except Exception:
LOG.warning(_LW("Deleting certs is failed for Cluster %s"),
LOG.warning("Deleting certs is failed for Cluster %s" %
cluster.uuid)

View File

@ -14,7 +14,6 @@ from oslo_log import log as logging
from magnum.common import exception
from magnum.common import utils
from magnum.i18n import _LE
LOG = logging.getLogger(__name__)
@ -38,7 +37,7 @@ def create_trustee_and_trust(osc, cluster):
except Exception:
LOG.exception(
_LE('Failed to create trustee and trust for Cluster: %s'),
'Failed to create trustee and trust for Cluster: %s' %
cluster.uuid)
raise exception.TrusteeOrTrustToClusterFailed(
cluster_uuid=cluster.uuid)

View File

@ -20,7 +20,6 @@ from kubernetes.client.apis import core_v1_api
from oslo_log import log as logging
from magnum.conductor.handlers.common.cert_manager import create_client_files
from magnum.i18n import _LE
LOG = logging.getLogger(__name__)
@ -38,7 +37,7 @@ class K8sAPI(core_v1_api.CoreV1Api):
tmp.write(content)
tmp.flush()
except Exception as err:
LOG.error(_LE("Error while creating temp file: %s"), err)
LOG.error("Error while creating temp file: %s" % err)
raise
return tmp

View File

@ -18,8 +18,6 @@ from oslo_log import log as logging
from magnum.common import exception
from magnum.drivers.common.driver import Driver
from magnum.i18n import _
from magnum.i18n import _LI
from magnum.i18n import _LW
from magnum import objects
@ -30,9 +28,9 @@ def get_scale_manager(context, osclient, cluster):
cluster_driver = Driver.get_driver_for_cluster(context, cluster)
manager = cluster_driver.get_scale_manager(context, osclient, cluster)
if not manager:
LOG.warning(_LW(
LOG.warning(
"Currently only kubernetes and mesos cluster scale manager "
"are available"))
"are available")
return manager
@ -66,16 +64,16 @@ class ScaleManager(object):
num_of_removal = self._get_num_of_removal()
if len(hosts_no_container) < num_of_removal:
LOG.warning(_LW(
LOG.warning(
"About to remove %(num_removal)d nodes, which is larger than "
"the number of empty nodes (%(num_empty)d). %(num_non_empty)d "
"non-empty nodes will be removed."), {
"non-empty nodes will be removed." % {
'num_removal': num_of_removal,
'num_empty': len(hosts_no_container),
'num_non_empty': num_of_removal - len(hosts_no_container)})
hosts_to_remove = hosts_no_container[0:num_of_removal]
LOG.info(_LI('Require removal of hosts: %s'), hosts_to_remove)
LOG.info('Require removal of hosts: %s' % hosts_to_remove)
return hosts_to_remove

View File

@ -31,7 +31,6 @@ from sqlalchemy import Text
from sqlalchemy.types import TypeDecorator, TEXT
import magnum.conf
from magnum.i18n import _LE
CONF = magnum.conf.CONF
@ -55,11 +54,11 @@ class JsonEncodedType(TypeDecorator):
# interface the consistent.
value = self.type()
elif not isinstance(value, self.type):
raise TypeError(_LE("%(class)s supposes to store "
"%(type)s objects, but %(value)s "
"given") % {'class': self.__class__.__name__,
'type': self.type.__name__,
'value': type(value).__name__})
raise TypeError("%(class)s supposes to store "
"%(type)s objects, but %(value)s "
"given" % {'class': self.__class__.__name__,
'type': self.type.__name__,
'value': type(value).__name__})
serialized_value = json.dumps(value)
return serialized_value

View File

@ -30,8 +30,6 @@ from magnum.conductor.handlers.common import trust_manager
from magnum.conductor import utils as conductor_utils
from magnum.drivers.common import driver
from magnum.i18n import _
from magnum.i18n import _LE
from magnum.i18n import _LI
from magnum.objects import fields
@ -192,7 +190,7 @@ class HeatPoller(object):
self._cluster_failed(stack)
def _delete_complete(self):
LOG.info(_LI('Cluster has been deleted, stack_id: %s')
LOG.info('Cluster has been deleted, stack_id: %s'
% self.cluster.stack_id)
try:
trust_manager.delete_trustee_and_trust(self.openstack_client,
@ -201,7 +199,7 @@ class HeatPoller(object):
cert_manager.delete_certificates_from_cluster(self.cluster,
context=self.context)
except exception.ClusterNotFound:
LOG.info(_LI('The cluster %s has been deleted by others.')
LOG.info('The cluster %s has been deleted by others.'
% self.cluster.uuid)
def _sync_cluster_status(self, stack):
@ -233,9 +231,9 @@ class HeatPoller(object):
self._sync_cluster_status(stack)
def _cluster_failed(self, stack):
LOG.error(_LE('Cluster error, stack status: %(cluster_status)s, '
'stack_id: %(stack_id)s, '
'reason: %(reason)s') %
LOG.error('Cluster error, stack status: %(cluster_status)s, '
'stack_id: %(stack_id)s, '
'reason: %(reason)s' %
{'cluster_status': stack.stack_status,
'stack_id': self.cluster.stack_id,
'reason': self.cluster.status_reason})
@ -253,8 +251,8 @@ class HeatPoller(object):
self.cluster.status_reason = _("Stack with id %s not found in "
"Heat.") % self.cluster.stack_id
self.cluster.save()
LOG.info(_LI("Cluster with id %(id)s has been set to "
"%(status)s due to stack with id %(sid)s "
"not found in Heat."),
LOG.info("Cluster with id %(id)s has been set to "
"%(status)s due to stack with id %(sid)s "
"not found in Heat." %
{'id': self.cluster.id, 'status': self.cluster.status,
'sid': self.cluster.stack_id})

View File

@ -21,8 +21,6 @@ import six
from magnum.common import clients
from magnum.common import exception
import magnum.conf
from magnum.i18n import _LE
from magnum.i18n import _LW
from requests import exceptions as req_exceptions
@ -102,7 +100,7 @@ class OutputMapping(object):
if output['output_key'] == self.heat_output:
return output['output_value']
LOG.warning(_LW('stack does not have output_key %s'), self.heat_output)
LOG.warning('stack does not have output_key %s' % self.heat_output)
return None
@ -254,8 +252,8 @@ class BaseTemplateDefinition(TemplateDefinition):
extra_params['trust_id'] = cluster.trust_id
else:
missing_setting = ('trust/cluster_user_trust = True')
msg = _LE('This cluster can only be created with %s in '
'magnum.conf')
msg = ('This cluster can only be created with %s in '
'magnum.conf')
raise exception.ConfigInvalid(msg % missing_setting)
else:
extra_params['trust_id'] = ""

View File

@ -17,7 +17,6 @@ from oslo_log import log
from magnum.common import docker_utils
from magnum.conductor import monitors
from magnum.i18n import _LW
LOG = log.getLogger(__name__)
@ -51,8 +50,8 @@ class SwarmMonitor(monitors.MonitorBase):
try:
container = docker.inspect_container(container['Id'])
except Exception as e:
LOG.warning(_LW("Ignore error [%(e)s] when inspecting "
"container %(container_id)s."),
LOG.warning("Ignore error [%(e)s] when inspecting "
"container %(container_id)s." %
{'e': e, 'container_id': container['Id']},
exc_info=True)
containers.append(container)

View File

@ -15,7 +15,7 @@
import re
import pep8
import pep8 # noqa
"""
Guidelines for writing new hacking checks
@ -135,23 +135,6 @@ def assert_true_isinstance(logical_line):
yield (0, "M316: assertTrue(isinstance(a, b)) sentences not allowed")
def validate_log_translations(logical_line, physical_line, filename=None):
if pep8.noqa(physical_line):
return
msg = "M328: LOG.info messages require translations `_LI()`!"
if log_translation_info.match(logical_line):
yield (0, msg)
msg = "M329: LOG.exception messages require translations `_LE()`!"
if log_translation_exception.match(logical_line):
yield (0, msg)
msg = "M330: LOG.warning, LOG.warn messages require translations `_LW()`!"
if log_translation_LW.match(logical_line):
yield (0, msg)
msg = "M321: Log messages require translations!"
if log_translation.match(logical_line):
yield (0, msg)
def assert_equal_in(logical_line):
"""Check for assertEqual(True|False, A in B), assertEqual(A in B, True|False)
@ -242,5 +225,4 @@ def factory(register):
register(dict_constructor_with_list_copy)
register(no_xrange)
register(no_log_warn)
register(validate_log_translations)
register(check_explicit_underscore_import)

View File

@ -25,16 +25,6 @@ _translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# The primary translation function using the well-known name "_"
_ = _translators.primary
# Translators for log levels.
#
# The abbreviated names are meant to reflect the usual use of a short
# name like '_'. The "L" is for "log" and the other letter comes from
# the level.
_LI = _translators.log_info
_LW = _translators.log_warning
_LE = _translators.log_error
_LC = _translators.log_critical
def translate(value, user_locale):
return oslo_i18n.translate(value, user_locale)

View File

@ -28,7 +28,6 @@ from magnum.conductor import monitors
from magnum.conductor import utils as conductor_utils
import magnum.conf
from magnum.drivers.common import driver
from magnum.i18n import _LW
from magnum import objects
@ -135,9 +134,9 @@ class MagnumPeriodicTasks(periodic_task.PeriodicTasks):
lc.start(1, stop_on_exception=True)
except Exception as e:
LOG.warning(_LW(
"Ignore error [%s] when syncing up cluster status."
), e, exc_info=True)
LOG.warning(
"Ignore error [%s] when syncing up cluster status." %
e, exc_info=True)
@periodic_task.periodic_task(run_immediately=True)
@set_context
@ -157,8 +156,8 @@ class MagnumPeriodicTasks(periodic_task.PeriodicTasks):
monitor.pull_data()
except Exception as e:
LOG.warning(
_LW("Skip pulling data from cluster %(cluster)s due to "
"error: %(e)s"),
"Skip pulling data from cluster %(cluster)s due to "
"error: %(e)s" %
{'e': e, 'cluster': cluster.uuid}, exc_info=True)
continue
@ -172,8 +171,8 @@ class MagnumPeriodicTasks(periodic_task.PeriodicTasks):
}
metrics.append(metric)
except Exception as e:
LOG.warning(_LW("Skip adding metric %(name)s due to "
"error: %(e)s"),
LOG.warning("Skip adding metric %(name)s due to "
"error: %(e)s" %
{'e': e, 'name': name}, exc_info=True)
message = dict(metrics=metrics,

View File

@ -13,9 +13,6 @@
from oslo_log import log as logging
from tempest.lib import exceptions
from magnum.i18n import _LE
from magnum.i18n import _LI
from magnum.i18n import _LW
from magnum.tests.functional.api.v1.models import bay_model
from magnum.tests.functional.common import client
from magnum.tests.functional.common import utils
@ -123,9 +120,9 @@ class BayClient(client.MagnumClient):
lambda: self.does_bay_exist(bay_id), 10, 1800)
except Exception:
# In error state. Clean up the bay id if desired
self.LOG.error(_LE('Bay %s entered an exception state.'), bay_id)
self.LOG.error('Bay %s entered an exception state.' % bay_id)
if delete_on_error:
self.LOG.error(_LE('We will attempt to delete bays now.'))
self.LOG.error('We will attempt to delete bays now.')
self.delete_bay(bay_id)
self.wait_for_bay_to_delete(bay_id)
raise
@ -139,35 +136,35 @@ class BayClient(client.MagnumClient):
resp, model = self.get_bay(bay_id)
if model.status in ['CREATED', 'CREATE_COMPLETE',
'ERROR', 'CREATE_FAILED']:
self.LOG.info(_LI('Bay %s succeeded.'), bay_id)
self.LOG.info('Bay %s succeeded.' % bay_id)
return True
else:
return False
except exceptions.NotFound:
self.LOG.warning(_LW('Bay %s is not found.'), bay_id)
self.LOG.warning('Bay %s is not found.' % bay_id)
return False
def does_bay_exist(self, bay_id):
try:
resp, model = self.get_bay(bay_id)
if model.status in ['CREATED', 'CREATE_COMPLETE']:
self.LOG.info(_LI('Bay %s is created.'), bay_id)
self.LOG.info('Bay %s is created.' % bay_id)
return True
elif model.status in ['ERROR', 'CREATE_FAILED']:
self.LOG.error(_LE('Bay %s is in fail state.'), bay_id)
self.LOG.error('Bay %s is in fail state.' % bay_id)
raise exceptions.ServerFault(
"Got into an error condition: %s for %s" %
(model.status, bay_id))
else:
return False
except exceptions.NotFound:
self.LOG.warning(_LW('Bay %s is not found.'), bay_id)
self.LOG.warning('Bay %s is not found.' % bay_id)
return False
def does_bay_not_exist(self, bay_id):
try:
self.get_bay(bay_id)
except exceptions.NotFound:
self.LOG.warning(_LW('Bay %s is not found.'), bay_id)
self.LOG.warning('Bay %s is not found.' % bay_id)
return True
return False

View File

@ -13,9 +13,6 @@
from oslo_log import log as logging
from tempest.lib import exceptions
from magnum.i18n import _LE
from magnum.i18n import _LI
from magnum.i18n import _LW
from magnum.tests.functional.api.v1.models import cluster_id_model
from magnum.tests.functional.api.v1.models import cluster_model
from magnum.tests.functional.common import client
@ -124,10 +121,10 @@ class ClusterClient(client.MagnumClient):
lambda: self.does_cluster_exist(cluster_id), 10, 1800)
except Exception:
# In error state. Clean up the cluster id if desired
self.LOG.error(_LE('Cluster %s entered an exception state.'),
self.LOG.error('Cluster %s entered an exception state.' %
cluster_id)
if delete_on_error:
self.LOG.error(_LE('We will attempt to delete clusters now.'))
self.LOG.error('We will attempt to delete clusters now.')
self.delete_cluster(cluster_id)
self.wait_for_cluster_to_delete(cluster_id)
raise
@ -141,22 +138,22 @@ class ClusterClient(client.MagnumClient):
resp, model = self.get_cluster(cluster_id)
if model.status in ['CREATED', 'CREATE_COMPLETE',
'ERROR', 'CREATE_FAILED']:
self.LOG.info(_LI('Cluster %s succeeded.'), cluster_id)
self.LOG.info('Cluster %s succeeded.' % cluster_id)
return True
else:
return False
except exceptions.NotFound:
self.LOG.warning(_LW('Cluster %s is not found.'), cluster_id)
self.LOG.warning('Cluster %s is not found.' % cluster_id)
return False
def does_cluster_exist(self, cluster_id):
try:
resp, model = self.get_cluster(cluster_id)
if model.status in ['CREATED', 'CREATE_COMPLETE']:
self.LOG.info(_LI('Cluster %s is created.'), cluster_id)
self.LOG.info('Cluster %s is created.' % cluster_id)
return True
elif model.status in ['ERROR', 'CREATE_FAILED']:
self.LOG.error(_LE('Cluster %s is in fail state.'),
self.LOG.error('Cluster %s is in fail state.' %
cluster_id)
raise exceptions.ServerFault(
"Got into an error condition: %s for %s" %
@ -164,13 +161,13 @@ class ClusterClient(client.MagnumClient):
else:
return False
except exceptions.NotFound:
self.LOG.warning(_LW('Cluster %s is not found.'), cluster_id)
self.LOG.warning('Cluster %s is not found.' % cluster_id)
return False
def does_cluster_not_exist(self, cluster_id):
try:
self.get_cluster(cluster_id)
except exceptions.NotFound:
self.LOG.warning(_LW('Cluster %s is not found.'), cluster_id)
self.LOG.warning('Cluster %s is not found.' % cluster_id)
return True
return False

View File

@ -17,8 +17,6 @@ import subprocess
from tempest.lib import base
import magnum
from magnum.i18n import _LE
from magnum.i18n import _LI
COPY_LOG_HELPER = "magnum/tests/contrib/copy_instance_logs.sh"
@ -46,10 +44,10 @@ class BaseMagnumTest(base.BaseTestCase):
"""
def int_copy_logs(exec_info):
try:
cls.LOG.info(_LI("Copying logs..."))
cls.LOG.info("Copying logs...")
fn = exec_info[2].tb_frame.f_locals['fn']
func_name = fn.im_self._get_test_method().__name__
msg = (_LE("Failed to copy logs for cluster"))
msg = ("Failed to copy logs for cluster")
nodes_addresses = get_nodes_fn()
master_nodes = nodes_addresses[0]
@ -63,7 +61,7 @@ class BaseMagnumTest(base.BaseTestCase):
if not nodes_address:
return
msg = _LI("copy logs from : %s") % ','.join(nodes_address)
msg = "copy logs from : %s" % ','.join(nodes_address)
cls.LOG.info(msg)
log_name = prefix + "-" + func_name
for node_address in nodes_address:
@ -80,9 +78,9 @@ class BaseMagnumTest(base.BaseTestCase):
except Exception:
cls.LOG.error(msg)
msg = (
_LE("failed to copy from %(node_address)s "
"to %(base_path)s%(log_name)s-"
"%(node_address)s") %
"failed to copy from %(node_address)s "
"to %(base_path)s%(log_name)s-"
"%(node_address)s" %
{'node_address': node_address,
'base_path': "/opt/stack/logs/cluster-nodes/",
'log_name': log_name})

View File

@ -33,7 +33,6 @@ from kubernetes.client.apis import core_v1_api
from magnum.common.utils import rmtree_without_raise
import magnum.conf
from magnum.i18n import _LI
from magnum.tests.functional.common import base
from magnum.tests.functional.common import utils
from magnumclient.common.apiclient import exceptions
@ -301,11 +300,11 @@ extendedKeyUsage = clientAuth
def _get_nodes(self):
nodes = self._get_nodes_from_cluster()
if not [x for x in nodes if x]:
self.LOG.info(_LI("the list of nodes from cluster is empty"))
self.LOG.info("the list of nodes from cluster is empty")
nodes = self._get_nodes_from_stack()
if not [x for x in nodes if x]:
self.LOG.info(_LI("the list of nodes from stack is empty"))
self.LOG.info(_LI("Nodes are: %s"), nodes)
self.LOG.info("the list of nodes from stack is empty")
self.LOG.info("Nodes are: %s" % nodes)
return nodes
def _get_nodes_from_cluster(self):
@ -411,10 +410,10 @@ class BaseK8sTest(ClusterTest):
def _is_api_ready(self):
try:
self.k8s_api.list_node()
self.LOG.info(_LI("API is ready."))
self.LOG.info("API is ready.")
return True
except Exception:
self.LOG.info(_LI("API is not ready yet."))
self.LOG.info("API is not ready yet.")
return False
def test_pod_apis(self):

View File

@ -17,7 +17,6 @@ from requests import exceptions as req_exceptions
from magnum.common import docker_utils
import magnum.conf
from magnum.i18n import _LI
from magnum.tests.functional.python_client_base import ClusterTest
@ -96,15 +95,15 @@ class TestSwarmAPIs(ClusterTest):
# need to investigate the cause of this issue. See bug #1583337.
for i in range(150):
try:
self.LOG.info(_LI("Calling function ") + func.__name__)
self.LOG.info("Calling function " + func.__name__)
return func(*args, **kwargs)
except req_exceptions.ConnectionError:
self.LOG.info(_LI("Connection aborted on calling Swarm API. "
"Will retry in 2 seconds."))
self.LOG.info("Connection aborted on calling Swarm API. "
"Will retry in 2 seconds.")
except errors.APIError as e:
if e.response.status_code != 500:
raise
self.LOG.info(_LI("Internal Server Error: ") + str(e))
self.LOG.info("Internal Server Error: " + str(e))
time.sleep(2)
raise Exception("Cannot connect to Swarm API.")

View File

@ -215,28 +215,6 @@ class HackingTestCase(base.TestCase):
"""
self._assert_has_no_errors(code, check)
def test_log_translations(self):
logs = ['audit', 'error', 'info', 'warning', 'critical', 'warn',
'exception']
levels = ['_LI', '_LW', '_LE', '_LC']
debug = "LOG.debug('OK')"
self.assertEqual(
0, len(list(checks.validate_log_translations(debug, debug))))
for log in logs:
bad = 'LOG.%s("Bad")' % log
self.assertEqual(
1, len(list(checks.validate_log_translations(bad, bad))))
ok = "LOG.%s('OK') # noqa" % log
self.assertEqual(
0, len(list(checks.validate_log_translations(ok, ok))))
ok = "LOG.%s(variable)" % log
self.assertEqual(
0, len(list(checks.validate_log_translations(ok, ok))))
for level in levels:
ok = "LOG.%s(%s('OK'))" % (log, level)
self.assertEqual(
0, len(list(checks.validate_log_translations(ok, ok))))
def test_use_timeunitls_utcow(self):
errors = [(1, 0, "M310")]
check = checks.use_timeutils_utcnow