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 import context
from placement.db.sqlalchemy import migration from placement.db.sqlalchemy import migration
from placement import db_api from placement import db_api
from placement.i18n import _
from placement.objects import consumer as consumer_obj from placement.objects import consumer as consumer_obj
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
@ -86,13 +85,13 @@ class DbCommands(object):
except ValueError: except ValueError:
max_count = -1 max_count = -1
if 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 return 127
limited = True limited = True
else: else:
max_count = 50 max_count = 50
limited = False limited = False
print(_('Running batches of %i until complete') % max_count) print('Running batches of %i until complete' % max_count)
ran = None ran = None
migration_info = collections.OrderedDict() migration_info = collections.OrderedDict()
@ -113,7 +112,7 @@ class DbCommands(object):
break break
t = prettytable.PrettyTable( t = prettytable.PrettyTable(
[_('Migration'), _('Total Found'), _('Completed')]) ['Migration', 'Total Found', 'Completed'])
for name, info in migration_info.items(): for name, info in migration_info.items():
t.add_row([name, info[0], info[1]]) t.add_row([name, info[0], info[1]])
print(t) print(t)
@ -123,8 +122,8 @@ class DbCommands(object):
# to be done, and that work may resolve dependencies for the failing # to be done, and that work may resolve dependencies for the failing
# migrations. # migrations.
if exceptions and not (limited and ran): if exceptions and not (limited and ran):
print(_("Some migrations failed unexpectedly. Check log for " print("Some migrations failed unexpectedly. Check log for "
"details.")) "details.")
return 2 return 2
# TODO(mriedem): Potentially add another return code for # TODO(mriedem): Potentially add another return code for
@ -141,7 +140,7 @@ class DbCommands(object):
try: try:
found, done = migration_meth(ctxt, count) found, done = migration_meth(ctxt, count)
except Exception: except Exception:
msg = (_("Error attempting to run %(method)s") % dict( msg = ("Error attempting to run %(method)s" % dict(
method=migration_meth)) method=migration_meth))
print(msg) print(msg)
LOG.exception(msg) LOG.exception(msg)
@ -150,8 +149,8 @@ class DbCommands(object):
name = migration_meth.__name__ name = migration_meth.__name__
if found: if found:
print(_('%(total)i rows matched query %(meth)s, %(done)i ' print('%(total)i rows matched query %(meth)s, %(done)i '
'migrated') % {'total': found, 'migrated' % {'total': found,
'meth': name, 'meth': name,
'done': done}) 'done': done})
# This is the per-migration method result for this batch, and # This is the per-migration method result for this batch, and
@ -178,21 +177,21 @@ def add_db_command_parsers(subparsers, config):
parser.set_defaults(func=parser.print_help) parser.set_defaults(func=parser.print_help)
db_parser = parser.add_subparsers(description='database commands') 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 = db_parser.add_parser('sync', help=help, description=help)
sync_parser.set_defaults(func=command_object.db_sync) 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_parser = db_parser.add_parser(
'version', help=help, description=help) 'version', help=help, description=help)
version_parser.set_defaults(func=command_object.db_version) 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 = 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) 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_dm_parser = db_parser.add_parser(
'online_data_migrations', help=help, description=help) 'online_data_migrations', help=help, description=help)
online_dm_parser.add_argument( online_dm_parser.add_argument(
@ -208,7 +207,7 @@ def setup_commands(config):
add_db_cmd_parsers = functools.partial( add_db_cmd_parsers = functools.partial(
add_db_command_parsers, config=config) add_db_command_parsers, config=config)
command_opt = cfg.SubCommandOpt( 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) handler=add_db_cmd_parsers)
return [command_opt] return [command_opt]

View File

@ -20,7 +20,6 @@ from placement import conf
from placement import context from placement import context
from placement.db.sqlalchemy import models from placement.db.sqlalchemy import models
from placement import db_api from placement import db_api
from placement.i18n import _
class Checks(upgradecheck.UpgradeCommands): class Checks(upgradecheck.UpgradeCommands):
@ -57,10 +56,10 @@ class Checks(upgradecheck.UpgradeCommands):
if self._check_missing_root_ids(self.ctxt): if self._check_missing_root_ids(self.ctxt):
return upgradecheck.Result( return upgradecheck.Result(
upgradecheck.Code.WARNING, upgradecheck.Code.WARNING,
details=_('There is at least one resource provider table ' details='There is at least one resource provider table '
'record which misses its root provider id. ' 'record which misses its root provider id. '
'Run the "placement-manage db ' 'Run the "placement-manage db '
'online_data_migrations" command.')) 'online_data_migrations" command.')
return upgradecheck.Result(upgradecheck.Code.SUCCESS) return upgradecheck.Result(upgradecheck.Code.SUCCESS)
@db_api.placement_context_manager.reader @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. # a warning and tell the user to run the online data migrations.
return upgradecheck.Result( return upgradecheck.Result(
upgradecheck.Code.WARNING, upgradecheck.Code.WARNING,
details=_('There are %s incomplete consumers table records ' details='There are %s incomplete consumers table records '
'for existing allocations. Run the ' 'for existing allocations. Run the '
'"placement-manage db online_data_migrations" ' '"placement-manage db online_data_migrations" '
'command.') % missing_consumer_count) 'command.' % missing_consumer_count)
# No missing consumers (or no allocations [fresh install?]) so it's OK. # No missing consumers (or no allocations [fresh install?]) so it's OK.
return upgradecheck.Result(upgradecheck.Code.SUCCESS) return upgradecheck.Result(upgradecheck.Code.SUCCESS)
@ -111,8 +110,8 @@ class Checks(upgradecheck.UpgradeCommands):
# in the returned Result's "details" attribute. The # in the returned Result's "details" attribute. The
# summary will be rolled up at the end of the check() method. # summary will be rolled up at the end of the check() method.
_upgrade_checks = ( _upgrade_checks = (
(_('Missing Root Provider IDs'), _check_root_provider_ids), ('Missing Root Provider IDs', _check_root_provider_ids),
(_('Incomplete Consumers'), _check_incomplete_consumers), ('Incomplete Consumers', _check_incomplete_consumers),
) )

View File

@ -13,8 +13,6 @@
from oslo_log import log as logging from oslo_log import log as logging
from placement.i18n import _
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -27,7 +25,7 @@ class _BaseException(Exception):
with the keyword arguments provided to the constructor. 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): def __init__(self, message=None, **kwargs):
self.kwargs = kwargs self.kwargs = kwargs
@ -58,53 +56,53 @@ class _BaseException(Exception):
class NotFound(_BaseException): class NotFound(_BaseException):
msg_fmt = _("Resource could not be found.") msg_fmt = "Resource could not be found."
class Exists(_BaseException): class Exists(_BaseException):
msg_fmt = _("Resource already exists.") msg_fmt = "Resource already exists."
class InvalidInventory(_BaseException): class InvalidInventory(_BaseException):
msg_fmt = _("Inventory for '%(resource_class)s' on " msg_fmt = ("Inventory for '%(resource_class)s' on "
"resource provider '%(resource_provider)s' invalid.") "resource provider '%(resource_provider)s' invalid.")
class CannotDeleteParentResourceProvider(_BaseException): class CannotDeleteParentResourceProvider(_BaseException):
msg_fmt = _("Cannot delete resource provider that is a parent of " msg_fmt = ("Cannot delete resource provider that is a parent of "
"another. Delete child providers first.") "another. Delete child providers first.")
class ConcurrentUpdateDetected(_BaseException): class ConcurrentUpdateDetected(_BaseException):
msg_fmt = _("Another thread concurrently updated the data. " msg_fmt = ("Another thread concurrently updated the data. "
"Please retry your update") "Please retry your update")
class ResourceProviderConcurrentUpdateDetected(ConcurrentUpdateDetected): class ResourceProviderConcurrentUpdateDetected(ConcurrentUpdateDetected):
msg_fmt = _("Another thread concurrently updated the resource provider " msg_fmt = ("Another thread concurrently updated the resource provider "
"data. Please retry your update") "data. Please retry your update")
class InvalidAllocationCapacityExceeded(InvalidInventory): class InvalidAllocationCapacityExceeded(InvalidInventory):
msg_fmt = _("Unable to create allocation for '%(resource_class)s' on " msg_fmt = ("Unable to create allocation for '%(resource_class)s' on "
"resource provider '%(resource_provider)s'. The requested " "resource provider '%(resource_provider)s'. The requested "
"amount would exceed the capacity.") "amount would exceed the capacity.")
class InvalidAllocationConstraintsViolated(InvalidInventory): class InvalidAllocationConstraintsViolated(InvalidInventory):
msg_fmt = _("Unable to create allocation for '%(resource_class)s' on " msg_fmt = ("Unable to create allocation for '%(resource_class)s' on "
"resource provider '%(resource_provider)s'. The requested " "resource provider '%(resource_provider)s'. The requested "
"amount would violate inventory constraints.") "amount would violate inventory constraints.")
class InvalidInventoryCapacity(InvalidInventory): class InvalidInventoryCapacity(InvalidInventory):
msg_fmt = _("Invalid inventory for '%(resource_class)s' on " msg_fmt = ("Invalid inventory for '%(resource_class)s' on "
"resource provider '%(resource_provider)s'. " "resource provider '%(resource_provider)s'. "
"The reserved value is greater than or equal to total.") "The reserved value is greater than or equal to total.")
class InvalidInventoryCapacityReservedCanBeTotal(InvalidInventoryCapacity): class InvalidInventoryCapacityReservedCanBeTotal(InvalidInventoryCapacity):
msg_fmt = _("Invalid inventory for '%(resource_class)s' on " msg_fmt = ("Invalid inventory for '%(resource_class)s' on "
"resource provider '%(resource_provider)s'. " "resource provider '%(resource_provider)s'. "
"The reserved value is greater than total.") "The reserved value is greater than total.")
@ -112,87 +110,87 @@ class InvalidInventoryCapacityReservedCanBeTotal(InvalidInventoryCapacity):
# An exception with this name is used on both sides of the placement/ # An exception with this name is used on both sides of the placement/
# nova interaction. # nova interaction.
class InventoryInUse(InvalidInventory): class InventoryInUse(InvalidInventory):
msg_fmt = _("Inventory for '%(resource_classes)s' on " msg_fmt = ("Inventory for '%(resource_classes)s' on "
"resource provider '%(resource_provider)s' in use.") "resource provider '%(resource_provider)s' in use.")
class InventoryWithResourceClassNotFound(NotFound): 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): class MaxDBRetriesExceeded(_BaseException):
msg_fmt = _("Max retries of DB transaction exceeded attempting to " msg_fmt = ("Max retries of DB transaction exceeded attempting to "
"perform %(action)s.") "perform %(action)s.")
class ObjectActionError(_BaseException): 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): 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): 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): 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): class ResourceClassExists(_BaseException):
msg_fmt = _("Resource class %(resource_class)s already exists.") msg_fmt = "Resource class %(resource_class)s already exists."
class ResourceClassInUse(_BaseException): class ResourceClassInUse(_BaseException):
msg_fmt = _("Cannot delete resource class %(resource_class)s. " msg_fmt = ("Cannot delete resource class %(resource_class)s. "
"Class is in use in inventory.") "Class is in use in inventory.")
class ResourceClassNotFound(NotFound): class ResourceClassNotFound(NotFound):
msg_fmt = _("No such resource class %(resource_class)s.") msg_fmt = "No such resource class %(resource_class)s."
class ResourceProviderInUse(_BaseException): class ResourceProviderInUse(_BaseException):
msg_fmt = _("Resource provider has allocations.") msg_fmt = "Resource provider has allocations."
class TraitCannotDeleteStandard(_BaseException): class TraitCannotDeleteStandard(_BaseException):
msg_fmt = _("Cannot delete standard trait %(name)s.") msg_fmt = "Cannot delete standard trait %(name)s."
class TraitExists(_BaseException): class TraitExists(_BaseException):
msg_fmt = _("The Trait %(name)s already exists") msg_fmt = "The Trait %(name)s already exists"
class TraitInUse(_BaseException): 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): class TraitNotFound(NotFound):
msg_fmt = _("No such trait(s): %(names)s.") msg_fmt = "No such trait(s): %(names)s."
class ProjectNotFound(NotFound): class ProjectNotFound(NotFound):
msg_fmt = _("No such project(s): %(external_id)s.") msg_fmt = "No such project(s): %(external_id)s."
class ProjectExists(Exists): class ProjectExists(Exists):
msg_fmt = _("The project %(external_id)s already exists.") msg_fmt = "The project %(external_id)s already exists."
class UserNotFound(NotFound): class UserNotFound(NotFound):
msg_fmt = _("No such user(s): %(external_id)s.") msg_fmt = "No such user(s): %(external_id)s."
class UserExists(Exists): class UserExists(Exists):
msg_fmt = _("The user %(external_id)s already exists.") msg_fmt = "The user %(external_id)s already exists."
class ConsumerNotFound(NotFound): class ConsumerNotFound(NotFound):
msg_fmt = _("No such consumer(s): %(uuid)s.") msg_fmt = "No such consumer(s): %(uuid)s."
class ConsumerExists(Exists): 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 root
from placement.handlers import trait from placement.handlers import trait
from placement.handlers import usage from placement.handlers import usage
from placement.i18n import _
from placement import util from placement import util
LOG = logging.getLogger(__name__) LOG = logging.getLogger(__name__)
@ -166,7 +165,7 @@ def handle_405(environ, start_response):
headers['allow'] = str(_methods) headers['allow'] = str(_methods)
# Use Exception class as WSGI Application. We don't want to raise here. # Use Exception class as WSGI Application. We don't want to raise here.
response = webob.exc.HTTPMethodNotAllowed( 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) headers=headers, json_formatter=util.json_error_formatter)
return response(environ, start_response) return response(environ, start_response)
@ -206,11 +205,11 @@ class PlacementHandler(object):
try: try:
if clen and (int(clen) > 0) and not environ.get('CONTENT_TYPE'): if clen and (int(clen) > 0) and not environ.get('CONTENT_TYPE'):
raise webob.exc.HTTPBadRequest( 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) json_formatter=util.json_error_formatter)
except ValueError as exc: except ValueError as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('content-length header must be an integer'), 'content-length header must be an integer',
json_formatter=util.json_error_formatter) json_formatter=util.json_error_formatter)
try: try:
return dispatch(environ, start_response, self._map) return dispatch(environ, start_response, self._map)

View File

@ -19,7 +19,6 @@ import webob
from placement import errors from placement import errors
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
from placement.policies import aggregate as policies from placement.policies import aggregate as policies
@ -72,11 +71,11 @@ def _set_aggregates(resource_provider, aggregate_uuids,
aggregate_uuids, increment_generation=increment_generation) aggregate_uuids, increment_generation=increment_generation)
except exception.ConcurrentUpdateDetected as exc: except exception.ConcurrentUpdateDetected as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Update conflict: %(error)s') % {'error': exc}, 'Update conflict: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except db_exc.DBDuplicateEntry as exc: except db_exc.DBDuplicateEntry as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Update conflict: %(error)s') % {'error': exc}) 'Update conflict: %(error)s' % {'error': exc})
@wsgi_wrapper.PlacementWsgify @wsgi_wrapper.PlacementWsgify
@ -121,8 +120,8 @@ def set_aggregates(req):
rp_gen = data['resource_provider_generation'] rp_gen = data['resource_provider_generation']
if resource_provider.generation != rp_gen: if resource_provider.generation != rp_gen:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_("Resource provider's generation already changed. Please " "Resource provider's generation already changed. Please "
"update the generation and try again."), "update the generation and try again.",
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
aggregate_uuids = data['aggregates'] aggregate_uuids = data['aggregates']
else: else:

View File

@ -25,7 +25,6 @@ import webob
from placement import errors from placement import errors
from placement import exception from placement import exception
from placement.handlers import util as data_util from placement.handlers import util as data_util
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import allocation as alloc_obj from placement.objects import allocation as alloc_obj
from placement.objects import resource_provider as rp_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) rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'rp_uuid': uuid, 'error': exc})
allocs = alloc_obj.get_all_by_resource_provider(context, rp) 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) res[rp_uuid] = rp_obj.ResourceProvider.get_by_uuid(ctx, rp_uuid)
except exception.NotFound: except exception.NotFound:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_("Allocation for resource provider '%(rp_uuid)s' " "Allocation for resource provider '%(rp_uuid)s' "
"that does not exist.") % "that does not exist." % {'rp_uuid': rp_uuid})
{'rp_uuid': rp_uuid})
return res return res
@ -376,7 +374,7 @@ def _set_allocations_for_consumer(req, schema):
consumer_uuid = util.wsgi_path_item(req.environ, 'consumer_uuid') consumer_uuid = util.wsgi_path_item(req.environ, 'consumer_uuid')
if not uuidutils.is_uuid_like(consumer_uuid): if not uuidutils.is_uuid_like(consumer_uuid):
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Malformed consumer_uuid: %(consumer_uuid)s') % 'Malformed consumer_uuid: %(consumer_uuid)s' %
{'consumer_uuid': consumer_uuid}) {'consumer_uuid': consumer_uuid})
consumer_uuid = str(uuid.UUID(consumer_uuid)) consumer_uuid = str(uuid.UUID(consumer_uuid))
data = util.extract_json(req.body, schema) data = util.extract_json(req.body, schema)
@ -447,15 +445,15 @@ def _set_allocations_for_consumer(req, schema):
# capacity limits have been exceeded. # capacity limits have been exceeded.
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_("Unable to allocate inventory for consumer %(consumer_uuid)s: " "Unable to allocate inventory for consumer %(consumer_uuid)s: "
"%(error)s") % {'consumer_uuid': consumer_uuid, 'error': exc}) "%(error)s" % {'consumer_uuid': consumer_uuid, 'error': exc})
except exception.InvalidInventory as exc: except exception.InvalidInventory as exc:
raise webob.exc.HTTPConflict( 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: except exception.ConcurrentUpdateDetected as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Inventory and/or allocations changed while attempting to ' 'Inventory and/or allocations changed while attempting to '
'allocate: %(error)s') % {'error': exc}, 'allocate: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
req.response.status = 204 req.response.status = 204
@ -523,17 +521,17 @@ def set_allocations(req):
_create_allocations(allocations) _create_allocations(allocations)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPBadRequest( 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: except exception.InvalidInventory as exc:
# InvalidInventory is a parent for several exceptions that # InvalidInventory is a parent for several exceptions that
# indicate either that Inventory is not present, or that # indicate either that Inventory is not present, or that
# capacity limits have been exceeded. # capacity limits have been exceeded.
raise webob.exc.HTTPConflict( 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: except exception.ConcurrentUpdateDetected as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Inventory and/or allocations changed while attempting to ' 'Inventory and/or allocations changed while attempting to '
'allocate: %(error)s') % {'error': exc}, 'allocate: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
req.response.status = 204 req.response.status = 204
@ -556,12 +554,11 @@ def delete_allocations(req):
# activity. In that case, delete_all() will throw a NotFound exception. # activity. In that case, delete_all() will throw a NotFound exception.
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( raise webob.exc.HTTPNotFound(
_("Allocation for consumer with id %(id)s not found. error: " "Allocation for consumer with id %(id)s not found. error: "
"%(error)s") % "%(error)s" % {'id': consumer_uuid, 'error': exc})
{'id': consumer_uuid, 'error': exc})
else: else:
raise webob.exc.HTTPNotFound( raise webob.exc.HTTPNotFound(
_("No allocations for consumer '%(consumer_uuid)s'") % "No allocations for consumer '%(consumer_uuid)s'" %
{'consumer_uuid': consumer_uuid}) {'consumer_uuid': consumer_uuid})
LOG.debug("Successfully deleted allocations %s", allocations) LOG.debug("Successfully deleted allocations %s", allocations)

View File

@ -21,7 +21,6 @@ import six
import webob import webob
from placement import exception from placement import exception
from placement.i18n import _
from placement import lib from placement import lib
from placement import microversion from placement import microversion
from placement.objects import allocation_candidate as ac_obj from placement.objects import allocation_candidate as ac_obj
@ -310,15 +309,15 @@ def list_allocation_candidates(req):
# specified. # specified.
if len([rg for rg in requests.values() if rg.use_same_provider]) > 1: if len([rg for rg in requests.values() if rg.use_same_provider]) > 1:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('The "group_policy" parameter is required when specifying ' 'The "group_policy" parameter is required when specifying '
'more than one "resources{N}" parameter.')) 'more than one "resources{N}" parameter.')
try: try:
cands = ac_obj.AllocationCandidates.get_by_requests( cands = ac_obj.AllocationCandidates.get_by_requests(
context, requests, limit=limit, group_policy=group_policy) context, requests, limit=limit, group_policy=group_policy)
except exception.ResourceClassNotFound as exc: except exception.ResourceClassNotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Invalid resource class in resources parameter: %(error)s') % 'Invalid resource class in resources parameter: %(error)s' %
{'error': exc}) {'error': exc})
except exception.TraitNotFound as exc: except exception.TraitNotFound as exc:
raise webob.exc.HTTPBadRequest(six.text_type(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.db import constants as db_const
from placement import errors from placement import errors
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import inventory as inv_obj from placement.objects import inventory as inv_obj
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
@ -88,8 +87,8 @@ def make_inventory_object(resource_provider, resource_class, **data):
resource_class=resource_class, **data) resource_class=resource_class, **data)
except (ValueError, TypeError) as exc: except (ValueError, TypeError) as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Bad inventory %(class)s for resource provider ' 'Bad inventory %(class)s for resource provider '
'%(rp_uuid)s: %(error)s') % {'class': resource_class, '%(rp_uuid)s: %(error)s' % {'class': resource_class,
'rp_uuid': resource_provider.uuid, 'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
return inventory return inventory
@ -204,13 +203,13 @@ def create_inventory(req):
except (exception.ConcurrentUpdateDetected, except (exception.ConcurrentUpdateDetected,
db_exc.DBDuplicateEntry) as exc: db_exc.DBDuplicateEntry) as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Update conflict: %(error)s') % {'error': exc}, 'Update conflict: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except (exception.InvalidInventoryCapacity, except (exception.InvalidInventoryCapacity,
exception.NotFound) as exc: exception.NotFound) as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Unable to create inventory for resource provider ' 'Unable to create inventory for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
response = req.response response = req.response
@ -241,12 +240,12 @@ def delete_inventory(req):
except (exception.ConcurrentUpdateDetected, except (exception.ConcurrentUpdateDetected,
exception.InventoryInUse) as exc: exception.InventoryInUse) as exc:
raise webob.exc.HTTPConflict( 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}, {'class': resource_class, 'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'class': resource_class, 'error': exc})
response = req.response response = req.response
@ -270,7 +269,7 @@ def get_inventories(req):
rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid) rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'uuid': uuid, 'error': exc})
inv_list = inv_obj.get_all_by_resource_provider(context, rp) 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) rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'uuid': uuid, 'error': exc})
inv_list = inv_obj.get_all_by_resource_provider(context, rp) inv_list = inv_obj.get_all_by_resource_provider(context, rp)
@ -302,7 +301,7 @@ def get_inventory(req):
if not inventory: if not inventory:
raise webob.exc.HTTPNotFound( 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}) {'class': resource_class, 'rp_uuid': uuid})
return _send_inventory(req, rp, inventory) return _send_inventory(req, rp, inventory)
@ -333,7 +332,7 @@ def set_inventories(req):
data = _extract_inventories(req.body, schema.PUT_INVENTORY_SCHEMA) data = _extract_inventories(req.body, schema.PUT_INVENTORY_SCHEMA)
if data['resource_provider_generation'] != resource_provider.generation: if data['resource_provider_generation'] != resource_provider.generation:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('resource provider generation conflict'), 'resource provider generation conflict',
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
inventories = [] inventories = []
@ -348,28 +347,28 @@ def set_inventories(req):
resource_provider.set_inventory(inventories) resource_provider.set_inventory(inventories)
except exception.ResourceClassNotFound as exc: except exception.ResourceClassNotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Unknown resource class in inventory for resource provider ' 'Unknown resource class in inventory for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
except exception.InventoryWithResourceClassNotFound as exc: except exception.InventoryWithResourceClassNotFound as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Race condition detected when setting inventory. No inventory ' 'Race condition detected when setting inventory. No inventory '
'record with resource class for resource provider ' 'record with resource class for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
except (exception.ConcurrentUpdateDetected, except (exception.ConcurrentUpdateDetected,
db_exc.DBDuplicateEntry) as exc: db_exc.DBDuplicateEntry) as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('update conflict: %(error)s') % {'error': exc}, 'update conflict: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except exception.InventoryInUse as exc: except exception.InventoryInUse as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('update conflict: %(error)s') % {'error': exc}, 'update conflict: %(error)s' % {'error': exc},
comment=errors.INVENTORY_INUSE) comment=errors.INVENTORY_INUSE)
except exception.InvalidInventoryCapacity as exc: except exception.InvalidInventoryCapacity as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Unable to update inventory for resource provider ' 'Unable to update inventory for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
return _send_inventories(req, resource_provider, inventories) return _send_inventories(req, resource_provider, inventories)
@ -395,9 +394,9 @@ def delete_inventories(req):
resource_provider.set_inventory([]) resource_provider.set_inventory([])
except exception.ConcurrentUpdateDetected: except exception.ConcurrentUpdateDetected:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Unable to delete inventory for resource provider ' 'Unable to delete inventory for resource provider '
'%(rp_uuid)s because the inventory was updated by ' '%(rp_uuid)s because the inventory was updated by '
'another process. Please retry your request.') % 'another process. Please retry your request.' %
{'rp_uuid': resource_provider.uuid}, {'rp_uuid': resource_provider.uuid},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except exception.InventoryInUse as ex: except exception.InventoryInUse as ex:
@ -434,7 +433,7 @@ def update_inventory(req):
data = _extract_inventory(req.body, schema.BASE_INVENTORY_SCHEMA) data = _extract_inventory(req.body, schema.BASE_INVENTORY_SCHEMA)
if data['resource_provider_generation'] != resource_provider.generation: if data['resource_provider_generation'] != resource_provider.generation:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('resource provider generation conflict'), 'resource provider generation conflict',
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
inventory = make_inventory_object(resource_provider, inventory = make_inventory_object(resource_provider,
@ -448,17 +447,17 @@ def update_inventory(req):
except (exception.ConcurrentUpdateDetected, except (exception.ConcurrentUpdateDetected,
db_exc.DBDuplicateEntry) as exc: db_exc.DBDuplicateEntry) as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('update conflict: %(error)s') % {'error': exc}, 'update conflict: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
except exception.InventoryWithResourceClassNotFound as exc: except exception.InventoryWithResourceClassNotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('No inventory record with resource class for resource provider ' 'No inventory record with resource class for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
except exception.InvalidInventoryCapacity as exc: except exception.InvalidInventoryCapacity as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Unable to update inventory for resource provider ' 'Unable to update inventory for resource provider '
'%(rp_uuid)s: %(error)s') % {'rp_uuid': resource_provider.uuid, '%(rp_uuid)s: %(error)s' % {'rp_uuid': resource_provider.uuid,
'error': exc}) 'error': exc})
return _send_inventory(req, resource_provider, inventory) 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. # extracted from the handler to a shared module.
from placement.handlers import allocation from placement.handlers import allocation
from placement.handlers import inventory from placement.handlers import inventory
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import reshaper from placement.objects import reshaper
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
@ -60,16 +59,16 @@ def reshape(req):
context, rp_uuid) context, rp_uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Resource provider %(rp_uuid)s in inventories not found: ' 'Resource provider %(rp_uuid)s in inventories not found: '
'%(error)s') % {'rp_uuid': rp_uuid, 'error': exc}, '%(error)s' % {'rp_uuid': rp_uuid, 'error': exc},
comment=errors.RESOURCE_PROVIDER_NOT_FOUND) comment=errors.RESOURCE_PROVIDER_NOT_FOUND)
# Do an early generation check. # Do an early generation check.
generation = inventory_data['resource_provider_generation'] generation = inventory_data['resource_provider_generation']
if generation != resource_provider.generation: if generation != resource_provider.generation:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('resource provider generation conflict for provider %(rp)s: ' 'resource provider generation conflict for provider %(rp)s: '
'actual: %(actual)s, given: %(given)s') % 'actual: %(actual)s, given: %(given)s' %
{'rp': rp_uuid, {'rp': rp_uuid,
'actual': resource_provider.generation, 'actual': resource_provider.generation,
'given': generation}, 'given': generation},
@ -108,21 +107,21 @@ def reshape(req):
# places in reshape(). # places in reshape().
except exception.ConcurrentUpdateDetected as exc: except exception.ConcurrentUpdateDetected as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('update conflict: %(error)s') % {'error': exc}, 'update conflict: %(error)s' % {'error': exc},
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
# A NotFound here means a resource class that does not exist was named # A NotFound here means a resource class that does not exist was named
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPBadRequest( 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)... # Distinguish inventory in use (has allocations on it)...
except exception.InventoryInUse as exc: except exception.InventoryInUse as exc:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('update conflict: %(error)s') % {'error': exc}, 'update conflict: %(error)s' % {'error': exc},
comment=errors.INVENTORY_INUSE) comment=errors.INVENTORY_INUSE)
# ...from allocations which won't fit for a variety of reasons. # ...from allocations which won't fit for a variety of reasons.
except exception.InvalidInventory as exc: except exception.InvalidInventory as exc:
raise webob.exc.HTTPConflict( 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.status = 204
req.response.content_type = None req.response.content_type = None

View File

@ -17,7 +17,6 @@ from oslo_utils import timeutils
import webob import webob
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import resource_class as rc_obj from placement.objects import resource_class as rc_obj
from placement.policies import resource_class as policies from placement.policies import resource_class as policies
@ -71,13 +70,13 @@ def create_resource_class(req):
rc.create() rc.create()
except exception.ResourceClassExists: except exception.ResourceClassExists:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Conflicting resource class already exists: %(name)s') % 'Conflicting resource class already exists: %(name)s' %
{'name': data['name']}) {'name': data['name']})
except exception.MaxDBRetriesExceeded: except exception.MaxDBRetriesExceeded:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Max retries of DB transaction exceeded attempting ' 'Max retries of DB transaction exceeded attempting '
'to create resource class: %(name)s, please ' 'to create resource class: %(name)s, please '
'try again.') % 'try again.' %
{'name': data['name']}) {'name': data['name']})
req.response.location = util.resource_class_url(req.environ, rc) req.response.location = util.resource_class_url(req.environ, rc)
@ -102,10 +101,10 @@ def delete_resource_class(req):
rc.destroy() rc.destroy()
except exception.ResourceClassCannotDeleteStandard as exc: except exception.ResourceClassCannotDeleteStandard as exc:
raise webob.exc.HTTPBadRequest( 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: except exception.ResourceClassInUse as exc:
raise webob.exc.HTTPConflict( 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.status = 204
req.response.content_type = None req.response.content_type = None
return req.response return req.response
@ -190,11 +189,11 @@ def update_resource_class(req):
rc.save() rc.save()
except exception.ResourceClassExists: except exception.ResourceClassExists:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Resource class already exists: %(name)s') % 'Resource class already exists: %(name)s' %
{'name': rc.name}) {'name': rc.name})
except exception.ResourceClassCannotUpdateStandard: except exception.ResourceClassCannotUpdateStandard:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Cannot update standard resource class %(rp_name)s') % 'Cannot update standard resource class %(rp_name)s' %
{'rp_name': name}) {'rp_name': name})
req.response.body = encodeutils.to_utf8(jsonutils.dumps( req.response.body = encodeutils.to_utf8(jsonutils.dumps(

View File

@ -22,7 +22,6 @@ import webob
from placement import errors from placement import errors
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
from placement.policies import resource_provider as policies from placement.policies import resource_provider as policies
@ -109,13 +108,13 @@ def create_resource_provider(req):
duplicate = ', '.join( duplicate = ', '.join(
['%s: %s' % (column, data[column]) for column in exc.columns]) ['%s: %s' % (column, data[column]) for column in exc.columns])
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Conflicting resource provider %(duplicate)s already exists.') % 'Conflicting resource provider %(duplicate)s already exists.' %
{'duplicate': duplicate}, {'duplicate': duplicate},
comment=errors.DUPLICATE_NAME) comment=errors.DUPLICATE_NAME)
except exception.ObjectActionError as exc: except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Unable to create resource provider "%(name)s", %(rp_uuid)s: ' 'Unable to create resource provider "%(name)s", %(rp_uuid)s: '
'%(error)s') % '%(error)s' %
{'name': data['name'], 'rp_uuid': data['uuid'], 'error': exc}) {'name': data['name'], 'rp_uuid': data['uuid'], 'error': exc})
req.response.location = util.resource_provider_url( req.response.location = util.resource_provider_url(
@ -149,16 +148,16 @@ def delete_resource_provider(req):
resource_provider.destroy() resource_provider.destroy()
except exception.ResourceProviderInUse as exc: except exception.ResourceProviderInUse as exc:
raise webob.exc.HTTPConflict( 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}, {'rp_uuid': uuid, 'error': exc},
comment=errors.PROVIDER_IN_USE) comment=errors.PROVIDER_IN_USE)
except exception.NotFound: except exception.NotFound:
raise webob.exc.HTTPNotFound( 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: except exception.CannotDeleteParentResourceProvider:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_("Unable to delete parent resource provider %(rp_uuid)s: " "Unable to delete parent resource provider %(rp_uuid)s: "
"It has child resource providers.") % {'rp_uuid': uuid}, "It has child resource providers." % {'rp_uuid': uuid},
comment=errors.PROVIDER_CANNOT_DELETE_PARENT) comment=errors.PROVIDER_CANNOT_DELETE_PARENT)
req.response.status = 204 req.response.status = 204
req.response.content_type = None req.response.content_type = None
@ -239,11 +238,11 @@ def list_resource_providers(req):
resource_providers = rp_obj.get_all_by_filters(context, filters) resource_providers = rp_obj.get_all_by_filters(context, filters)
except exception.ResourceClassNotFound as exc: except exception.ResourceClassNotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Invalid resource class in resources parameter: %(error)s') % 'Invalid resource class in resources parameter: %(error)s' %
{'error': exc}) {'error': exc})
except exception.TraitNotFound as exc: except exception.TraitNotFound as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Invalid trait(s) in "required" parameter: %(error)s') % 'Invalid trait(s) in "required" parameter: %(error)s' %
{'error': exc}) {'error': exc})
response = req.response response = req.response
@ -288,12 +287,12 @@ def update_resource_provider(req):
resource_provider.save() resource_provider.save()
except db_exc.DBDuplicateEntry: except db_exc.DBDuplicateEntry:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('Conflicting resource provider %(name)s already exists.') % 'Conflicting resource provider %(name)s already exists.' %
{'name': data['name']}, {'name': data['name']},
comment=errors.DUPLICATE_NAME) comment=errors.DUPLICATE_NAME)
except exception.ObjectActionError as exc: except exception.ObjectActionError as exc:
raise webob.exc.HTTPBadRequest( 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}) {'rp_uuid': uuid, 'error': exc})
response = req.response response = req.response

View File

@ -19,7 +19,6 @@ import webob
from placement import errors from placement import errors
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
from placement.objects import trait as trait_obj from placement.objects import trait as trait_obj
@ -33,7 +32,7 @@ def _normalize_traits_qs_param(qs):
try: try:
op, value = qs.split(':', 1) op, value = qs.split(':', 1)
except ValueError: except ValueError:
msg = _('Badly formatted name parameter. Expected name query string ' msg = ('Badly formatted name parameter. Expected name query string '
'parameter in form: ' 'parameter in form: '
'?name=[in|startswith]:[name1,name2|prefix]. Got: "%s"') '?name=[in|startswith]:[name1,name2|prefix]. Got: "%s"')
msg = msg % qs msg = msg % qs
@ -75,9 +74,9 @@ def put_trait(req):
jsonschema.validate(name, schema.CUSTOM_TRAIT) jsonschema.validate(name, schema.CUSTOM_TRAIT)
except jsonschema.ValidationError: except jsonschema.ValidationError:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('The trait is invalid. A valid trait must be no longer than ' 'The trait is invalid. A valid trait must be no longer than '
'255 characters, start with the prefix "CUSTOM_" and use ' '255 characters, start with the prefix "CUSTOM_" and use '
'following characters: "A"-"Z", "0"-"9" and "_"')) 'following characters: "A"-"Z", "0"-"9" and "_"')
trait = trait_obj.Trait(context) trait = trait_obj.Trait(context)
trait.name = name trait.name = name
@ -158,8 +157,8 @@ def list_traits(req):
if 'associated' in req.GET: if 'associated' in req.GET:
if req.GET['associated'].lower() not in ['true', 'false']: if req.GET['associated'].lower() not in ['true', 'false']:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('The query parameter "associated" only accepts ' 'The query parameter "associated" only accepts '
'"true" or "false"')) '"true" or "false"')
filters['associated'] = ( filters['associated'] = (
True if req.GET['associated'].lower() == 'true' else False) 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) rp = rp_obj.ResourceProvider.get_by_uuid(context, uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'uuid': uuid, 'error': exc})
traits = trait_obj.get_all_by_resource_provider(context, rp) 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: if resource_provider.generation != rp_gen:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_("Resource provider's generation already changed. Please update " "Resource provider's generation already changed. Please update "
"the generation and try again."), "the generation and try again.",
json_formatter=util.json_error_formatter, json_formatter=util.json_error_formatter,
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
@ -235,7 +234,7 @@ def update_traits_for_resource_provider(req):
non_existed_trait = set(traits) - set(traits_name) non_existed_trait = set(traits) - set(traits_name)
if non_existed_trait: if non_existed_trait:
raise webob.exc.HTTPBadRequest( 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) resource_provider.set_traits(trait_objs)

View File

@ -17,7 +17,6 @@ from oslo_utils import timeutils
import webob import webob
from placement import exception from placement import exception
from placement.i18n import _
from placement import microversion from placement import microversion
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
from placement.objects import usage as usage_obj from placement.objects import usage as usage_obj
@ -59,7 +58,7 @@ def list_usages(req):
context, uuid) context, uuid)
except exception.NotFound as exc: except exception.NotFound as exc:
raise webob.exc.HTTPNotFound( 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}) {'uuid': uuid, 'error': exc})
usage = usage_obj.get_all_by_resource_provider_uuid(context, uuid) 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 errors
from placement import exception from placement import exception
from placement.i18n import _
from placement.objects import consumer as consumer_obj from placement.objects import consumer as consumer_obj
from placement.objects import project as project_obj from placement.objects import project as project_obj
from placement.objects import user as user_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 requires_consumer_generation:
if consumer.generation != consumer_generation: if consumer.generation != consumer_generation:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('consumer generation conflict - ' 'consumer generation conflict - '
'expected %(expected_gen)s but got %(got_gen)s') % 'expected %(expected_gen)s but got %(got_gen)s' %
{ {
'expected_gen': consumer.generation, 'expected_gen': consumer.generation,
'got_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 requires_consumer_generation:
if consumer_generation is not None: if consumer_generation is not None:
raise webob.exc.HTTPConflict( raise webob.exc.HTTPConflict(
_('consumer generation conflict - ' 'consumer generation conflict - '
'expected null but got %s') % consumer_generation, 'expected null but got %s' % consumer_generation,
comment=errors.CONCURRENT_UPDATE) comment=errors.CONCURRENT_UPDATE)
# No such consumer. This is common for new allocations. Create the # No such consumer. This is common for new allocations. Create the
# consumer record # 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 import webob
from placement.i18n import _
from placement import microversion from placement import microversion
from placement import util from placement import util
@ -115,25 +114,25 @@ class RequestGroup(object):
orphans = [('required%s' % suff) for suff, group in by_suffix.items() orphans = [('required%s' % suff) for suff, group in by_suffix.items()
if group.required_traits and not group.resources] if group.required_traits and not group.resources]
if orphans: if orphans:
msg = _( msg = (
'All traits parameters must be associated with resources. ' 'All traits parameters must be associated with resources. '
'Found the following orphaned traits keys: %s') 'Found the following orphaned traits keys: %s')
raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans)) raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans))
orphans = [('member_of%s' % suff) for suff, group in by_suffix.items() orphans = [('member_of%s' % suff) for suff, group in by_suffix.items()
if group.member_of and not group.resources] if group.member_of and not group.resources]
if orphans: if orphans:
msg = _('All member_of parameters must be associated with ' msg = ('All member_of parameters must be associated with '
'resources. Found the following orphaned member_of ' 'resources. Found the following orphaned member_of '
'keys: %s') 'keys: %s')
raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans)) raise webob.exc.HTTPBadRequest(msg % ', '.join(orphans))
# All request groups must have resources (which is almost, but not # All request groups must have resources (which is almost, but not
# quite, verified by the orphan checks above). # quite, verified by the orphan checks above).
if not all(grp.resources for grp in by_suffix.values()): 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) raise webob.exc.HTTPBadRequest(msg)
# The above would still pass if there were no request groups # The above would still pass if there were no request groups
if not by_suffix: if not by_suffix:
msg = _( msg = (
"At least one request group (`resources` or `resources{N}`) " "At least one request group (`resources` or `resources{N}`) "
"is required.") "is required.")
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
@ -152,7 +151,7 @@ class RequestGroup(object):
conflicting_traits.append('required%s: (%s)' conflicting_traits.append('required%s: (%s)'
% (suff, ', '.join(conflicts))) % (suff, ', '.join(conflicts)))
if conflicting_traits: if conflicting_traits:
msg = _( msg = (
'Conflicting required and forbidden traits found in the ' 'Conflicting required and forbidden traits found in the '
'following traits keys: %s') 'following traits keys: %s')
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(

View File

@ -24,7 +24,6 @@ from sqlalchemy import sql
from placement.db.sqlalchemy import models from placement.db.sqlalchemy import models
from placement import db_api from placement import db_api
from placement.i18n import _
from placement.objects import resource_provider as rp_obj from placement.objects import resource_provider as rp_obj
from placement.objects import trait as trait_obj from placement.objects import trait as trait_obj
from placement import resource_class_cache as rc_cache 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: if anchor_rp_uuid != areq.anchor_root_provider_uuid:
# This should never happen. If it does, it's a dev bug. # This should never happen. If it does, it's a dev bug.
raise ValueError( raise ValueError(
_("Expected every AllocationRequest in " "Expected every AllocationRequest in "
"`_consolidate_allocation_requests` to have the same " "`_consolidate_allocation_requests` to have the same "
"anchor!")) "anchor!")
for arr in areq.resource_requests: for arr in areq.resource_requests:
key = _rp_rc_key(arr.resource_provider, arr.resource_class) key = _rp_rc_key(arr.resource_provider, arr.resource_class)
if key not in arrs_by_rp_rc: if key not in arrs_by_rp_rc:

View File

@ -23,7 +23,6 @@ from sqlalchemy import func
from placement.db.sqlalchemy import models from placement.db.sqlalchemy import models
from placement import db_api from placement import db_api
from placement import exception from placement import exception
from placement.i18n import _
from placement import resource_class_cache as rc_cache from placement import resource_class_cache as rc_cache
_RC_TBL = models.ResourceClass.__table__ _RC_TBL = models.ResourceClass.__table__
@ -135,7 +134,7 @@ class ResourceClass(object):
LOG.warning("Exceeded retry limit on ID generation while " LOG.warning("Exceeded retry limit on ID generation while "
"creating ResourceClass %(name)s", "creating ResourceClass %(name)s",
{'name': self.name}) {'name': self.name})
msg = _("creating resource class %s") % self.name msg = "creating resource class %s" % self.name
raise exception.MaxDBRetriesExceeded(action=msg) raise exception.MaxDBRetriesExceeded(action=msg)
@staticmethod @staticmethod

View File

@ -33,7 +33,6 @@ from sqlalchemy import sql
from placement.db.sqlalchemy import models from placement.db.sqlalchemy import models
from placement import db_api from placement import db_api
from placement import exception from placement import exception
from placement.i18n import _
from placement.objects import inventory as inv_obj from placement.objects import inventory as inv_obj
from placement.objects import rp_candidates from placement.objects import rp_candidates
from placement.objects import trait as trait_obj from placement.objects import trait as trait_obj
@ -972,15 +971,15 @@ class ResourceProvider(object):
if parent_uuid == self.uuid: if parent_uuid == self.uuid:
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='create', action='create',
reason=_('parent provider UUID cannot be same as UUID. ' reason='parent provider UUID cannot be same as UUID. '
'Please set parent provider UUID to None if ' 'Please set parent provider UUID to None if '
'there is no parent.')) 'there is no parent.')
parent_ids = provider_ids_from_uuid(context, parent_uuid) parent_ids = provider_ids_from_uuid(context, parent_uuid)
if parent_ids is None: if parent_ids is None:
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='create', action='create',
reason=_('parent provider UUID does not exist.')) reason='parent provider UUID does not exist.')
parent_id = parent_ids.id parent_id = parent_ids.id
root_id = parent_ids.root_id root_id = parent_ids.root_id
@ -1075,13 +1074,13 @@ class ResourceProvider(object):
if parent_ids is None: if parent_ids is None:
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='create', 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 if (my_ids.parent_id is not None and
my_ids.parent_id != parent_ids.id): my_ids.parent_id != parent_ids.id):
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='update', action='update',
reason=_('re-parenting a provider is not currently ' reason='re-parenting a provider is not currently '
'allowed.')) 'allowed.')
if my_ids.parent_uuid is None: if my_ids.parent_uuid is None:
# So the user specifies a parent for an RP that doesn't # So the user specifies a parent for an RP that doesn't
# have one. We have to check that by this new parent we # 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: if parent_uuid in rp_uuids_in_the_same_tree:
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='update', action='update',
reason=_('creating loop in the provider tree is ' reason='creating loop in the provider tree is '
'not allowed.')) 'not allowed.')
updates['root_provider_id'] = parent_ids.root_id updates['root_provider_id'] = parent_ids.root_id
updates['parent_provider_id'] = parent_ids.id updates['parent_provider_id'] = parent_ids.id
@ -1106,8 +1105,8 @@ class ResourceProvider(object):
if my_ids.parent_id is not None: if my_ids.parent_id is not None:
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='update', action='update',
reason=_('un-parenting a provider is not currently ' reason='un-parenting a provider is not currently '
'allowed.')) 'allowed.')
db_rp = context.session.query(models.ResourceProvider).filter_by( db_rp = context.session.query(models.ResourceProvider).filter_by(
id=id).first() id=id).first()
@ -1136,7 +1135,7 @@ class ResourceProvider(object):
# parent provider and here... # parent provider and here...
raise exception.ObjectActionError( raise exception.ObjectActionError(
action='update', action='update',
reason=_('parent provider UUID does not exist.')) reason='parent provider UUID does not exist.')
@staticmethod @staticmethod
@db_api.placement_context_manager.writer # For online data migration @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. :raise ValueError: If traits is empty or None.
""" """
if not traits: 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") rptt = sa.alias(_RP_TRAIT_TBL, name="rpt")
sel = sa.select([rptt.c.resource_provider_id]) 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. :raise ValueError: If required_traits is empty or None.
""" """
if not required_traits: 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") rptt = sa.alias(_RP_TRAIT_TBL, name="rpt")
sel = sa.select([rptt.c.resource_provider_id]) sel = sa.select([rptt.c.resource_provider_id])

View File

@ -23,7 +23,6 @@ import sqlalchemy as sa
from placement.db.sqlalchemy import models from placement.db.sqlalchemy import models
from placement import db_api from placement import db_api
from placement import exception from placement import exception
from placement.i18n import _
_RP_TBL = models.ResourceProvider.__table__ _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 :param root_ids: list of root resource provider IDs
""" """
if not root_ids: if not root_ids:
raise ValueError(_("Expected root_ids to be a list of root resource " raise ValueError("Expected root_ids to be a list of root resource "
"provider internal IDs, but got an empty list.")) "provider internal IDs, but got an empty list.")
rpt = sa.alias(_RP_TBL, name='rpt') rpt = sa.alias(_RP_TBL, name='rpt')
rptt = sa.alias(_RP_TRAIT_TBL, name='rptt') 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. :raise TraitNotFound: if any named trait doesn't exist in the database.
""" """
if not names: if not names:
raise ValueError(_("Expected names to be a list of string trait " raise ValueError("Expected names to be a list of string trait "
"names, but got an empty list.")) "names, but got an empty list.")
# Avoid SAWarnings about unicode types... # Avoid SAWarnings about unicode types...
unames = map(six.text_type, names) unames = map(six.text_type, names)

View File

@ -22,7 +22,6 @@ from oslo_utils import uuidutils
import webob import webob
from placement import errors from placement import errors
from placement.i18n import _
# NOTE(cdent): avoid cyclical import conflict between util and # NOTE(cdent): avoid cyclical import conflict between util and
# microversion # microversion
import placement.microversion import placement.microversion
@ -60,7 +59,7 @@ def check_accept(*types):
if not best_matches: if not best_matches:
type_string = ', '.join(types) type_string = ', '.join(types)
raise webob.exc.HTTPNotAcceptable( 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) json_formatter=json_error_formatter)
return f(req) return f(req)
return decorated_function return decorated_function
@ -73,14 +72,14 @@ def extract_json(body, schema):
data = jsonutils.loads(body) data = jsonutils.loads(body)
except ValueError as exc: except ValueError as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Malformed JSON: %(error)s') % {'error': exc}, 'Malformed JSON: %(error)s' % {'error': exc},
json_formatter=json_error_formatter) json_formatter=json_error_formatter)
try: try:
jsonschema.validate(data, schema, jsonschema.validate(data, schema,
format_checker=jsonschema.FormatChecker()) format_checker=jsonschema.FormatChecker())
except jsonschema.ValidationError as exc: except jsonschema.ValidationError as exc:
raise webob.exc.HTTPBadRequest( 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) json_formatter=json_error_formatter)
return data return data
@ -164,8 +163,8 @@ def require_content(content_type):
if not req.content_type: if not req.content_type:
req.content_type = 'None' req.content_type = 'None'
raise webob.exc.HTTPUnsupportedMediaType( raise webob.exc.HTTPUnsupportedMediaType(
_('The media type %(bad_type)s is not supported, ' 'The media type %(bad_type)s is not supported, '
'use %(good_type)s') % 'use %(good_type)s' %
{'bad_type': req.content_type, {'bad_type': req.content_type,
'good_type': content_type}, 'good_type': content_type},
json_formatter=json_error_formatter) json_formatter=json_error_formatter)
@ -213,7 +212,7 @@ def validate_query_params(req, schema):
format_checker=jsonschema.FormatChecker()) format_checker=jsonschema.FormatChecker())
except (jsonschema.ValidationError, UnicodeDecodeError) as exc: except (jsonschema.ValidationError, UnicodeDecodeError) as exc:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Invalid query string parameters: %(exc)s') % 'Invalid query string parameters: %(exc)s' %
{'exc': exc}) {'exc': exc})
@ -258,7 +257,7 @@ def normalize_resources_qs_param(qs):
expected format. expected format.
""" """
if qs.strip() == "": if qs.strip() == "":
msg = _('Badly formed resources parameter. Expected resources ' msg = ('Badly formed resources parameter. Expected resources '
'query string parameter in form: ' 'query string parameter in form: '
'?resources=VCPU:2,MEMORY_MB:1024. Got: empty string.') '?resources=VCPU:2,MEMORY_MB:1024. Got: empty string.')
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
@ -269,7 +268,7 @@ def normalize_resources_qs_param(qs):
try: try:
rc_name, amount = rt.split(':') rc_name, amount = rt.split(':')
except ValueError: except ValueError:
msg = _('Badly formed resources parameter. Expected resources ' msg = ('Badly formed resources parameter. Expected resources '
'query string parameter in form: ' 'query string parameter in form: '
'?resources=VCPU:2,MEMORY_MB:1024. Got: %s.') '?resources=VCPU:2,MEMORY_MB:1024. Got: %s.')
msg = msg % rt msg = msg % rt
@ -277,7 +276,7 @@ def normalize_resources_qs_param(qs):
try: try:
amount = int(amount) amount = int(amount)
except ValueError: except ValueError:
msg = _('Requested resource %(resource_name)s expected positive ' msg = ('Requested resource %(resource_name)s expected positive '
'integer amount. Got: %(amount)s.') 'integer amount. Got: %(amount)s.')
msg = msg % { msg = msg % {
'resource_name': rc_name, 'resource_name': rc_name,
@ -285,7 +284,7 @@ def normalize_resources_qs_param(qs):
} }
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
if amount < 1: if amount < 1:
msg = _('Requested resource %(resource_name)s requires ' msg = ('Requested resource %(resource_name)s requires '
'amount >= 1. Got: %(amount)d.') 'amount >= 1. Got: %(amount)d.')
msg = msg % { msg = msg % {
'resource_name': rc_name, 'resource_name': rc_name,
@ -331,7 +330,7 @@ def normalize_traits_qs_param(val, allow_forbidden=False):
if allow_forbidden: if allow_forbidden:
expected_form = 'HW_CPU_X86_VMX,!CUSTOM_MAGIC' expected_form = 'HW_CPU_X86_VMX,!CUSTOM_MAGIC'
if not all(trait and valid_trait(trait, allow_forbidden) for trait in ret): if not all(trait and valid_trait(trait, allow_forbidden) for trait in ret):
msg = _("Invalid query string parameters: Expected 'required' " msg = ("Invalid query string parameters: Expected 'required' "
"parameter value of the form: %(form)s. " "parameter value of the form: %(form)s. "
"Got: %(val)s") % {'form': expected_form, 'val': val} "Got: %(val)s") % {'form': expected_form, 'val': val}
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
@ -354,7 +353,7 @@ def normalize_member_of_qs_params(req, suffix=''):
multi_member_of = want_version.matches((1, 24)) multi_member_of = want_version.matches((1, 24))
if not multi_member_of and len(req.GET.getall('member_of' + suffix)) > 1: if not multi_member_of and len(req.GET.getall('member_of' + suffix)) > 1:
raise webob.exc.HTTPBadRequest( raise webob.exc.HTTPBadRequest(
_('Multiple member_of%s parameters are not supported') % suffix) 'Multiple member_of%s parameters are not supported' % suffix)
values = [] values = []
for value in req.GET.getall('member_of' + suffix): for value in req.GET.getall('member_of' + suffix):
values.append(normalize_member_of_qs_param(value)) values.append(normalize_member_of_qs_param(value))
@ -375,7 +374,7 @@ def normalize_member_of_qs_param(value):
expected format. expected format.
""" """
if "," in value and not value.startswith("in:"): if "," in value and not value.startswith("in:"):
msg = _("Multiple values for 'member_of' must be prefixed with the " msg = ("Multiple values for 'member_of' must be prefixed with the "
"'in:' keyword. Got: %s") % value "'in:' keyword. Got: %s") % value
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
if value.startswith('in:'): if value.startswith('in:'):
@ -385,7 +384,7 @@ def normalize_member_of_qs_param(value):
# Make sure the values are actually UUIDs. # Make sure the values are actually UUIDs.
for aggr_uuid in value: for aggr_uuid in value:
if not uuidutils.is_uuid_like(aggr_uuid): if not uuidutils.is_uuid_like(aggr_uuid):
msg = _("Invalid query string parameters: Expected 'member_of' " msg = ("Invalid query string parameters: Expected 'member_of' "
"parameter to contain valid UUID(s). Got: %s") % aggr_uuid "parameter to contain valid UUID(s). Got: %s") % aggr_uuid
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)
return value return value
@ -401,7 +400,7 @@ def normalize_in_tree_qs_params(value):
""" """
ret = value.strip() ret = value.strip()
if not uuidutils.is_uuid_like(ret): if not uuidutils.is_uuid_like(ret):
msg = _("Invalid query string parameters: Expected 'in_tree' " msg = ("Invalid query string parameters: Expected 'in_tree' "
"parameter to be a format of uuid. " "parameter to be a format of uuid. "
"Got: %(val)s") % {'val': value} "Got: %(val)s") % {'val': value}
raise webob.exc.HTTPBadRequest(msg) raise webob.exc.HTTPBadRequest(msg)

View File

@ -19,7 +19,6 @@ oslo.serialization!=2.19.1,>=2.18.0 # Apache-2.0
oslo.utils>=3.37.0 # Apache-2.0 oslo.utils>=3.37.0 # Apache-2.0
oslo.db>=4.40.0 # Apache-2.0 oslo.db>=4.40.0 # Apache-2.0
oslo.policy>=1.35.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.middleware>=3.31.0 # Apache-2.0
oslo.upgradecheck>=0.2.0 # Apache-2.0 oslo.upgradecheck>=0.2.0 # Apache-2.0
os-resource-classes>=0.2.0 # Apache-2.0 os-resource-classes>=0.2.0 # Apache-2.0

View File

@ -51,21 +51,5 @@ tag_build =
tag_date = 0 tag_date = 0
tag_svn_revision = 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] [wheel]
universal = 1 universal = 1

View File

@ -156,9 +156,6 @@ exclude = .venv,.git,.tox,dist,*lib/python*,*egg,build,releasenotes
# 14 is currently the most complex thing we have # 14 is currently the most complex thing we have
max-complexity=15 max-complexity=15
[hacking]
import_exceptions = placement.i18n
[testenv:bindep] [testenv:bindep]
# Do not install any requirements. We want this to be fast and work even if # 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 # system dependencies are missing, since it's used to tell you what system