diff --git a/placement/cmd/manage.py b/placement/cmd/manage.py index 8fb7d6080..cc3adb231 100644 --- a/placement/cmd/manage.py +++ b/placement/cmd/manage.py @@ -24,7 +24,6 @@ from placement import conf from placement import context from placement.db.sqlalchemy import migration from placement import db_api -from placement.i18n import _ from placement.objects import consumer as consumer_obj from placement.objects import resource_provider as rp_obj @@ -86,13 +85,13 @@ class DbCommands(object): except ValueError: max_count = -1 if max_count < 1: - print(_('Must supply a positive value for max_count')) + print('Must supply a positive value for max_count') return 127 limited = True else: max_count = 50 limited = False - print(_('Running batches of %i until complete') % max_count) + print('Running batches of %i until complete' % max_count) ran = None migration_info = collections.OrderedDict() @@ -113,7 +112,7 @@ class DbCommands(object): break t = prettytable.PrettyTable( - [_('Migration'), _('Total Found'), _('Completed')]) + ['Migration', 'Total Found', 'Completed']) for name, info in migration_info.items(): t.add_row([name, info[0], info[1]]) print(t) @@ -123,8 +122,8 @@ class DbCommands(object): # to be done, and that work may resolve dependencies for the failing # migrations. if exceptions and not (limited and ran): - print(_("Some migrations failed unexpectedly. Check log for " - "details.")) + print("Some migrations failed unexpectedly. Check log for " + "details.") return 2 # TODO(mriedem): Potentially add another return code for @@ -141,7 +140,7 @@ class DbCommands(object): try: found, done = migration_meth(ctxt, count) except Exception: - msg = (_("Error attempting to run %(method)s") % dict( + msg = ("Error attempting to run %(method)s" % dict( method=migration_meth)) print(msg) LOG.exception(msg) @@ -150,10 +149,10 @@ class DbCommands(object): name = migration_meth.__name__ if found: - print(_('%(total)i rows matched query %(meth)s, %(done)i ' - 'migrated') % {'total': found, - 'meth': name, - 'done': done}) + print('%(total)i rows matched query %(meth)s, %(done)i ' + 'migrated' % {'total': found, + 'meth': name, + 'done': done}) # This is the per-migration method result for this batch, and # _run_online_migration will either continue on to the next # migration, or stop if up to this point we've processed max_count @@ -178,21 +177,21 @@ def add_db_command_parsers(subparsers, config): parser.set_defaults(func=parser.print_help) db_parser = parser.add_subparsers(description='database commands') - help = _('Sync the datatabse to the current version.') + help = 'Sync the datatabse to the current version.' sync_parser = db_parser.add_parser('sync', help=help, description=help) sync_parser.set_defaults(func=command_object.db_sync) - help = _('Report the current database version.') + help = 'Report the current database version.' version_parser = db_parser.add_parser( 'version', help=help, description=help) version_parser.set_defaults(func=command_object.db_version) - help = _('Stamp the revision table with the given version.') + help = 'Stamp the revision table with the given version.' stamp_parser = db_parser.add_parser('stamp', help=help, description=help) - stamp_parser.add_argument('version', help=_('the version to stamp')) + stamp_parser.add_argument('version', help='the version to stamp') stamp_parser.set_defaults(func=command_object.db_stamp) - help = _('Run the online data migrations.') + help = 'Run the online data migrations.' online_dm_parser = db_parser.add_parser( 'online_data_migrations', help=help, description=help) online_dm_parser.add_argument( @@ -208,7 +207,7 @@ def setup_commands(config): add_db_cmd_parsers = functools.partial( add_db_command_parsers, config=config) command_opt = cfg.SubCommandOpt( - 'db', dest='command', title='Command', help=_('Available DB commands'), + 'db', dest='command', title='Command', help='Available DB commands', handler=add_db_cmd_parsers) return [command_opt] diff --git a/placement/cmd/status.py b/placement/cmd/status.py index bc7b921bc..f8d8bee17 100644 --- a/placement/cmd/status.py +++ b/placement/cmd/status.py @@ -20,7 +20,6 @@ from placement import conf from placement import context from placement.db.sqlalchemy import models from placement import db_api -from placement.i18n import _ class Checks(upgradecheck.UpgradeCommands): @@ -57,10 +56,10 @@ class Checks(upgradecheck.UpgradeCommands): if self._check_missing_root_ids(self.ctxt): return upgradecheck.Result( upgradecheck.Code.WARNING, - details=_('There is at least one resource provider table ' - 'record which misses its root provider id. ' - 'Run the "placement-manage db ' - 'online_data_migrations" command.')) + details='There is at least one resource provider table ' + 'record which misses its root provider id. ' + 'Run the "placement-manage db ' + 'online_data_migrations" command.') return upgradecheck.Result(upgradecheck.Code.SUCCESS) @db_api.placement_context_manager.reader @@ -96,10 +95,10 @@ class Checks(upgradecheck.UpgradeCommands): # a warning and tell the user to run the online data migrations. return upgradecheck.Result( upgradecheck.Code.WARNING, - details=_('There are %s incomplete consumers table records ' - 'for existing allocations. Run the ' - '"placement-manage db online_data_migrations" ' - 'command.') % missing_consumer_count) + details='There are %s incomplete consumers table records ' + 'for existing allocations. Run the ' + '"placement-manage db online_data_migrations" ' + 'command.' % missing_consumer_count) # No missing consumers (or no allocations [fresh install?]) so it's OK. return upgradecheck.Result(upgradecheck.Code.SUCCESS) @@ -111,8 +110,8 @@ class Checks(upgradecheck.UpgradeCommands): # in the returned Result's "details" attribute. The # summary will be rolled up at the end of the check() method. _upgrade_checks = ( - (_('Missing Root Provider IDs'), _check_root_provider_ids), - (_('Incomplete Consumers'), _check_incomplete_consumers), + ('Missing Root Provider IDs', _check_root_provider_ids), + ('Incomplete Consumers', _check_incomplete_consumers), ) diff --git a/placement/exception.py b/placement/exception.py index b5901ff90..1b89b7a0c 100644 --- a/placement/exception.py +++ b/placement/exception.py @@ -13,8 +13,6 @@ from oslo_log import log as logging -from placement.i18n import _ - LOG = logging.getLogger(__name__) @@ -27,7 +25,7 @@ class _BaseException(Exception): with the keyword arguments provided to the constructor. """ - msg_fmt = _("An unknown exception occurred.") + msg_fmt = "An unknown exception occurred." def __init__(self, message=None, **kwargs): self.kwargs = kwargs @@ -58,141 +56,141 @@ class _BaseException(Exception): class NotFound(_BaseException): - msg_fmt = _("Resource could not be found.") + msg_fmt = "Resource could not be found." class Exists(_BaseException): - msg_fmt = _("Resource already exists.") + msg_fmt = "Resource already exists." class InvalidInventory(_BaseException): - msg_fmt = _("Inventory for '%(resource_class)s' on " - "resource provider '%(resource_provider)s' invalid.") + msg_fmt = ("Inventory for '%(resource_class)s' on " + "resource provider '%(resource_provider)s' invalid.") class CannotDeleteParentResourceProvider(_BaseException): - msg_fmt = _("Cannot delete resource provider that is a parent of " - "another. Delete child providers first.") + msg_fmt = ("Cannot delete resource provider that is a parent of " + "another. Delete child providers first.") class ConcurrentUpdateDetected(_BaseException): - msg_fmt = _("Another thread concurrently updated the data. " - "Please retry your update") + msg_fmt = ("Another thread concurrently updated the data. " + "Please retry your update") class ResourceProviderConcurrentUpdateDetected(ConcurrentUpdateDetected): - msg_fmt = _("Another thread concurrently updated the resource provider " - "data. Please retry your update") + msg_fmt = ("Another thread concurrently updated the resource provider " + "data. Please retry your update") class InvalidAllocationCapacityExceeded(InvalidInventory): - msg_fmt = _("Unable to create allocation for '%(resource_class)s' on " - "resource provider '%(resource_provider)s'. The requested " - "amount would exceed the capacity.") + msg_fmt = ("Unable to create allocation for '%(resource_class)s' on " + "resource provider '%(resource_provider)s'. The requested " + "amount would exceed the capacity.") class InvalidAllocationConstraintsViolated(InvalidInventory): - msg_fmt = _("Unable to create allocation for '%(resource_class)s' on " - "resource provider '%(resource_provider)s'. The requested " - "amount would violate inventory constraints.") + msg_fmt = ("Unable to create allocation for '%(resource_class)s' on " + "resource provider '%(resource_provider)s'. The requested " + "amount would violate inventory constraints.") class InvalidInventoryCapacity(InvalidInventory): - msg_fmt = _("Invalid inventory for '%(resource_class)s' on " - "resource provider '%(resource_provider)s'. " - "The reserved value is greater than or equal to total.") + msg_fmt = ("Invalid inventory for '%(resource_class)s' on " + "resource provider '%(resource_provider)s'. " + "The reserved value is greater than or equal to total.") class InvalidInventoryCapacityReservedCanBeTotal(InvalidInventoryCapacity): - msg_fmt = _("Invalid inventory for '%(resource_class)s' on " - "resource provider '%(resource_provider)s'. " - "The reserved value is greater than total.") + msg_fmt = ("Invalid inventory for '%(resource_class)s' on " + "resource provider '%(resource_provider)s'. " + "The reserved value is greater than total.") # An exception with this name is used on both sides of the placement/ # nova interaction. class InventoryInUse(InvalidInventory): - msg_fmt = _("Inventory for '%(resource_classes)s' on " - "resource provider '%(resource_provider)s' in use.") + msg_fmt = ("Inventory for '%(resource_classes)s' on " + "resource provider '%(resource_provider)s' in use.") class InventoryWithResourceClassNotFound(NotFound): - msg_fmt = _("No inventory of class %(resource_class)s found.") + msg_fmt = "No inventory of class %(resource_class)s found." class MaxDBRetriesExceeded(_BaseException): - msg_fmt = _("Max retries of DB transaction exceeded attempting to " - "perform %(action)s.") + msg_fmt = ("Max retries of DB transaction exceeded attempting to " + "perform %(action)s.") class ObjectActionError(_BaseException): - msg_fmt = _('Object action %(action)s failed because: %(reason)s') + msg_fmt = 'Object action %(action)s failed because: %(reason)s' class PolicyNotAuthorized(_BaseException): - msg_fmt = _("Policy does not allow %(action)s to be performed.") + msg_fmt = "Policy does not allow %(action)s to be performed." class ResourceClassCannotDeleteStandard(_BaseException): - msg_fmt = _("Cannot delete standard resource class %(resource_class)s.") + msg_fmt = "Cannot delete standard resource class %(resource_class)s." class ResourceClassCannotUpdateStandard(_BaseException): - msg_fmt = _("Cannot update standard resource class %(resource_class)s.") + msg_fmt = "Cannot update standard resource class %(resource_class)s." class ResourceClassExists(_BaseException): - msg_fmt = _("Resource class %(resource_class)s already exists.") + msg_fmt = "Resource class %(resource_class)s already exists." class ResourceClassInUse(_BaseException): - msg_fmt = _("Cannot delete resource class %(resource_class)s. " - "Class is in use in inventory.") + msg_fmt = ("Cannot delete resource class %(resource_class)s. " + "Class is in use in inventory.") class ResourceClassNotFound(NotFound): - msg_fmt = _("No such resource class %(resource_class)s.") + msg_fmt = "No such resource class %(resource_class)s." class ResourceProviderInUse(_BaseException): - msg_fmt = _("Resource provider has allocations.") + msg_fmt = "Resource provider has allocations." class TraitCannotDeleteStandard(_BaseException): - msg_fmt = _("Cannot delete standard trait %(name)s.") + msg_fmt = "Cannot delete standard trait %(name)s." class TraitExists(_BaseException): - msg_fmt = _("The Trait %(name)s already exists") + msg_fmt = "The Trait %(name)s already exists" class TraitInUse(_BaseException): - msg_fmt = _("The trait %(name)s is in use by a resource provider.") + msg_fmt = "The trait %(name)s is in use by a resource provider." class TraitNotFound(NotFound): - msg_fmt = _("No such trait(s): %(names)s.") + msg_fmt = "No such trait(s): %(names)s." class ProjectNotFound(NotFound): - msg_fmt = _("No such project(s): %(external_id)s.") + msg_fmt = "No such project(s): %(external_id)s." class ProjectExists(Exists): - msg_fmt = _("The project %(external_id)s already exists.") + msg_fmt = "The project %(external_id)s already exists." class UserNotFound(NotFound): - msg_fmt = _("No such user(s): %(external_id)s.") + msg_fmt = "No such user(s): %(external_id)s." class UserExists(Exists): - msg_fmt = _("The user %(external_id)s already exists.") + msg_fmt = "The user %(external_id)s already exists." class ConsumerNotFound(NotFound): - msg_fmt = _("No such consumer(s): %(uuid)s.") + msg_fmt = "No such consumer(s): %(uuid)s." class ConsumerExists(Exists): - msg_fmt = _("The consumer %(uuid)s already exists.") + msg_fmt = "The consumer %(uuid)s already exists." diff --git a/placement/handler.py b/placement/handler.py index ed195ba90..ef280558c 100644 --- a/placement/handler.py +++ b/placement/handler.py @@ -39,7 +39,6 @@ from placement.handlers import resource_provider from placement.handlers import root from placement.handlers import trait from placement.handlers import usage -from placement.i18n import _ from placement import util LOG = logging.getLogger(__name__) @@ -166,7 +165,7 @@ def handle_405(environ, start_response): headers['allow'] = str(_methods) # Use Exception class as WSGI Application. We don't want to raise here. response = webob.exc.HTTPMethodNotAllowed( - _('The method specified is not allowed for this resource.'), + 'The method specified is not allowed for this resource.', headers=headers, json_formatter=util.json_error_formatter) return response(environ, start_response) @@ -206,11 +205,11 @@ class PlacementHandler(object): try: if clen and (int(clen) > 0) and not environ.get('CONTENT_TYPE'): raise webob.exc.HTTPBadRequest( - _('content-type header required when content-length > 0'), + 'content-type header required when content-length > 0', json_formatter=util.json_error_formatter) except ValueError as exc: raise webob.exc.HTTPBadRequest( - _('content-length header must be an integer'), + 'content-length header must be an integer', json_formatter=util.json_error_formatter) try: return dispatch(environ, start_response, self._map) diff --git a/placement/handlers/aggregate.py b/placement/handlers/aggregate.py index a6fc0bc24..ea39533aa 100644 --- a/placement/handlers/aggregate.py +++ b/placement/handlers/aggregate.py @@ -19,7 +19,6 @@ import webob from placement import errors from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import resource_provider as rp_obj from placement.policies import aggregate as policies @@ -72,11 +71,11 @@ def _set_aggregates(resource_provider, aggregate_uuids, aggregate_uuids, increment_generation=increment_generation) except exception.ConcurrentUpdateDetected as exc: raise webob.exc.HTTPConflict( - _('Update conflict: %(error)s') % {'error': exc}, + 'Update conflict: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) except db_exc.DBDuplicateEntry as exc: raise webob.exc.HTTPConflict( - _('Update conflict: %(error)s') % {'error': exc}) + 'Update conflict: %(error)s' % {'error': exc}) @wsgi_wrapper.PlacementWsgify @@ -121,8 +120,8 @@ def set_aggregates(req): rp_gen = data['resource_provider_generation'] if resource_provider.generation != rp_gen: raise webob.exc.HTTPConflict( - _("Resource provider's generation already changed. Please " - "update the generation and try again."), + "Resource provider's generation already changed. Please " + "update the generation and try again.", comment=errors.CONCURRENT_UPDATE) aggregate_uuids = data['aggregates'] else: diff --git a/placement/handlers/allocation.py b/placement/handlers/allocation.py index fd1c159ea..b68775807 100644 --- a/placement/handlers/allocation.py +++ b/placement/handlers/allocation.py @@ -25,7 +25,6 @@ import webob from placement import errors from placement import exception from placement.handlers import util as data_util -from placement.i18n import _ from placement import microversion from placement.objects import allocation as alloc_obj from placement.objects import resource_provider as rp_obj @@ -287,7 +286,7 @@ def list_for_resource_provider(req): rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("Resource provider '%(rp_uuid)s' not found: %(error)s") % + "Resource provider '%(rp_uuid)s' not found: %(error)s" % {'rp_uuid': uuid, 'error': exc}) allocs = alloc_obj.get_all_by_resource_provider(context, rp) @@ -328,9 +327,8 @@ def _resource_providers_by_uuid(ctx, rp_uuids): res[rp_uuid] = rp_obj.ResourceProvider.get_by_uuid(ctx, rp_uuid) except exception.NotFound: raise webob.exc.HTTPBadRequest( - _("Allocation for resource provider '%(rp_uuid)s' " - "that does not exist.") % - {'rp_uuid': rp_uuid}) + "Allocation for resource provider '%(rp_uuid)s' " + "that does not exist." % {'rp_uuid': rp_uuid}) return res @@ -376,7 +374,7 @@ def _set_allocations_for_consumer(req, schema): consumer_uuid = util.wsgi_path_item(req.environ, 'consumer_uuid') if not uuidutils.is_uuid_like(consumer_uuid): raise webob.exc.HTTPBadRequest( - _('Malformed consumer_uuid: %(consumer_uuid)s') % + 'Malformed consumer_uuid: %(consumer_uuid)s' % {'consumer_uuid': consumer_uuid}) consumer_uuid = str(uuid.UUID(consumer_uuid)) data = util.extract_json(req.body, schema) @@ -447,15 +445,15 @@ def _set_allocations_for_consumer(req, schema): # capacity limits have been exceeded. except exception.NotFound as exc: raise webob.exc.HTTPBadRequest( - _("Unable to allocate inventory for consumer %(consumer_uuid)s: " - "%(error)s") % {'consumer_uuid': consumer_uuid, 'error': exc}) + "Unable to allocate inventory for consumer %(consumer_uuid)s: " + "%(error)s" % {'consumer_uuid': consumer_uuid, 'error': exc}) except exception.InvalidInventory as exc: raise webob.exc.HTTPConflict( - _('Unable to allocate inventory: %(error)s') % {'error': exc}) + 'Unable to allocate inventory: %(error)s' % {'error': exc}) except exception.ConcurrentUpdateDetected as exc: raise webob.exc.HTTPConflict( - _('Inventory and/or allocations changed while attempting to ' - 'allocate: %(error)s') % {'error': exc}, + 'Inventory and/or allocations changed while attempting to ' + 'allocate: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) req.response.status = 204 @@ -523,17 +521,17 @@ def set_allocations(req): _create_allocations(allocations) except exception.NotFound as exc: raise webob.exc.HTTPBadRequest( - _("Unable to allocate inventory %(error)s") % {'error': exc}) + "Unable to allocate inventory %(error)s" % {'error': exc}) except exception.InvalidInventory as exc: # InvalidInventory is a parent for several exceptions that # indicate either that Inventory is not present, or that # capacity limits have been exceeded. raise webob.exc.HTTPConflict( - _('Unable to allocate inventory: %(error)s') % {'error': exc}) + 'Unable to allocate inventory: %(error)s' % {'error': exc}) except exception.ConcurrentUpdateDetected as exc: raise webob.exc.HTTPConflict( - _('Inventory and/or allocations changed while attempting to ' - 'allocate: %(error)s') % {'error': exc}, + 'Inventory and/or allocations changed while attempting to ' + 'allocate: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) req.response.status = 204 @@ -556,12 +554,11 @@ def delete_allocations(req): # activity. In that case, delete_all() will throw a NotFound exception. except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("Allocation for consumer with id %(id)s not found. error: " - "%(error)s") % - {'id': consumer_uuid, 'error': exc}) + "Allocation for consumer with id %(id)s not found. error: " + "%(error)s" % {'id': consumer_uuid, 'error': exc}) else: raise webob.exc.HTTPNotFound( - _("No allocations for consumer '%(consumer_uuid)s'") % + "No allocations for consumer '%(consumer_uuid)s'" % {'consumer_uuid': consumer_uuid}) LOG.debug("Successfully deleted allocations %s", allocations) diff --git a/placement/handlers/allocation_candidate.py b/placement/handlers/allocation_candidate.py index e8a44c8f1..2750c4e17 100644 --- a/placement/handlers/allocation_candidate.py +++ b/placement/handlers/allocation_candidate.py @@ -21,7 +21,6 @@ import six import webob from placement import exception -from placement.i18n import _ from placement import lib from placement import microversion from placement.objects import allocation_candidate as ac_obj @@ -310,15 +309,15 @@ def list_allocation_candidates(req): # specified. if len([rg for rg in requests.values() if rg.use_same_provider]) > 1: raise webob.exc.HTTPBadRequest( - _('The "group_policy" parameter is required when specifying ' - 'more than one "resources{N}" parameter.')) + 'The "group_policy" parameter is required when specifying ' + 'more than one "resources{N}" parameter.') try: cands = ac_obj.AllocationCandidates.get_by_requests( context, requests, limit=limit, group_policy=group_policy) except exception.ResourceClassNotFound as exc: raise webob.exc.HTTPBadRequest( - _('Invalid resource class in resources parameter: %(error)s') % + 'Invalid resource class in resources parameter: %(error)s' % {'error': exc}) except exception.TraitNotFound as exc: raise webob.exc.HTTPBadRequest(six.text_type(exc)) diff --git a/placement/handlers/inventory.py b/placement/handlers/inventory.py index 8bdf6b882..d907eb25f 100644 --- a/placement/handlers/inventory.py +++ b/placement/handlers/inventory.py @@ -22,7 +22,6 @@ import webob from placement.db import constants as db_const from placement import errors from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import inventory as inv_obj from placement.objects import resource_provider as rp_obj @@ -88,10 +87,10 @@ def make_inventory_object(resource_provider, resource_class, **data): resource_class=resource_class, **data) except (ValueError, TypeError) as exc: raise webob.exc.HTTPBadRequest( - _('Bad inventory %(class)s for resource provider ' - '%(rp_uuid)s: %(error)s') % {'class': resource_class, - 'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Bad inventory %(class)s for resource provider ' + '%(rp_uuid)s: %(error)s' % {'class': resource_class, + 'rp_uuid': resource_provider.uuid, + 'error': exc}) return inventory @@ -204,14 +203,14 @@ def create_inventory(req): except (exception.ConcurrentUpdateDetected, db_exc.DBDuplicateEntry) as exc: raise webob.exc.HTTPConflict( - _('Update conflict: %(error)s') % {'error': exc}, + 'Update conflict: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) except (exception.InvalidInventoryCapacity, exception.NotFound) as exc: raise webob.exc.HTTPBadRequest( - _('Unable to create inventory for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Unable to create inventory for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) response = req.response response.location = util.inventory_url( @@ -241,12 +240,12 @@ def delete_inventory(req): except (exception.ConcurrentUpdateDetected, exception.InventoryInUse) as exc: raise webob.exc.HTTPConflict( - _('Unable to delete inventory of class %(class)s: %(error)s') % + 'Unable to delete inventory of class %(class)s: %(error)s' % {'class': resource_class, 'error': exc}, comment=errors.CONCURRENT_UPDATE) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _('No inventory of class %(class)s found for delete: %(error)s') % + 'No inventory of class %(class)s found for delete: %(error)s' % {'class': resource_class, 'error': exc}) response = req.response @@ -270,7 +269,7 @@ def get_inventories(req): rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("No resource provider with uuid %(uuid)s found : %(error)s") % + "No resource provider with uuid %(uuid)s found : %(error)s" % {'uuid': uuid, 'error': exc}) inv_list = inv_obj.get_all_by_resource_provider(context, rp) @@ -294,7 +293,7 @@ def get_inventory(req): rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("No resource provider with uuid %(uuid)s found : %(error)s") % + "No resource provider with uuid %(uuid)s found : %(error)s" % {'uuid': uuid, 'error': exc}) inv_list = inv_obj.get_all_by_resource_provider(context, rp) @@ -302,7 +301,7 @@ def get_inventory(req): if not inventory: raise webob.exc.HTTPNotFound( - _('No inventory of class %(class)s for %(rp_uuid)s') % + 'No inventory of class %(class)s for %(rp_uuid)s' % {'class': resource_class, 'rp_uuid': uuid}) return _send_inventory(req, rp, inventory) @@ -333,7 +332,7 @@ def set_inventories(req): data = _extract_inventories(req.body, schema.PUT_INVENTORY_SCHEMA) if data['resource_provider_generation'] != resource_provider.generation: raise webob.exc.HTTPConflict( - _('resource provider generation conflict'), + 'resource provider generation conflict', comment=errors.CONCURRENT_UPDATE) inventories = [] @@ -348,29 +347,29 @@ def set_inventories(req): resource_provider.set_inventory(inventories) except exception.ResourceClassNotFound as exc: raise webob.exc.HTTPBadRequest( - _('Unknown resource class in inventory for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Unknown resource class in inventory for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) except exception.InventoryWithResourceClassNotFound as exc: raise webob.exc.HTTPConflict( - _('Race condition detected when setting inventory. No inventory ' - 'record with resource class for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Race condition detected when setting inventory. No inventory ' + 'record with resource class for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) except (exception.ConcurrentUpdateDetected, db_exc.DBDuplicateEntry) as exc: raise webob.exc.HTTPConflict( - _('update conflict: %(error)s') % {'error': exc}, + 'update conflict: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) except exception.InventoryInUse as exc: raise webob.exc.HTTPConflict( - _('update conflict: %(error)s') % {'error': exc}, + 'update conflict: %(error)s' % {'error': exc}, comment=errors.INVENTORY_INUSE) except exception.InvalidInventoryCapacity as exc: raise webob.exc.HTTPBadRequest( - _('Unable to update inventory for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Unable to update inventory for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) return _send_inventories(req, resource_provider, inventories) @@ -395,9 +394,9 @@ def delete_inventories(req): resource_provider.set_inventory([]) except exception.ConcurrentUpdateDetected: raise webob.exc.HTTPConflict( - _('Unable to delete inventory for resource provider ' - '%(rp_uuid)s because the inventory was updated by ' - 'another process. Please retry your request.') % + 'Unable to delete inventory for resource provider ' + '%(rp_uuid)s because the inventory was updated by ' + 'another process. Please retry your request.' % {'rp_uuid': resource_provider.uuid}, comment=errors.CONCURRENT_UPDATE) except exception.InventoryInUse as ex: @@ -434,7 +433,7 @@ def update_inventory(req): data = _extract_inventory(req.body, schema.BASE_INVENTORY_SCHEMA) if data['resource_provider_generation'] != resource_provider.generation: raise webob.exc.HTTPConflict( - _('resource provider generation conflict'), + 'resource provider generation conflict', comment=errors.CONCURRENT_UPDATE) inventory = make_inventory_object(resource_provider, @@ -448,17 +447,17 @@ def update_inventory(req): except (exception.ConcurrentUpdateDetected, db_exc.DBDuplicateEntry) as exc: raise webob.exc.HTTPConflict( - _('update conflict: %(error)s') % {'error': exc}, + 'update conflict: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) except exception.InventoryWithResourceClassNotFound as exc: raise webob.exc.HTTPBadRequest( - _('No inventory record with resource class for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'No inventory record with resource class for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) except exception.InvalidInventoryCapacity as exc: raise webob.exc.HTTPBadRequest( - _('Unable to update inventory for resource provider ' - '%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, - 'error': exc}) + 'Unable to update inventory for resource provider ' + '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid, + 'error': exc}) return _send_inventory(req, resource_provider, inventory) diff --git a/placement/handlers/reshaper.py b/placement/handlers/reshaper.py index 8c9199ebc..ec140e548 100644 --- a/placement/handlers/reshaper.py +++ b/placement/handlers/reshaper.py @@ -28,7 +28,6 @@ from placement import exception # extracted from the handler to a shared module. from placement.handlers import allocation from placement.handlers import inventory -from placement.i18n import _ from placement import microversion from placement.objects import reshaper from placement.objects import resource_provider as rp_obj @@ -60,16 +59,16 @@ def reshape(req): context, rp_uuid) except exception.NotFound as exc: raise webob.exc.HTTPBadRequest( - _('Resource provider %(rp_uuid)s in inventories not found: ' - '%(error)s') % {'rp_uuid': rp_uuid, 'error': exc}, + 'Resource provider %(rp_uuid)s in inventories not found: ' + '%(error)s' % {'rp_uuid': rp_uuid, 'error': exc}, comment=errors.RESOURCE_PROVIDER_NOT_FOUND) # Do an early generation check. generation = inventory_data['resource_provider_generation'] if generation != resource_provider.generation: raise webob.exc.HTTPConflict( - _('resource provider generation conflict for provider %(rp)s: ' - 'actual: %(actual)s, given: %(given)s') % + 'resource provider generation conflict for provider %(rp)s: ' + 'actual: %(actual)s, given: %(given)s' % {'rp': rp_uuid, 'actual': resource_provider.generation, 'given': generation}, @@ -108,21 +107,21 @@ def reshape(req): # places in reshape(). except exception.ConcurrentUpdateDetected as exc: raise webob.exc.HTTPConflict( - _('update conflict: %(error)s') % {'error': exc}, + 'update conflict: %(error)s' % {'error': exc}, comment=errors.CONCURRENT_UPDATE) # A NotFound here means a resource class that does not exist was named except exception.NotFound as exc: raise webob.exc.HTTPBadRequest( - _('malformed reshaper data: %(error)s') % {'error': exc}) + 'malformed reshaper data: %(error)s' % {'error': exc}) # Distinguish inventory in use (has allocations on it)... except exception.InventoryInUse as exc: raise webob.exc.HTTPConflict( - _('update conflict: %(error)s') % {'error': exc}, + 'update conflict: %(error)s' % {'error': exc}, comment=errors.INVENTORY_INUSE) # ...from allocations which won't fit for a variety of reasons. except exception.InvalidInventory as exc: raise webob.exc.HTTPConflict( - _('Unable to allocate inventory: %(error)s') % {'error': exc}) + 'Unable to allocate inventory: %(error)s' % {'error': exc}) req.response.status = 204 req.response.content_type = None diff --git a/placement/handlers/resource_class.py b/placement/handlers/resource_class.py index 0e032c1f3..b0504799a 100644 --- a/placement/handlers/resource_class.py +++ b/placement/handlers/resource_class.py @@ -17,7 +17,6 @@ from oslo_utils import timeutils import webob from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import resource_class as rc_obj from placement.policies import resource_class as policies @@ -71,13 +70,13 @@ def create_resource_class(req): rc.create() except exception.ResourceClassExists: raise webob.exc.HTTPConflict( - _('Conflicting resource class already exists: %(name)s') % + 'Conflicting resource class already exists: %(name)s' % {'name': data['name']}) except exception.MaxDBRetriesExceeded: raise webob.exc.HTTPConflict( - _('Max retries of DB transaction exceeded attempting ' - 'to create resource class: %(name)s, please ' - 'try again.') % + 'Max retries of DB transaction exceeded attempting ' + 'to create resource class: %(name)s, please ' + 'try again.' % {'name': data['name']}) req.response.location = util.resource_class_url(req.environ, rc) @@ -102,10 +101,10 @@ def delete_resource_class(req): rc.destroy() except exception.ResourceClassCannotDeleteStandard as exc: raise webob.exc.HTTPBadRequest( - _('Error in delete resource class: %(error)s') % {'error': exc}) + 'Error in delete resource class: %(error)s' % {'error': exc}) except exception.ResourceClassInUse as exc: raise webob.exc.HTTPConflict( - _('Error in delete resource class: %(error)s') % {'error': exc}) + 'Error in delete resource class: %(error)s' % {'error': exc}) req.response.status = 204 req.response.content_type = None return req.response @@ -190,11 +189,11 @@ def update_resource_class(req): rc.save() except exception.ResourceClassExists: raise webob.exc.HTTPConflict( - _('Resource class already exists: %(name)s') % + 'Resource class already exists: %(name)s' % {'name': rc.name}) except exception.ResourceClassCannotUpdateStandard: raise webob.exc.HTTPBadRequest( - _('Cannot update standard resource class %(rp_name)s') % + 'Cannot update standard resource class %(rp_name)s' % {'rp_name': name}) req.response.body = encodeutils.to_utf8(jsonutils.dumps( diff --git a/placement/handlers/resource_provider.py b/placement/handlers/resource_provider.py index 940eb25a0..c2a6c9ba5 100644 --- a/placement/handlers/resource_provider.py +++ b/placement/handlers/resource_provider.py @@ -22,7 +22,6 @@ import webob from placement import errors from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import resource_provider as rp_obj from placement.policies import resource_provider as policies @@ -109,13 +108,13 @@ def create_resource_provider(req): duplicate = ', '.join( ['%s: %s' % (column, data[column]) for column in exc.columns]) raise webob.exc.HTTPConflict( - _('Conflicting resource provider %(duplicate)s already exists.') % + 'Conflicting resource provider %(duplicate)s already exists.' % {'duplicate': duplicate}, comment=errors.DUPLICATE_NAME) except exception.ObjectActionError as exc: raise webob.exc.HTTPBadRequest( - _('Unable to create resource provider "%(name)s", %(rp_uuid)s: ' - '%(error)s') % + 'Unable to create resource provider "%(name)s", %(rp_uuid)s: ' + '%(error)s' % {'name': data['name'], 'rp_uuid': data['uuid'], 'error': exc}) req.response.location = util.resource_provider_url( @@ -149,16 +148,16 @@ def delete_resource_provider(req): resource_provider.destroy() except exception.ResourceProviderInUse as exc: raise webob.exc.HTTPConflict( - _('Unable to delete resource provider %(rp_uuid)s: %(error)s') % + 'Unable to delete resource provider %(rp_uuid)s: %(error)s' % {'rp_uuid': uuid, 'error': exc}, comment=errors.PROVIDER_IN_USE) except exception.NotFound: raise webob.exc.HTTPNotFound( - _("No resource provider with uuid %s found for delete") % uuid) + "No resource provider with uuid %s found for delete" % uuid) except exception.CannotDeleteParentResourceProvider: raise webob.exc.HTTPConflict( - _("Unable to delete parent resource provider %(rp_uuid)s: " - "It has child resource providers.") % {'rp_uuid': uuid}, + "Unable to delete parent resource provider %(rp_uuid)s: " + "It has child resource providers." % {'rp_uuid': uuid}, comment=errors.PROVIDER_CANNOT_DELETE_PARENT) req.response.status = 204 req.response.content_type = None @@ -239,11 +238,11 @@ def list_resource_providers(req): resource_providers = rp_obj.get_all_by_filters(context, filters) except exception.ResourceClassNotFound as exc: raise webob.exc.HTTPBadRequest( - _('Invalid resource class in resources parameter: %(error)s') % + 'Invalid resource class in resources parameter: %(error)s' % {'error': exc}) except exception.TraitNotFound as exc: raise webob.exc.HTTPBadRequest( - _('Invalid trait(s) in "required" parameter: %(error)s') % + 'Invalid trait(s) in "required" parameter: %(error)s' % {'error': exc}) response = req.response @@ -288,12 +287,12 @@ def update_resource_provider(req): resource_provider.save() except db_exc.DBDuplicateEntry: raise webob.exc.HTTPConflict( - _('Conflicting resource provider %(name)s already exists.') % + 'Conflicting resource provider %(name)s already exists.' % {'name': data['name']}, comment=errors.DUPLICATE_NAME) except exception.ObjectActionError as exc: raise webob.exc.HTTPBadRequest( - _('Unable to save resource provider %(rp_uuid)s: %(error)s') % + 'Unable to save resource provider %(rp_uuid)s: %(error)s' % {'rp_uuid': uuid, 'error': exc}) response = req.response diff --git a/placement/handlers/trait.py b/placement/handlers/trait.py index 87d00db57..dab9dbced 100644 --- a/placement/handlers/trait.py +++ b/placement/handlers/trait.py @@ -19,7 +19,6 @@ import webob from placement import errors from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import resource_provider as rp_obj from placement.objects import trait as trait_obj @@ -33,9 +32,9 @@ def _normalize_traits_qs_param(qs): try: op, value = qs.split(':', 1) except ValueError: - msg = _('Badly formatted name parameter. Expected name query string ' - 'parameter in form: ' - '?name=[in|startswith]:[name1,name2|prefix]. Got: "%s"') + msg = ('Badly formatted name parameter. Expected name query string ' + 'parameter in form: ' + '?name=[in|startswith]:[name1,name2|prefix]. Got: "%s"') msg = msg % qs raise webob.exc.HTTPBadRequest(msg) @@ -75,9 +74,9 @@ def put_trait(req): jsonschema.validate(name, schema.CUSTOM_TRAIT) except jsonschema.ValidationError: raise webob.exc.HTTPBadRequest( - _('The trait is invalid. A valid trait must be no longer than ' - '255 characters, start with the prefix "CUSTOM_" and use ' - 'following characters: "A"-"Z", "0"-"9" and "_"')) + 'The trait is invalid. A valid trait must be no longer than ' + '255 characters, start with the prefix "CUSTOM_" and use ' + 'following characters: "A"-"Z", "0"-"9" and "_"') trait = trait_obj.Trait(context) trait.name = name @@ -158,8 +157,8 @@ def list_traits(req): if 'associated' in req.GET: if req.GET['associated'].lower() not in ['true', 'false']: raise webob.exc.HTTPBadRequest( - _('The query parameter "associated" only accepts ' - '"true" or "false"')) + 'The query parameter "associated" only accepts ' + '"true" or "false"') filters['associated'] = ( True if req.GET['associated'].lower() == 'true' else False) @@ -192,7 +191,7 @@ def list_traits_for_resource_provider(req): rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("No resource provider with uuid %(uuid)s found: %(error)s") % + "No resource provider with uuid %(uuid)s found: %(error)s" % {'uuid': uuid, 'error': exc}) traits = trait_obj.get_all_by_resource_provider(context, rp) @@ -225,8 +224,8 @@ def update_traits_for_resource_provider(req): if resource_provider.generation != rp_gen: raise webob.exc.HTTPConflict( - _("Resource provider's generation already changed. Please update " - "the generation and try again."), + "Resource provider's generation already changed. Please update " + "the generation and try again.", json_formatter=util.json_error_formatter, comment=errors.CONCURRENT_UPDATE) @@ -235,7 +234,7 @@ def update_traits_for_resource_provider(req): non_existed_trait = set(traits) - set(traits_name) if non_existed_trait: raise webob.exc.HTTPBadRequest( - _("No such trait %s") % ', '.join(non_existed_trait)) + "No such trait %s" % ', '.join(non_existed_trait)) resource_provider.set_traits(trait_objs) diff --git a/placement/handlers/usage.py b/placement/handlers/usage.py index a852e07bb..0bf322327 100644 --- a/placement/handlers/usage.py +++ b/placement/handlers/usage.py @@ -17,7 +17,6 @@ from oslo_utils import timeutils import webob from placement import exception -from placement.i18n import _ from placement import microversion from placement.objects import resource_provider as rp_obj from placement.objects import usage as usage_obj @@ -59,7 +58,7 @@ def list_usages(req): context, uuid) except exception.NotFound as exc: raise webob.exc.HTTPNotFound( - _("No resource provider with uuid %(uuid)s found: %(error)s") % + "No resource provider with uuid %(uuid)s found: %(error)s" % {'uuid': uuid, 'error': exc}) usage = usage_obj.get_all_by_resource_provider_uuid(context, uuid) diff --git a/placement/handlers/util.py b/placement/handlers/util.py index dec3c3780..37919e6c9 100644 --- a/placement/handlers/util.py +++ b/placement/handlers/util.py @@ -16,7 +16,6 @@ import webob from placement import errors from placement import exception -from placement.i18n import _ from placement.objects import consumer as consumer_obj from placement.objects import project as project_obj from placement.objects import user as user_obj @@ -80,8 +79,8 @@ def ensure_consumer(ctx, consumer_uuid, project_id, user_id, if requires_consumer_generation: if consumer.generation != consumer_generation: raise webob.exc.HTTPConflict( - _('consumer generation conflict - ' - 'expected %(expected_gen)s but got %(got_gen)s') % + 'consumer generation conflict - ' + 'expected %(expected_gen)s but got %(got_gen)s' % { 'expected_gen': consumer.generation, 'got_gen': consumer_generation, @@ -127,8 +126,8 @@ def ensure_consumer(ctx, consumer_uuid, project_id, user_id, if requires_consumer_generation: if consumer_generation is not None: raise webob.exc.HTTPConflict( - _('consumer generation conflict - ' - 'expected null but got %s') % consumer_generation, + 'consumer generation conflict - ' + 'expected null but got %s' % consumer_generation, comment=errors.CONCURRENT_UPDATE) # No such consumer. This is common for new allocations. Create the # consumer record diff --git a/placement/i18n.py b/placement/i18n.py deleted file mode 100644 index 4574496a8..000000000 --- a/placement/i18n.py +++ /dev/null @@ -1,36 +0,0 @@ -# Copyright 2014 IBM Corp. -# -# Licensed under the Apache License, Version 2.0 (the "License"); you may -# not use this file except in compliance with the License. You may obtain -# a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -# License for the specific language governing permissions and limitations -# under the License. - -"""oslo.i18n integration module. - -See https://docs.openstack.org/oslo.i18n/latest/user/index.html . - -""" - -import oslo_i18n - -DOMAIN = 'placement' - -_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN) - -# The primary translation function using the well-known name "_" -_ = _translators.primary - - -def translate(value, user_locale): - return oslo_i18n.translate(value, user_locale) - - -def get_available_languages(): - return oslo_i18n.get_available_languages(DOMAIN) diff --git a/placement/lib.py b/placement/lib.py index 3ff4b9651..aa7dc3fd5 100644 --- a/placement/lib.py +++ b/placement/lib.py @@ -18,7 +18,6 @@ import re import webob -from placement.i18n import _ from placement import microversion from placement import util @@ -115,25 +114,25 @@ class RequestGroup(object): orphans = [('required%s' % suff) for suff, group in by_suffix.items() if group.required_traits and not group.resources] if orphans: - msg = _( + msg = ( 'All traits parameters must be associated with resources. ' 'Found the following orphaned traits keys: %s') raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans)) orphans = [('member_of%s' % suff) for suff, group in by_suffix.items() if group.member_of and not group.resources] if orphans: - msg = _('All member_of parameters must be associated with ' - 'resources. Found the following orphaned member_of ' - 'keys: %s') + msg = ('All member_of parameters must be associated with ' + 'resources. Found the following orphaned member_of ' + 'keys: %s') raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans)) # All request groups must have resources (which is almost, but not # quite, verified by the orphan checks above). if not all(grp.resources for grp in by_suffix.values()): - msg = _("All request groups must specify resources.") + msg = "All request groups must specify resources." raise webob.exc.HTTPBadRequest(msg) # The above would still pass if there were no request groups if not by_suffix: - msg = _( + msg = ( "At least one request group (`resources` or `resources{N}`) " "is required.") raise webob.exc.HTTPBadRequest(msg) @@ -152,7 +151,7 @@ class RequestGroup(object): conflicting_traits.append('required%s: (%s)' % (suff, ', '.join(conflicts))) if conflicting_traits: - msg = _( + msg = ( 'Conflicting required and forbidden traits found in the ' 'following traits keys: %s') raise webob.exc.HTTPBadRequest( diff --git a/placement/objects/allocation_candidate.py b/placement/objects/allocation_candidate.py index 750e8493a..50dc4251e 100644 --- a/placement/objects/allocation_candidate.py +++ b/placement/objects/allocation_candidate.py @@ -24,7 +24,6 @@ from sqlalchemy import sql from placement.db.sqlalchemy import models from placement import db_api -from placement.i18n import _ from placement.objects import resource_provider as rp_obj from placement.objects import trait as trait_obj from placement import resource_class_cache as rc_cache @@ -674,9 +673,9 @@ def _consolidate_allocation_requests(areqs): if anchor_rp_uuid != areq.anchor_root_provider_uuid: # This should never happen. If it does, it's a dev bug. raise ValueError( - _("Expected every AllocationRequest in " - "`_consolidate_allocation_requests` to have the same " - "anchor!")) + "Expected every AllocationRequest in " + "`_consolidate_allocation_requests` to have the same " + "anchor!") for arr in areq.resource_requests: key = _rp_rc_key(arr.resource_provider, arr.resource_class) if key not in arrs_by_rp_rc: diff --git a/placement/objects/resource_class.py b/placement/objects/resource_class.py index 4f963b3d5..50e470ff5 100644 --- a/placement/objects/resource_class.py +++ b/placement/objects/resource_class.py @@ -23,7 +23,6 @@ from sqlalchemy import func from placement.db.sqlalchemy import models from placement import db_api from placement import exception -from placement.i18n import _ from placement import resource_class_cache as rc_cache _RC_TBL = models.ResourceClass.__table__ @@ -135,7 +134,7 @@ class ResourceClass(object): LOG.warning("Exceeded retry limit on ID generation while " "creating ResourceClass %(name)s", {'name': self.name}) - msg = _("creating resource class %s") % self.name + msg = "creating resource class %s" % self.name raise exception.MaxDBRetriesExceeded(action=msg) @staticmethod diff --git a/placement/objects/resource_provider.py b/placement/objects/resource_provider.py index 05caeb7d2..96fc77fa7 100644 --- a/placement/objects/resource_provider.py +++ b/placement/objects/resource_provider.py @@ -33,7 +33,6 @@ from sqlalchemy import sql from placement.db.sqlalchemy import models from placement import db_api from placement import exception -from placement.i18n import _ from placement.objects import inventory as inv_obj from placement.objects import rp_candidates from placement.objects import trait as trait_obj @@ -972,15 +971,15 @@ class ResourceProvider(object): if parent_uuid == self.uuid: raise exception.ObjectActionError( action='create', - reason=_('parent provider UUID cannot be same as UUID. ' - 'Please set parent provider UUID to None if ' - 'there is no parent.')) + reason='parent provider UUID cannot be same as UUID. ' + 'Please set parent provider UUID to None if ' + 'there is no parent.') parent_ids = provider_ids_from_uuid(context, parent_uuid) if parent_ids is None: raise exception.ObjectActionError( action='create', - reason=_('parent provider UUID does not exist.')) + reason='parent provider UUID does not exist.') parent_id = parent_ids.id root_id = parent_ids.root_id @@ -1075,13 +1074,13 @@ class ResourceProvider(object): if parent_ids is None: raise exception.ObjectActionError( action='create', - reason=_('parent provider UUID does not exist.')) + reason='parent provider UUID does not exist.') if (my_ids.parent_id is not None and my_ids.parent_id != parent_ids.id): raise exception.ObjectActionError( action='update', - reason=_('re-parenting a provider is not currently ' - 'allowed.')) + reason='re-parenting a provider is not currently ' + 'allowed.') if my_ids.parent_uuid is None: # So the user specifies a parent for an RP that doesn't # have one. We have to check that by this new parent we @@ -1096,8 +1095,8 @@ class ResourceProvider(object): if parent_uuid in rp_uuids_in_the_same_tree: raise exception.ObjectActionError( action='update', - reason=_('creating loop in the provider tree is ' - 'not allowed.')) + reason='creating loop in the provider tree is ' + 'not allowed.') updates['root_provider_id'] = parent_ids.root_id updates['parent_provider_id'] = parent_ids.id @@ -1106,8 +1105,8 @@ class ResourceProvider(object): if my_ids.parent_id is not None: raise exception.ObjectActionError( action='update', - reason=_('un-parenting a provider is not currently ' - 'allowed.')) + reason='un-parenting a provider is not currently ' + 'allowed.') db_rp = context.session.query(models.ResourceProvider).filter_by( id=id).first() @@ -1136,7 +1135,7 @@ class ResourceProvider(object): # parent provider and here... raise exception.ObjectActionError( action='update', - reason=_('parent provider UUID does not exist.')) + reason='parent provider UUID does not exist.') @staticmethod @db_api.placement_context_manager.writer # For online data migration @@ -1424,7 +1423,7 @@ def get_provider_ids_having_any_trait(ctx, traits): :raise ValueError: If traits is empty or None. """ if not traits: - raise ValueError(_('traits must not be empty')) + raise ValueError('traits must not be empty') rptt = sa.alias(_RP_TRAIT_TBL, name="rpt") sel = sa.select([rptt.c.resource_provider_id]) @@ -1447,7 +1446,7 @@ def _get_provider_ids_having_all_traits(ctx, required_traits): :raise ValueError: If required_traits is empty or None. """ if not required_traits: - raise ValueError(_('required_traits must not be empty')) + raise ValueError('required_traits must not be empty') rptt = sa.alias(_RP_TRAIT_TBL, name="rpt") sel = sa.select([rptt.c.resource_provider_id]) diff --git a/placement/objects/trait.py b/placement/objects/trait.py index 3c8cc54dd..f7f8db0be 100644 --- a/placement/objects/trait.py +++ b/placement/objects/trait.py @@ -23,7 +23,6 @@ import sqlalchemy as sa from placement.db.sqlalchemy import models from placement import db_api from placement import exception -from placement.i18n import _ _RP_TBL = models.ResourceProvider.__table__ @@ -192,8 +191,8 @@ def get_traits_by_provider_tree(ctx, root_ids): :param root_ids: list of root resource provider IDs """ if not root_ids: - raise ValueError(_("Expected root_ids to be a list of root resource " - "provider internal IDs, but got an empty list.")) + raise ValueError("Expected root_ids to be a list of root resource " + "provider internal IDs, but got an empty list.") rpt = sa.alias(_RP_TBL, name='rpt') rptt = sa.alias(_RP_TRAIT_TBL, name='rptt') @@ -220,8 +219,8 @@ def ids_from_names(ctx, names): :raise TraitNotFound: if any named trait doesn't exist in the database. """ if not names: - raise ValueError(_("Expected names to be a list of string trait " - "names, but got an empty list.")) + raise ValueError("Expected names to be a list of string trait " + "names, but got an empty list.") # Avoid SAWarnings about unicode types... unames = map(six.text_type, names) diff --git a/placement/util.py b/placement/util.py index 629e20f0f..32c63956f 100644 --- a/placement/util.py +++ b/placement/util.py @@ -22,7 +22,6 @@ from oslo_utils import uuidutils import webob from placement import errors -from placement.i18n import _ # NOTE(cdent): avoid cyclical import conflict between util and # microversion import placement.microversion @@ -60,7 +59,7 @@ def check_accept(*types): if not best_matches: type_string = ', '.join(types) raise webob.exc.HTTPNotAcceptable( - _('Only %(type)s is provided') % {'type': type_string}, + 'Only %(type)s is provided' % {'type': type_string}, json_formatter=json_error_formatter) return f(req) return decorated_function @@ -73,14 +72,14 @@ def extract_json(body, schema): data = jsonutils.loads(body) except ValueError as exc: raise webob.exc.HTTPBadRequest( - _('Malformed JSON: %(error)s') % {'error': exc}, + 'Malformed JSON: %(error)s' % {'error': exc}, json_formatter=json_error_formatter) try: jsonschema.validate(data, schema, format_checker=jsonschema.FormatChecker()) except jsonschema.ValidationError as exc: raise webob.exc.HTTPBadRequest( - _('JSON does not validate: %(error)s') % {'error': exc}, + 'JSON does not validate: %(error)s' % {'error': exc}, json_formatter=json_error_formatter) return data @@ -164,8 +163,8 @@ def require_content(content_type): if not req.content_type: req.content_type = 'None' raise webob.exc.HTTPUnsupportedMediaType( - _('The media type %(bad_type)s is not supported, ' - 'use %(good_type)s') % + 'The media type %(bad_type)s is not supported, ' + 'use %(good_type)s' % {'bad_type': req.content_type, 'good_type': content_type}, json_formatter=json_error_formatter) @@ -213,7 +212,7 @@ def validate_query_params(req, schema): format_checker=jsonschema.FormatChecker()) except (jsonschema.ValidationError, UnicodeDecodeError) as exc: raise webob.exc.HTTPBadRequest( - _('Invalid query string parameters: %(exc)s') % + 'Invalid query string parameters: %(exc)s' % {'exc': exc}) @@ -258,9 +257,9 @@ def normalize_resources_qs_param(qs): expected format. """ if qs.strip() == "": - msg = _('Badly formed resources parameter. Expected resources ' - 'query string parameter in form: ' - '?resources=VCPU:2,MEMORY_MB:1024. Got: empty string.') + msg = ('Badly formed resources parameter. Expected resources ' + 'query string parameter in form: ' + '?resources=VCPU:2,MEMORY_MB:1024. Got: empty string.') raise webob.exc.HTTPBadRequest(msg) result = {} @@ -269,24 +268,24 @@ def normalize_resources_qs_param(qs): try: rc_name, amount = rt.split(':') except ValueError: - msg = _('Badly formed resources parameter. Expected resources ' - 'query string parameter in form: ' - '?resources=VCPU:2,MEMORY_MB:1024. Got: %s.') + msg = ('Badly formed resources parameter. Expected resources ' + 'query string parameter in form: ' + '?resources=VCPU:2,MEMORY_MB:1024. Got: %s.') msg = msg % rt raise webob.exc.HTTPBadRequest(msg) try: amount = int(amount) except ValueError: - msg = _('Requested resource %(resource_name)s expected positive ' - 'integer amount. Got: %(amount)s.') + msg = ('Requested resource %(resource_name)s expected positive ' + 'integer amount. Got: %(amount)s.') msg = msg % { 'resource_name': rc_name, 'amount': amount, } raise webob.exc.HTTPBadRequest(msg) if amount < 1: - msg = _('Requested resource %(resource_name)s requires ' - 'amount >= 1. Got: %(amount)d.') + msg = ('Requested resource %(resource_name)s requires ' + 'amount >= 1. Got: %(amount)d.') msg = msg % { 'resource_name': rc_name, 'amount': amount, @@ -331,9 +330,9 @@ def normalize_traits_qs_param(val, allow_forbidden=False): if allow_forbidden: expected_form = 'HW_CPU_X86_VMX,!CUSTOM_MAGIC' if not all(trait and valid_trait(trait, allow_forbidden) for trait in ret): - msg = _("Invalid query string parameters: Expected 'required' " - "parameter value of the form: %(form)s. " - "Got: %(val)s") % {'form': expected_form, 'val': val} + msg = ("Invalid query string parameters: Expected 'required' " + "parameter value of the form: %(form)s. " + "Got: %(val)s") % {'form': expected_form, 'val': val} raise webob.exc.HTTPBadRequest(msg) return ret @@ -354,7 +353,7 @@ def normalize_member_of_qs_params(req, suffix=''): multi_member_of = want_version.matches((1, 24)) if not multi_member_of and len(req.GET.getall('member_of' + suffix)) > 1: raise webob.exc.HTTPBadRequest( - _('Multiple member_of%s parameters are not supported') % suffix) + 'Multiple member_of%s parameters are not supported' % suffix) values = [] for value in req.GET.getall('member_of' + suffix): values.append(normalize_member_of_qs_param(value)) @@ -375,8 +374,8 @@ def normalize_member_of_qs_param(value): expected format. """ if "," in value and not value.startswith("in:"): - msg = _("Multiple values for 'member_of' must be prefixed with the " - "'in:' keyword. Got: %s") % value + msg = ("Multiple values for 'member_of' must be prefixed with the " + "'in:' keyword. Got: %s") % value raise webob.exc.HTTPBadRequest(msg) if value.startswith('in:'): value = set(value[3:].split(',')) @@ -385,8 +384,8 @@ def normalize_member_of_qs_param(value): # Make sure the values are actually UUIDs. for aggr_uuid in value: if not uuidutils.is_uuid_like(aggr_uuid): - msg = _("Invalid query string parameters: Expected 'member_of' " - "parameter to contain valid UUID(s). Got: %s") % aggr_uuid + msg = ("Invalid query string parameters: Expected 'member_of' " + "parameter to contain valid UUID(s). Got: %s") % aggr_uuid raise webob.exc.HTTPBadRequest(msg) return value @@ -401,9 +400,9 @@ def normalize_in_tree_qs_params(value): """ ret = value.strip() if not uuidutils.is_uuid_like(ret): - msg = _("Invalid query string parameters: Expected 'in_tree' " - "parameter to be a format of uuid. " - "Got: %(val)s") % {'val': value} + msg = ("Invalid query string parameters: Expected 'in_tree' " + "parameter to be a format of uuid. " + "Got: %(val)s") % {'val': value} raise webob.exc.HTTPBadRequest(msg) return ret diff --git a/requirements.txt b/requirements.txt index b109c7c96..cb10e2c80 100644 --- a/requirements.txt +++ b/requirements.txt @@ -19,7 +19,6 @@ oslo.serialization!=2.19.1,>=2.18.0 # Apache-2.0 oslo.utils>=3.37.0 # Apache-2.0 oslo.db>=4.40.0 # Apache-2.0 oslo.policy>=1.35.0 # Apache-2.0 -oslo.i18n>=3.15.3 # Apache-2.0 oslo.middleware>=3.31.0 # Apache-2.0 oslo.upgradecheck>=0.2.0 # Apache-2.0 os-resource-classes>=0.2.0 # Apache-2.0 diff --git a/setup.cfg b/setup.cfg index 18dc1d3c7..7c8eaca58 100644 --- a/setup.cfg +++ b/setup.cfg @@ -51,21 +51,5 @@ tag_build = tag_date = 0 tag_svn_revision = 0 -[compile_catalog] -# TODO(cdent): Create translation infrastructure. -# See: https://docs.openstack.org/oslo.i18n/latest/user/usage.html -directory = placement/locale -domain = placement - -[update_catalog] -domain = placement -output_dir = placement/locale -input_file = placement/locale/placement.pot - -[extract_messages] -keywords = _ gettext ngettext l_ lazy_gettext -mapping_file = babel.cfg -output_file = placement/locale/placement.pot - [wheel] universal = 1 diff --git a/tox.ini b/tox.ini index ab2ff3c41..984a5e26b 100644 --- a/tox.ini +++ b/tox.ini @@ -156,9 +156,6 @@ exclude = .venv,.git,.tox,dist,*lib/python*,*egg,build,releasenotes # 14 is currently the most complex thing we have max-complexity=15 -[hacking] -import_exceptions = placement.i18n - [testenv:bindep] # Do not install any requirements. We want this to be fast and work even if # system dependencies are missing, since it's used to tell you what system