Remove use of oslo.i18n and translation

Nothing is being translated in placement so, for the sake of being clean
and tidy, this patch removes the framework for translation and the
import of oslo.i18n.

Originally the hope was we could remove the dependency on oslo.i18n and
Babel entirely to save some disk space but many other oslo-related libs
depend on oslo.i18n so they are present anyway. [1]

[1] http://lists.openstack.org/pipermail/openstack-discuss/2019-March/004220.html

Change-Id: Ia965d028b6f7c9f04d1f29beb12f4862585631d5
This commit is contained in:
Chris Dent 2019-03-25 12:44:11 +00:00
parent c6a23a3037
commit da1a588b8d
24 changed files with 236 additions and 315 deletions

View File

@ -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]

View File

@ -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),
)

View File

@ -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."

View File

@ -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)

View File

@ -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:

View File

@ -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)

View File

@ -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))

View File

@ -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)

View File

@ -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

View File

@ -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(

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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

View File

@ -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)

View File

@ -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(

View File

@ -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:
</