Remove log translations

Log messages are no longer being translated. This removes all use of
the _LC, _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: I4c96f3590d46205c45d12ee4ead8c208e11c52c5
This commit is contained in:
lcsong 2017-03-21 13:14:49 +08:00
parent 2525205c24
commit c9f7a3c56d
21 changed files with 128 additions and 217 deletions

View File

@ -26,9 +26,6 @@ Masakari Specific Commandments
- [M309] Don't import translation in tests - [M309] Don't import translation in tests
- [M310] Setting CONF.* attributes directly in tests is forbidden. Use - [M310] Setting CONF.* attributes directly in tests is forbidden. Use
self.flags(option=value) instead. self.flags(option=value) instead.
- [M311] Validate that LOG.info messages use _LI.
- [M312] Validate that LOG.exception messages use _LE.
- [M313] Validate that LOG.warning and LOG.warn messages use _LW.
- [M314] Log messages require translations! - [M314] Log messages require translations!
- [M315] Method's default argument shouldn't be mutable - [M315] Method's default argument shouldn't be mutable
- [M316] Ensure that the _() function is explicitly imported to ensure proper translations. - [M316] Ensure that the _() function is explicitly imported to ensure proper translations.

View File

@ -25,7 +25,6 @@ import webob.exc
from masakari.api.openstack import wsgi from masakari.api.openstack import wsgi
import masakari.conf import masakari.conf
from masakari.i18n import _LE, _LI, _LW
from masakari.i18n import translate from masakari.i18n import translate
from masakari import utils from masakari import utils
from masakari import wsgi as base_wsgi from masakari import wsgi as base_wsgi
@ -49,7 +48,7 @@ class FaultWrapper(base_wsgi.Middleware):
status, webob.exc.HTTPInternalServerError)() status, webob.exc.HTTPInternalServerError)()
def _error(self, inner, req): def _error(self, inner, req):
LOG.exception(_LE("Caught error: %s"), six.text_type(inner)) LOG.exception("Caught error: %s", six.text_type(inner))
safe = getattr(inner, 'safe', False) safe = getattr(inner, 'safe', False)
headers = getattr(inner, 'headers', None) headers = getattr(inner, 'headers', None)
@ -58,7 +57,7 @@ class FaultWrapper(base_wsgi.Middleware):
status = 500 status = 500
msg_dict = dict(url=req.url, status=status) msg_dict = dict(url=req.url, status=status)
LOG.info(_LI("%(url)s returned with HTTP %(status)d"), msg_dict) LOG.info("%(url)s returned with HTTP %(status)d", msg_dict)
outer = self.status_to_type(status) outer = self.status_to_type(status)
if headers: if headers:
outer.headers = headers outer.headers = headers
@ -181,7 +180,7 @@ class APIRouterV1(base_wsgi.Router):
self._register_resources_check_inherits(mapper) self._register_resources_check_inherits(mapper)
self.api_extension_manager.map(self._register_controllers) self.api_extension_manager.map(self._register_controllers)
LOG.info(_LI("Loaded extensions: %s"), LOG.info("Loaded extensions: %s",
sorted(self.loaded_extension_info.get_extensions().keys())) sorted(self.loaded_extension_info.get_extensions().keys()))
super(APIRouterV1, self).__init__(mapper) super(APIRouterV1, self).__init__(mapper)
@ -269,8 +268,8 @@ class APIRouterV1(base_wsgi.Router):
controller = extension.controller controller = extension.controller
if collection not in self.resources: if collection not in self.resources:
LOG.warning(_LW('Extension %(ext_name)s: Cannot extend ' LOG.warning('Extension %(ext_name)s: Cannot extend '
'resource %(collection)s: No such resource'), 'resource %(collection)s: No such resource',
{'ext_name': ext_name, 'collection': collection}) {'ext_name': ext_name, 'collection': collection})
continue continue

View File

@ -25,7 +25,7 @@ import webob.exc
import masakari.api.openstack import masakari.api.openstack
from masakari.api.openstack import wsgi from masakari.api.openstack import wsgi
from masakari import exception from masakari import exception
from masakari.i18n import _, _LE, _LW from masakari.i18n import _
import masakari.policy import masakari.policy
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -176,7 +176,7 @@ class ExtensionManager(object):
try: try:
extension.is_valid() extension.is_valid()
except AttributeError: except AttributeError:
LOG.exception(_LE("Exception loading extension")) LOG.exception("Exception loading extension")
return False return False
return True return True
@ -211,8 +211,8 @@ class ExtensionManager(object):
try: try:
self.load_extension(ext_factory) self.load_extension(ext_factory)
except Exception as exc: except Exception as exc:
LOG.warning(_LW('Failed to load extension %(ext_factory)s: ' LOG.warning('Failed to load extension %(ext_factory)s: '
'%(exc)s'), '%(exc)s',
{'ext_factory': ext_factory, 'exc': exc}) {'ext_factory': ext_factory, 'exc': exc})
@ -282,8 +282,7 @@ def load_standard_extensions(ext_mgr, logger, path, package, ext_list=None):
try: try:
ext_mgr.load_extension(classpath) ext_mgr.load_extension(classpath)
except Exception as exc: except Exception as exc:
logger.warn(_LW('Failed to load extension %(classpath)s: ' logger.warn('Failed to load extension %(classpath)s: %(exc)s',
'%(exc)s'),
{'classpath': classpath, 'exc': exc}) {'classpath': classpath, 'exc': exc})
# Now, let's consider any subdirectories we may have... # Now, let's consider any subdirectories we may have...
@ -305,8 +304,8 @@ def load_standard_extensions(ext_mgr, logger, path, package, ext_list=None):
try: try:
ext(ext_mgr) ext(ext_mgr)
except Exception as exc: except Exception as exc:
logger.warn(_LW('Failed to load extension %(ext_name)s:' logger.warn('Failed to load extension %(ext_name)s:'
'%(exc)s'), '%(exc)s',
{'ext_name': ext_name, 'exc': exc}) {'ext_name': ext_name, 'exc': exc})
# Update the list of directories we'll explore... # Update the list of directories we'll explore...
@ -441,7 +440,7 @@ def expected_errors(errors):
raise raise
elif isinstance(exc, exception.ValidationError): elif isinstance(exc, exception.ValidationError):
raise raise
LOG.exception(_LE("Unexpected exception in API method")) LOG.exception("Unexpected exception in API method")
msg = _('Unexpected API Error. Please report this at ' msg = _('Unexpected API Error. Please report this at '
'http://bugs.launchpad.net/masakari/ and attach the ' 'http://bugs.launchpad.net/masakari/ and attach the '
'Masakari API log if possible.\n%s') % type(exc) 'Masakari API log if possible.\n%s') % type(exc)

View File

@ -19,7 +19,6 @@ import webob.exc
from masakari.api.openstack import extensions from masakari.api.openstack import extensions
from masakari.api.openstack import wsgi from masakari.api.openstack import wsgi
from masakari import exception from masakari import exception
from masakari.i18n import _LE
ALIAS = 'extensions' ALIAS = 'extensions'
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -131,7 +130,7 @@ class LoadedExtensionInfo(object):
try: try:
extension.is_valid() extension.is_valid()
except AttributeError: except AttributeError:
LOG.exception(_LE("Exception loading extension")) LOG.exception("Exception loading extension")
return False return False
return True return True

View File

@ -28,7 +28,7 @@ from masakari.api import api_version_request as api_version
from masakari.api import versioned_method from masakari.api import versioned_method
from masakari import exception from masakari import exception
from masakari import i18n from masakari import i18n
from masakari.i18n import _, _LE, _LI from masakari.i18n import _
from masakari import utils from masakari import utils
from masakari import wsgi from masakari import wsgi
@ -378,14 +378,14 @@ class ResourceExceptionHandler(object):
explanation=ex_value.format_message())) explanation=ex_value.format_message()))
elif isinstance(ex_value, TypeError): elif isinstance(ex_value, TypeError):
exc_info = (ex_type, ex_value, ex_traceback) exc_info = (ex_type, ex_value, ex_traceback)
LOG.error(_LE('Exception handling resource: %s'), ex_value, LOG.error('Exception handling resource: %s', ex_value,
exc_info=exc_info) exc_info=exc_info)
raise Fault(webob.exc.HTTPBadRequest()) raise Fault(webob.exc.HTTPBadRequest())
elif isinstance(ex_value, Fault): elif isinstance(ex_value, Fault):
LOG.info(_LI("Fault thrown: %s"), ex_value) LOG.info("Fault thrown: %s", ex_value)
raise ex_value raise ex_value
elif isinstance(ex_value, webob.exc.HTTPException): elif isinstance(ex_value, webob.exc.HTTPException):
LOG.info(_LI("HTTP exception thrown: %s"), ex_value) LOG.info("HTTP exception thrown: %s", ex_value)
raise Fault(ex_value) raise Fault(ex_value)
# We didn't handle the exception # We didn't handle the exception

View File

@ -25,7 +25,6 @@ import six
import masakari.conf import masakari.conf
from masakari import config from masakari import config
from masakari import exception from masakari import exception
from masakari.i18n import _LE, _LW
from masakari import objects from masakari import objects
from masakari import service from masakari import service
@ -46,13 +45,12 @@ def main():
launcher.launch_service(server, workers=server.workers or 1) launcher.launch_service(server, workers=server.workers or 1)
started += 1 started += 1
except exception.PasteAppNotFound as ex: except exception.PasteAppNotFound as ex:
log.warning( log.warning("%s. ``enabled_apis`` includes bad values. "
_LW("%s. ``enabled_apis`` includes bad values. " "Fix to remove this warning.", six.text_type(ex))
"Fix to remove this warning."), six.text_type(ex))
if started == 0: if started == 0:
log.error(_LE('No APIs were started. ' log.error('No APIs were started. '
'Check the enabled_apis config option.')) 'Check the enabled_apis config option.')
sys.exit(1) sys.exit(1)
launcher.wait() launcher.wait()

View File

@ -33,7 +33,6 @@ import six
from masakari import conf from masakari import conf
from masakari import context as ctx from masakari import context as ctx
from masakari import exception from masakari import exception
from masakari.i18n import _LI
CONF = conf.CONF CONF = conf.CONF
CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token') CONF.import_group('keystone_authtoken', 'keystonemiddleware.auth_token')
@ -136,7 +135,7 @@ class API(object):
'all_tenants': True 'all_tenants': True
} }
nova = novaclient(context) nova = novaclient(context)
LOG.info(_LI('Fetch Server list on %s'), host) LOG.info('Fetch Server list on %s', host)
return nova.servers.list(detailed=True, search_opts=opts) return nova.servers.list(detailed=True, search_opts=opts)
@translate_nova_exception @translate_nova_exception
@ -146,14 +145,14 @@ class API(object):
nova = novaclient(context) nova = novaclient(context)
if not enable: if not enable:
LOG.info(_LI('Disable nova-compute on %s'), host_name) LOG.info('Disable nova-compute on %s', host_name)
if reason: if reason:
nova.services.disable_log_reason(host_name, 'nova-compute', nova.services.disable_log_reason(host_name, 'nova-compute',
reason) reason)
else: else:
nova.services.disable(host_name, 'nova-compute') nova.services.disable(host_name, 'nova-compute')
else: else:
LOG.info(_LI('Enable nova-compute on %s'), host_name) LOG.info('Enable nova-compute on %s', host_name)
nova.services.enable(host_name, 'nova-compute') nova.services.enable(host_name, 'nova-compute')
@translate_nova_exception @translate_nova_exception
@ -167,8 +166,8 @@ class API(object):
def evacuate_instance(self, context, uuid, target=None, def evacuate_instance(self, context, uuid, target=None,
on_shared_storage=True): on_shared_storage=True):
"""Evacuate an instance from failed host to specified host.""" """Evacuate an instance from failed host to specified host."""
msg = (_LI('Call evacuate command for instance %(uuid)s on host ' msg = ('Call evacuate command for instance %(uuid)s on host '
'%(target)s')) '%(target)s')
LOG.info(msg, {'uuid': uuid, 'target': target}) LOG.info(msg, {'uuid': uuid, 'target': target})
nova = novaclient(context) nova = novaclient(context)
nova.servers.evacuate(uuid, host=target, nova.servers.evacuate(uuid, host=target,
@ -177,8 +176,8 @@ class API(object):
@translate_nova_exception @translate_nova_exception
def reset_instance_state(self, context, uuid, status='error'): def reset_instance_state(self, context, uuid, status='error'):
"""Reset the state of an instance to active or error.""" """Reset the state of an instance to active or error."""
msg = (_LI('Call reset state command on instance %(uuid)s to ' msg = ('Call reset state command on instance %(uuid)s to '
'status: %(status)s.')) 'status: %(status)s.')
LOG.info(msg, {'uuid': uuid, 'status': status}) LOG.info(msg, {'uuid': uuid, 'status': status})
nova = novaclient(context) nova = novaclient(context)
nova.servers.reset_state(uuid, status) nova.servers.reset_state(uuid, status)
@ -187,7 +186,7 @@ class API(object):
def get_server(self, context, uuid): def get_server(self, context, uuid):
"""Get a server.""" """Get a server."""
nova = novaclient(context) nova = novaclient(context)
msg = (_LI('Call get server command for instance %(uuid)s')) msg = ('Call get server command for instance %(uuid)s')
LOG.info(msg, {'uuid': uuid}) LOG.info(msg, {'uuid': uuid})
return nova.servers.get(uuid) return nova.servers.get(uuid)
@ -195,7 +194,7 @@ class API(object):
def stop_server(self, context, uuid): def stop_server(self, context, uuid):
"""Stop a server.""" """Stop a server."""
nova = novaclient(context) nova = novaclient(context)
msg = (_LI('Call stop server command for instance %(uuid)s')) msg = ('Call stop server command for instance %(uuid)s')
LOG.info(msg, {'uuid': uuid}) LOG.info(msg, {'uuid': uuid})
return nova.servers.stop(uuid) return nova.servers.stop(uuid)
@ -203,7 +202,7 @@ class API(object):
def start_server(self, context, uuid): def start_server(self, context, uuid):
"""Start a server.""" """Start a server."""
nova = novaclient(context) nova = novaclient(context)
msg = (_LI('Call start server command for instance %(uuid)s')) msg = ('Call start server command for instance %(uuid)s')
LOG.info(msg, {'uuid': uuid}) LOG.info(msg, {'uuid': uuid})
return nova.servers.start(uuid) return nova.servers.start(uuid)
@ -211,15 +210,14 @@ class API(object):
def get_aggregate_list(self, context): def get_aggregate_list(self, context):
"""Get all aggregate list.""" """Get all aggregate list."""
nova = novaclient(context) nova = novaclient(context)
LOG.info(_LI('Call aggregate-list command to get list of all ' LOG.info('Call aggregate-list command to get list of all aggregates.')
'aggregates.'))
return nova.aggregates.list() return nova.aggregates.list()
@translate_nova_exception @translate_nova_exception
def add_host_to_aggregate(self, context, host, aggregate): def add_host_to_aggregate(self, context, host, aggregate):
"""Add host to given aggregate.""" """Add host to given aggregate."""
nova = novaclient(context) nova = novaclient(context)
msg = _LI("Call add_host command to add host '%(host_name)s' to " msg = ("Call add_host command to add host '%(host_name)s' to "
"aggregate '%(aggregate_name)s'.") "aggregate '%(aggregate_name)s'.")
LOG.info(msg, {'host_name': host, 'aggregate_name': aggregate.name}) LOG.info(msg, {'host_name': host, 'aggregate_name': aggregate.name})
return nova.aggregates.add_host(aggregate.id, host) return nova.aggregates.add_host(aggregate.id, host)

View File

@ -28,7 +28,6 @@ import six
from stevedore import driver from stevedore import driver
import masakari.conf import masakari.conf
from masakari.i18n import _LE, _LI
from masakari import utils from masakari import utils
@ -68,17 +67,16 @@ def load_masakari_driver(masakari_driver=None):
masakari_driver = CONF.notification_driver masakari_driver = CONF.notification_driver
if not masakari_driver: if not masakari_driver:
LOG.error(_LE("Notification driver option required, but not" LOG.error("Notification driver option required, but not specified")
"specified"))
sys.exit(1) sys.exit(1)
LOG.info(_LI("Loading masakari notification driver '%s'"), masakari_driver) LOG.info("Loading masakari notification driver '%s'", masakari_driver)
try: try:
notification_driver = driver.DriverManager('masakari.driver', notification_driver = driver.DriverManager('masakari.driver',
masakari_driver, masakari_driver,
invoke_on_load=True).driver invoke_on_load=True).driver
return utils.check_isinstance(notification_driver, NotificationDriver) return utils.check_isinstance(notification_driver, NotificationDriver)
except ImportError: except ImportError:
LOG.exception(_LE("Failed to load notification driver " LOG.exception("Failed to load notification driver '%s'.",
"'%s'."), masakari_driver) masakari_driver)
sys.exit(1) sys.exit(1)

View File

@ -29,7 +29,7 @@ from masakari.engine.drivers.taskflow import host_failure
from masakari.engine.drivers.taskflow import instance_failure from masakari.engine.drivers.taskflow import instance_failure
from masakari.engine.drivers.taskflow import process_failure from masakari.engine.drivers.taskflow import process_failure
from masakari import exception from masakari import exception
from masakari.i18n import _, _LW from masakari.i18n import _
from masakari.objects import fields from masakari.objects import fields
@ -77,10 +77,10 @@ class TaskFlowDriver(driver.NotificationDriver):
# Caught generic Exception to make sure that any failure # Caught generic Exception to make sure that any failure
# should lead to execute 'reserved_host' recovery workflow. # should lead to execute 'reserved_host' recovery workflow.
msg = _LW("Failed to evacuate all instances from " msg = ("Failed to evacuate all instances from "
"failed_host: '%(failed_host)s' using " "failed_host: '%(failed_host)s' using "
"'%(auto)s' workflow, retrying using " "'%(auto)s' workflow, retrying using "
"'%(reserved_host)s' workflow.") "'%(reserved_host)s' workflow.")
LOG.warning(msg, { LOG.warning(msg, {
'failed_host': process_what['host_name'], 'failed_host': process_what['host_name'],
'auto': fields.FailoverSegmentRecoveryMethod.AUTO, 'auto': fields.FailoverSegmentRecoveryMethod.AUTO,
@ -103,10 +103,10 @@ class TaskFlowDriver(driver.NotificationDriver):
# Caught generic Exception to make sure that any failure # Caught generic Exception to make sure that any failure
# should lead to execute 'auto' recovery workflow. # should lead to execute 'auto' recovery workflow.
msg = _LW("Failed to evacuate all instances from " msg = ("Failed to evacuate all instances from "
"failed_host '%(failed_host)s' using " "failed_host '%(failed_host)s' using "
"'%(reserved_host)s' workflow, retrying using " "'%(reserved_host)s' workflow, retrying using "
"'%(auto)s' workflow") "'%(auto)s' workflow")
LOG.warning(msg, { LOG.warning(msg, {
'failed_host': process_what['host_name'], 'failed_host': process_what['host_name'],
'reserved_host': 'reserved_host':
@ -189,7 +189,7 @@ class TaskFlowDriver(driver.NotificationDriver):
if process_name == "nova-compute": if process_name == "nova-compute":
recovery_flow = process_failure.get_compute_process_recovery_flow recovery_flow = process_failure.get_compute_process_recovery_flow
else: else:
LOG.warning(_LW("Skipping recovery for process: %s."), LOG.warning("Skipping recovery for process: %s.",
process_name) process_name)
raise exception.SkipProcessRecoveryException() raise exception.SkipProcessRecoveryException()

View File

@ -26,7 +26,7 @@ from taskflow import retry
import masakari.conf import masakari.conf
from masakari.engine.drivers.taskflow import base from masakari.engine.drivers.taskflow import base
from masakari import exception from masakari import exception
from masakari.i18n import _, _LI from masakari.i18n import _
from masakari import utils from masakari import utils
@ -48,8 +48,8 @@ class DisableComputeServiceTask(base.MasakariTask):
self.novaclient.enable_disable_service(context, host_name) self.novaclient.enable_disable_service(context, host_name)
# Sleep until nova-compute service is marked as disabled. # Sleep until nova-compute service is marked as disabled.
msg = _LI("Sleeping %(wait)s sec before starting recovery " msg = ("Sleeping %(wait)s sec before starting recovery "
"thread until nova recognizes the node down.") "thread until nova recognizes the node down.")
LOG.info(msg, {'wait': CONF.wait_period_after_service_update}) LOG.info(msg, {'wait': CONF.wait_period_after_service_update})
eventlet.sleep(CONF.wait_period_after_service_update) eventlet.sleep(CONF.wait_period_after_service_update)
@ -118,8 +118,8 @@ class EvacuateInstancesTask(base.MasakariTask):
context, reserved_host.name, enable=True) context, reserved_host.name, enable=True)
# Sleep until nova-compute service is marked as enabled. # Sleep until nova-compute service is marked as enabled.
msg = _LI("Sleeping %(wait)s sec before starting recovery " msg = ("Sleeping %(wait)s sec before starting recovery "
"thread until nova recognizes the node up.") "thread until nova recognizes the node up.")
LOG.info(msg, { LOG.info(msg, {
'wait': CONF.wait_period_after_service_update}) 'wait': CONF.wait_period_after_service_update})
eventlet.sleep(CONF.wait_period_after_service_update) eventlet.sleep(CONF.wait_period_after_service_update)

View File

@ -24,7 +24,7 @@ from taskflow.patterns import linear_flow
import masakari.conf import masakari.conf
from masakari.engine.drivers.taskflow import base from masakari.engine.drivers.taskflow import base
from masakari import exception from masakari import exception
from masakari.i18n import _, _LI from masakari.i18n import _
CONF = masakari.conf.CONF CONF = masakari.conf.CONF
@ -51,8 +51,8 @@ class StopInstanceTask(base.MasakariTask):
if not CONF.instance_failure.process_all_instances and not ( if not CONF.instance_failure.process_all_instances and not (
strutils.bool_from_string( strutils.bool_from_string(
instance.metadata.get('HA_Enabled', False))): instance.metadata.get('HA_Enabled', False))):
LOG.info(_LI("Skipping recovery for instance: %s as it is " LOG.info("Skipping recovery for instance: %s as it is "
"not Ha_Enabled."), instance_uuid) "not Ha_Enabled.", instance_uuid)
raise exception.SkipInstanceRecoveryException() raise exception.SkipInstanceRecoveryException()
vm_state = getattr(instance, 'OS-EXT-STS:vm_state') vm_state = getattr(instance, 'OS-EXT-STS:vm_state')

View File

@ -23,7 +23,7 @@ from taskflow.patterns import linear_flow
import masakari.conf import masakari.conf
from masakari.engine.drivers.taskflow import base from masakari.engine.drivers.taskflow import base
from masakari import exception from masakari import exception
from masakari.i18n import _, _LI from masakari.i18n import _
CONF = masakari.conf.CONF CONF = masakari.conf.CONF
@ -46,8 +46,8 @@ class DisableComputeNodeTask(base.MasakariTask):
# disable compute node on given host # disable compute node on given host
self.novaclient.enable_disable_service(context, host_name) self.novaclient.enable_disable_service(context, host_name)
else: else:
LOG.info(_LI("Skipping recovery for process: %s as it is " LOG.info("Skipping recovery for process: %s as it is "
"already disabled."), "already disabled.",
process_name) process_name)

View File

@ -31,7 +31,6 @@ import masakari.conf
from masakari.engine import driver from masakari.engine import driver
from masakari.engine import instance_events as virt_events from masakari.engine import instance_events as virt_events
from masakari import exception from masakari import exception
from masakari.i18n import _LE, _LI, _LW
from masakari import manager from masakari import manager
from masakari import objects from masakari import objects
from masakari.objects import fields from masakari.objects import fields
@ -61,14 +60,13 @@ class MasakariManager(manager.Manager):
process_name = notification.payload.get('process_name') process_name = notification.payload.get('process_name')
if notification_event.upper() == 'STARTED': if notification_event.upper() == 'STARTED':
LOG.info(_LI("Notification type '%(type)s' received for host " LOG.info("Notification type '%(type)s' received for host "
"'%(host_uuid)s': '%(process_name)s' has been " "'%(host_uuid)s': '%(process_name)s' has been "
"%(event)s."), { "%(event)s.",
'type': notification.type, {'type': notification.type,
'host_uuid': notification.source_host_uuid, 'host_uuid': notification.source_host_uuid,
'process_name': process_name, 'process_name': process_name,
'event': notification_event 'event': notification_event})
})
elif notification_event.upper() == 'STOPPED': elif notification_event.upper() == 'STOPPED':
host_obj = objects.Host.get_by_uuid( host_obj = objects.Host.get_by_uuid(
context, notification.source_host_uuid) context, notification.source_host_uuid)
@ -91,21 +89,20 @@ class MasakariManager(manager.Manager):
exception.ProcessRecoveryFailureException): exception.ProcessRecoveryFailureException):
notification_status = fields.NotificationStatus.ERROR notification_status = fields.NotificationStatus.ERROR
else: else:
LOG.warning(_LW("Invalid event: %(event)s received for " LOG.warning("Invalid event: %(event)s received for "
"notification type: %(notification_type)s"), { "notification type: %(notification_type)s",
'event': notification_event, {'event': notification_event,
'notification_type': notification.type 'notification_type': notification.type})
})
notification_status = fields.NotificationStatus.IGNORED notification_status = fields.NotificationStatus.IGNORED
return notification_status return notification_status
def _handle_notification_type_instance(self, context, notification): def _handle_notification_type_instance(self, context, notification):
if not virt_events.is_valid_event(notification.payload): if not virt_events.is_valid_event(notification.payload):
LOG.info(_LI("Notification '%(uuid)s' received with payload " LOG.info("Notification '%(uuid)s' received with payload "
"%(payload)s is ignored."), { "%(payload)s is ignored.",
"uuid": notification.notification_uuid, {"uuid": notification.notification_uuid,
"payload": notification.payload}) "payload": notification.payload})
return fields.NotificationStatus.IGNORED return fields.NotificationStatus.IGNORED
notification_status = fields.NotificationStatus.FINISHED notification_status = fields.NotificationStatus.FINISHED
@ -126,12 +123,11 @@ class MasakariManager(manager.Manager):
notification_event = notification.payload.get('event') notification_event = notification.payload.get('event')
if notification_event.upper() == 'STARTED': if notification_event.upper() == 'STARTED':
LOG.info(_LI("Notification type '%(type)s' received for host " LOG.info("Notification type '%(type)s' received for host "
"'%(host_uuid)s' has been %(event)s."), { "'%(host_uuid)s' has been %(event)s.",
'type': notification.type, {'type': notification.type,
'host_uuid': notification.source_host_uuid, 'host_uuid': notification.source_host_uuid,
'event': notification_event 'event': notification_event})
})
elif notification_event.upper() == 'STOPPED': elif notification_event.upper() == 'STOPPED':
host_obj = objects.Host.get_by_uuid( host_obj = objects.Host.get_by_uuid(
context, notification.source_host_uuid) context, notification.source_host_uuid)
@ -170,11 +166,10 @@ class MasakariManager(manager.Manager):
exception.MasakariException): exception.MasakariException):
notification_status = fields.NotificationStatus.ERROR notification_status = fields.NotificationStatus.ERROR
else: else:
LOG.warning(_LW("Invalid event: %(event)s received for " LOG.warning("Invalid event: %(event)s received for "
"notification type: %(type)s"), { "notification type: %(type)s",
'event': notification_event, {'event': notification_event,
'type': notification.type 'type': notification.type})
})
notification_status = fields.NotificationStatus.IGNORED notification_status = fields.NotificationStatus.IGNORED
return notification_status return notification_status
@ -182,11 +177,10 @@ class MasakariManager(manager.Manager):
def _process_notification(self, context, notification): def _process_notification(self, context, notification):
@utils.synchronized(notification.source_host_uuid, blocking=True) @utils.synchronized(notification.source_host_uuid, blocking=True)
def do_process_notification(notification): def do_process_notification(notification):
LOG.info(_LI('Processing notification %(notification_uuid)s of ' LOG.info('Processing notification %(notification_uuid)s of '
'type: %(type)s'), { 'type: %(type)s',
'notification_uuid': notification.notification_uuid, {'notification_uuid': notification.notification_uuid,
'type': notification.type 'type': notification.type})
})
update_data = { update_data = {
'status': fields.NotificationStatus.RUNNING, 'status': fields.NotificationStatus.RUNNING,
@ -204,11 +198,10 @@ class MasakariManager(manager.Manager):
notification_status = self._handle_notification_type_host( notification_status = self._handle_notification_type_host(
context, notification) context, notification)
LOG.info(_LI("Notification %(notification_uuid)s exits with " LOG.info("Notification %(notification_uuid)s exits with "
"status: %(status)s."), { "status: %(status)s.",
'notification_uuid': notification.notification_uuid, {'notification_uuid': notification.notification_uuid,
'status': notification_status 'status': notification_status})
})
update_data = { update_data = {
'status': notification_status 'status': notification_status
@ -253,10 +246,9 @@ class MasakariManager(manager.Manager):
notification_db.update(update_data) notification_db.update(update_data)
notification_db.save() notification_db.save()
LOG.error(_LE( LOG.error(
"Periodic task 'process_unfinished_notifications': " "Periodic task 'process_unfinished_notifications': "
"Notification %(notification_uuid)s exits with " "Notification %(notification_uuid)s exits with "
"status: %(status)s."), { "status: %(status)s.",
'notification_uuid': notification.notification_uuid, {'notification_uuid': notification.notification_uuid,
'status': notification_status 'status': notification_status})
})

View File

@ -33,7 +33,7 @@ import webob.exc
from webob import util as woutil from webob import util as woutil
import masakari.conf import masakari.conf
from masakari.i18n import _, _LE from masakari.i18n import _
from masakari import safe_utils from masakari import safe_utils
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -58,7 +58,7 @@ class ConvertedException(webob.exc.WSGIHTTPException):
try: try:
self.title = woutil.status_reasons[self.code] self.title = woutil.status_reasons[self.code]
except KeyError: except KeyError:
msg = _LE("Improper or unknown HTTP status code used: %d") msg = "Improper or unknown HTTP status code used: %d"
LOG.error(msg, code) LOG.error(msg, code)
self.title = woutil.status_generic_reasons[self.code // 100] self.title = woutil.status_generic_reasons[self.code // 100]
self.explanation = explanation self.explanation = explanation
@ -137,7 +137,7 @@ class MasakariException(Exception):
exc_info = sys.exc_info() exc_info = sys.exc_info()
# kwargs doesn't match a variable in the message # kwargs doesn't match a variable in the message
# log the issue and the kwargs # log the issue and the kwargs
LOG.exception(_LE('Exception in string format operation')) LOG.exception('Exception in string format operation')
for name, value in kwargs.items(): for name, value in kwargs.items():
LOG.error("%s: %s" % (name, value)) # noqa LOG.error("%s: %s" % (name, value)) # noqa

View File

@ -15,7 +15,6 @@
import re import re
import pep8
""" """
Guidelines for writing new hacking checks Guidelines for writing new hacking checks
@ -70,14 +69,6 @@ asse_true_false_with_in_or_not_in_spaces = re.compile(
r"[][.'\", ])+[\[|'|\"](, .*)?\)") r"[][.'\", ])+[\[|'|\"](, .*)?\)")
asse_raises_regexp = re.compile(r"assertRaisesRegexp\(") asse_raises_regexp = re.compile(r"assertRaisesRegexp\(")
conf_attribute_set_re = re.compile(r"CONF\.[a-z0-9_.]+\s*=\s*\w") conf_attribute_set_re = re.compile(r"CONF\.[a-z0-9_.]+\s*=\s*\w")
log_translation = re.compile(
r"(.)*LOG\.(audit|error|critical)\(\s*('|\")")
log_translation_info = re.compile(
r"(.)*LOG\.(info)\(\s*(_\(|'|\")")
log_translation_exception = re.compile(
r"(.)*LOG\.(exception)\(\s*(_\(|'|\")")
log_translation_LW = re.compile(
r"(.)*LOG\.(warning|warn)\(\s*(_\(|'|\")")
translated_log = re.compile( translated_log = re.compile(
r"(.)*LOG\.(audit|error|info|critical|exception)" r"(.)*LOG\.(audit|error|info|critical|exception)"
"\(\s*_\(\s*('|\")") "\(\s*_\(\s*('|\")")
@ -222,27 +213,6 @@ def no_setting_conf_directly_in_tests(logical_line, filename):
"instead") "instead")
def validate_log_translations(logical_line, physical_line, filename):
# Translations are not required in the test directory
if "masakari/tests" in filename:
return
if pep8.noqa(physical_line):
return
msg = "M311: LOG.info messages require translations `_LI()`!"
if log_translation_info.match(logical_line):
yield (0, msg)
msg = "M312: LOG.exception messages require translations `_LE()`!"
if log_translation_exception.match(logical_line):
yield (0, msg)
msg = ("M313: LOG.warning, LOG.warn messages require "
"translations `_LW()`!")
if log_translation_LW.match(logical_line):
yield (0, msg)
msg = "M314: Log messages require translations!"
if log_translation.match(logical_line):
yield (0, msg)
def no_mutable_default_args(logical_line): def no_mutable_default_args(logical_line):
msg = "M315: Method's default argument shouldn't be mutable!" msg = "M315: Method's default argument shouldn't be mutable!"
if mutable_default_args.match(logical_line): if mutable_default_args.match(logical_line):
@ -469,7 +439,6 @@ def factory(register):
register(assert_raises_regexp) register(assert_raises_regexp)
register(no_translate_debug_logs) register(no_translate_debug_logs)
register(no_setting_conf_directly_in_tests) register(no_setting_conf_directly_in_tests)
register(validate_log_translations)
register(no_mutable_default_args) register(no_mutable_default_args)
register(check_explicit_underscore_import) register(check_explicit_underscore_import)
register(use_jsonutils) register(use_jsonutils)

View File

@ -27,16 +27,6 @@ _translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# The primary translation function using the well-known name "_" # The primary translation function using the well-known name "_"
_ = _translators.primary _ = _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): def translate(value, user_locale):
return oslo_i18n.translate(value, user_locale) return oslo_i18n.translate(value, user_locale)

View File

@ -28,7 +28,7 @@ from oslo_utils import importutils
import masakari.conf import masakari.conf
from masakari import context from masakari import context
from masakari import exception from masakari import exception
from masakari.i18n import _, _LE, _LI from masakari.i18n import _
from masakari.objects import base as objects_base from masakari.objects import base as objects_base
from masakari import rpc from masakari import rpc
from masakari import utils from masakari import utils
@ -79,7 +79,7 @@ class Service(service.Service):
def start(self): def start(self):
verstr = version.version_string_with_package() verstr = version.version_string_with_package()
LOG.info(_LI('Starting %(topic)s (version %(version)s)'), { LOG.info('Starting %(topic)s (version %(version)s)', {
'topic': self.topic, 'topic': self.topic,
'version': verstr 'version': verstr
}) })
@ -178,7 +178,7 @@ class Service(service.Service):
with utils.tempdir(): with utils.tempdir():
pass pass
except Exception as e: except Exception as e:
LOG.error(_LE('Temporary directory is invalid: %s'), e) LOG.error('Temporary directory is invalid: %s', e)
sys.exit(1) sys.exit(1)
def reset(self): def reset(self):

View File

@ -218,32 +218,6 @@ class HackingTestCase(test.NoDBTestCase):
self.assertEqual(len(list(checks.no_setting_conf_directly_in_tests( self.assertEqual(len(list(checks.no_setting_conf_directly_in_tests(
"CONF.option = 1", "masakari/compute/foo.py"))), 0) "CONF.option = 1", "masakari/compute/foo.py"))), 0)
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, 'f'))))
for log in logs:
bad = 'LOG.%s("Bad")' % log
self.assertEqual(1,
len(list(
checks.validate_log_translations(bad, bad, 'f'))))
ok = "LOG.%s('OK') # noqa" % log
self.assertEqual(0,
len(list(
checks.validate_log_translations(ok, ok, 'f'))))
ok = "LOG.%s(variable)" % log
self.assertEqual(0,
len(list(
checks.validate_log_translations(ok, ok, 'f'))))
for level in levels:
ok = "LOG.%s(%s('OK'))" % (log, level)
self.assertEqual(0,
len(list(
checks.validate_log_translations(ok, ok, 'f'))))
def test_no_mutable_default_args(self): def test_no_mutable_default_args(self):
self.assertEqual(1, len(list(checks.no_mutable_default_args( self.assertEqual(1, len(list(checks.no_mutable_default_args(
"def get_info_from_bdm(virt_type, bdm, mapping=[])")))) "def get_info_from_bdm(virt_type, bdm, mapping=[])"))))
@ -271,7 +245,7 @@ class HackingTestCase(test.NoDBTestCase):
"msg = _('My message')", "msg = _('My message')",
"masakari/tests/other_files.py"))), 0) "masakari/tests/other_files.py"))), 0)
self.assertEqual(len(list(checks.check_explicit_underscore_import( self.assertEqual(len(list(checks.check_explicit_underscore_import(
"from masakari.i18n import _, _LW", "from masakari.i18n import _",
"masakari/tests/other_files2.py"))), 0) "masakari/tests/other_files2.py"))), 0)
self.assertEqual(len(list(checks.check_explicit_underscore_import( self.assertEqual(len(list(checks.check_explicit_underscore_import(
"msg = _('My message')", "msg = _('My message')",
@ -485,18 +459,18 @@ class HackingTestCase(test.NoDBTestCase):
def test_check_delayed_string_interpolation(self): def test_check_delayed_string_interpolation(self):
checker = checks.check_delayed_string_interpolation checker = checks.check_delayed_string_interpolation
code = """ code = """
msg_w = _LW('Test string (%s)') msg_w = ('Test string (%s)')
msg_i = _LI('Test string (%s)') msg_i = 'Test string (%s)'
value = 'test' value = 'test'
LOG.error(_LE("Test string (%s)") % value) LOG.error(("Test string (%s)") % value)
LOG.warning(msg_w % 'test%string') LOG.warning(msg_w % 'test%string')
LOG.info(msg_i % LOG.info(msg_i %
"test%string%info") "test%string%info")
LOG.critical( LOG.critical(
_LC('Test string (%s)') % value, ('Test string (%s)') % value,
instance=instance) instance=instance)
LOG.exception(_LE(" 'Test quotation %s' \"Test\"") % 'test') LOG.exception((" 'Test quotation %s' \"Test\"") % 'test')
LOG.debug(' "Test quotation %s" \'Test\'' % "test") LOG.debug(' "Test quotation %s" \'Test\'' % "test")
LOG.debug('Tesing %(test)s' % LOG.debug('Tesing %(test)s' %
{'test': ','.join( {'test': ','.join(
@ -504,28 +478,28 @@ class HackingTestCase(test.NoDBTestCase):
for name, value in test.items()])}) for name, value in test.items()])})
""" """
expected_errors = [(5, 34, 'M330'), (6, 18, 'M330'), (7, 15, 'M330'), expected_errors = [(5, 31, 'M330'), (6, 18, 'M330'), (7, 15, 'M330'),
(10, 28, 'M330'), (12, 49, 'M330'), (10, 25, 'M330'), (12, 46, 'M330'),
(13, 40, 'M330'), (14, 28, 'M330')] (13, 40, 'M330'), (14, 28, 'M330')]
self._assert_has_errors(code, checker, expected_errors=expected_errors) self._assert_has_errors(code, checker, expected_errors=expected_errors)
self._assert_has_no_errors( self._assert_has_no_errors(
code, checker, filename='masakari/tests/unit/test_hacking.py') code, checker, filename='masakari/tests/unit/test_hacking.py')
code = """ code = """
msg_w = _LW('Test string (%s)') msg_w = ('Test string (%s)')
msg_i = _LI('Test string (%s)') msg_i = 'Test string (%s)'
value = 'test' value = 'test'
LOG.error(_LE("Test string (%s)"), value) LOG.error(("Test string (%s)"), value)
LOG.error(_LE("Test string (%s)") % value) # noqa LOG.error(("Test string (%s)") % value) # noqa
LOG.warn(_LW('Test string (%s)'), LOG.warn(('Test string (%s)'),
value) value)
LOG.info(msg_i, LOG.info(msg_i,
"test%string%info") "test%string%info")
LOG.critical( LOG.critical(
_LC('Test string (%s)'), value, ('Test string (%s)'), value,
instance=instance) instance=instance)
LOG.exception(_LE(" 'Test quotation %s' \"Test\""), 'test') LOG.exception((" 'Test quotation %s' \"Test\""), 'test')
LOG.debug(' "Test quotation %s" \'Test\'', "test") LOG.debug(' "Test quotation %s" \'Test\'', "test")
LOG.debug('Tesing %(test)s', LOG.debug('Tesing %(test)s',
{'test': ','.join( {'test': ','.join(

View File

@ -33,7 +33,7 @@ import six
import masakari.conf import masakari.conf
from masakari import exception from masakari import exception
from masakari.i18n import _, _LE from masakari.i18n import _
from masakari import safe_utils from masakari import safe_utils
@ -238,7 +238,7 @@ def tempdir(**kwargs):
try: try:
shutil.rmtree(tmpdir) shutil.rmtree(tmpdir)
except OSError as e: except OSError as e:
LOG.error(_LE('Could not remove tmpdir: %s'), e) LOG.error('Could not remove tmpdir: %s', e)
def validate_integer(value, name, min_value=None, max_value=None): def validate_integer(value, name, min_value=None, max_value=None):

View File

@ -15,8 +15,6 @@
from pbr import version as pbr_version from pbr import version as pbr_version
from masakari.i18n import _LE
MASAKARI_VENDOR = "OpenStack Foundation" MASAKARI_VENDOR = "OpenStack Foundation"
MASAKARI_PRODUCT = "OpenStack Masakari" MASAKARI_PRODUCT = "OpenStack Masakari"
MASAKARI_PACKAGE = None # OS distro package version suffix MASAKARI_PACKAGE = None # OS distro package version suffix
@ -60,7 +58,7 @@ def _load_config():
MASAKARI_PACKAGE = cfg.get("Masakari", "package") MASAKARI_PACKAGE = cfg.get("Masakari", "package")
except Exception as ex: except Exception as ex:
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
LOG.error(_LE("Failed to load %(cfgfile)s: %(ex)s"), LOG.error("Failed to load %(cfgfile)s: %(ex)s",
{'cfgfile': cfgfile, 'ex': ex}) {'cfgfile': cfgfile, 'ex': ex})

View File

@ -34,7 +34,7 @@ import webob.exc
import masakari.conf import masakari.conf
from masakari import exception from masakari import exception
from masakari.i18n import _, _LE, _LI from masakari.i18n import _
from masakari import utils from masakari import utils
CONF = masakari.conf.CONF CONF = masakari.conf.CONF
@ -94,12 +94,12 @@ class Server(service.ServiceBase):
try: try:
self._socket = eventlet.listen(bind_addr, family, backlog=backlog) self._socket = eventlet.listen(bind_addr, family, backlog=backlog)
except EnvironmentError: except EnvironmentError:
LOG.error(_LE("Could not bind to %(host)s:%(port)d"), LOG.error("Could not bind to %(host)s:%(port)d",
{'host': host, 'port': port}) {'host': host, 'port': port})
raise raise
(self.host, self.port) = self._socket.getsockname()[0:2] (self.host, self.port) = self._socket.getsockname()[0:2]
LOG.info(_LI("%(name)s listening on %(host)s:%(port)d"), LOG.info("%(name)s listening on %(host)s:%(port)d",
{'name': self.name, 'host': self.host, 'port': self.port}) {'name': self.name, 'host': self.host, 'port': self.port})
def start(self): def start(self):
@ -163,8 +163,8 @@ class Server(service.ServiceBase):
**ssl_kwargs) **ssl_kwargs)
except Exception: except Exception:
with excutils.save_and_reraise_exception(): with excutils.save_and_reraise_exception():
LOG.error(_LE("Failed to start %(name)s on %(host)s" LOG.error("Failed to start %(name)s on %(host)s"
":%(port)d with SSL support"), ":%(port)d with SSL support",
{'name': self.name, 'host': self.host, {'name': self.name, 'host': self.host,
'port': self.port}) 'port': self.port})
@ -203,7 +203,7 @@ class Server(service.ServiceBase):
:returns: None :returns: None
""" """
LOG.info(_LI("Stopping WSGI server.")) LOG.info("Stopping WSGI server.")
if self._server is not None: if self._server is not None:
# Resize pool to stop new requests from being processed # Resize pool to stop new requests from being processed
@ -223,7 +223,7 @@ class Server(service.ServiceBase):
self._pool.waitall() self._pool.waitall()
self._server.wait() self._server.wait()
except greenlet.GreenletExit: except greenlet.GreenletExit:
LOG.info(_LI("WSGI server has stopped.")) LOG.info("WSGI server has stopped.")
class Request(webob.Request): class Request(webob.Request):
@ -490,5 +490,5 @@ class Loader(object):
{'name': name, 'path': self.config_path}) {'name': name, 'path': self.config_path})
return deploy.loadapp("config:%s" % self.config_path, name=name) return deploy.loadapp("config:%s" % self.config_path, name=name)
except LookupError: except LookupError:
LOG.exception(_LE("Couldn't lookup app: %s"), name) LOG.exception("Couldn't lookup app: %s", name)
raise exception.PasteAppNotFound(name=name, path=self.config_path) raise exception.PasteAppNotFound(name=name, path=self.config_path)