"Fossies" - the Fresh Open Source Software Archive

Member "zun-7.0.0/zun/common/exception.py" (14 Apr 2021, 26179 Bytes) of package /linux/misc/openstack/zun-7.0.0.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. For more information about "exception.py" see the Fossies "Dox" file reference documentation and the latest Fossies "Diffs" side-by-side code changes report: 6.0.0_vs_7.0.0.

    1 # Copyright 2013 - Red Hat, Inc.
    2 #
    3 # Licensed under the Apache License, Version 2.0 (the "License");
    4 # you may not use this file except in compliance with the License.
    5 # You may obtain a copy of the License at
    6 #
    7 #     http://www.apache.org/licenses/LICENSE-2.0
    8 #
    9 # Unless required by applicable law or agreed to in writing, software
   10 # distributed under the License is distributed on an "AS IS" BASIS,
   11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   12 # See the License for the specific language governing permissions and
   13 # limitations under the License.
   14 
   15 """Zun base exception handling.
   16 
   17 Includes decorator for re-raising Zun-type exceptions.
   18 
   19 """
   20 
   21 import functools
   22 import inspect
   23 import re
   24 import sys
   25 
   26 from keystoneclient import exceptions as keystone_exceptions
   27 from oslo_config import cfg
   28 from oslo_log import log as logging
   29 from oslo_utils import excutils
   30 from oslo_utils import uuidutils
   31 import pecan
   32 from webob import util as woutil
   33 
   34 from zun.common.i18n import _
   35 import zun.conf
   36 
   37 LOG = logging.getLogger(__name__)
   38 
   39 CONF = zun.conf.CONF
   40 
   41 try:
   42     CONF.import_opt('fatal_exception_format_errors',
   43                     'oslo_versionedobjects.exception')
   44 except cfg.NoSuchOptError:
   45     # Note:work around for zun run against master branch
   46     # in devstack gate job, as zun not branched yet
   47     # versionobjects kilo/master different version can
   48     # cause issue here. As it changed import group. So
   49     # add here before branch to prevent gate failure.
   50     # Bug: #1447873
   51     CONF.import_opt('fatal_exception_format_errors',
   52                     'oslo_versionedobjects.exception',
   53                     group='oslo_versionedobjects')
   54 
   55 
   56 def wrap_exception(notifier=None, event_type=None):
   57     """This decorator wraps a method to catch any exceptions.
   58 
   59     It logs the exception as well as optionally sending
   60     it to the notification system.
   61     """
   62     def inner(f):
   63         def wrapped(self, context, *args, **kwargs):
   64             # Don't store self or context in the payload, it now seems to
   65             # contain confidential information.
   66             try:
   67                 return f(self, context, *args, **kwargs)
   68             except Exception as e:
   69                 with excutils.save_and_reraise_exception():
   70                     if notifier:
   71                         call_dict = inspect.getcallargs(f, self, context,
   72                                                         *args, **kwargs)
   73                         payload = dict(exception=e,
   74                                        private=dict(args=call_dict)
   75                                        )
   76 
   77                         temp_type = event_type
   78                         if not temp_type:
   79                             # If f has multiple decorators, they must use
   80                             # functools.wraps to ensure the name is
   81                             # propagated.
   82                             temp_type = f.__name__
   83 
   84                         notifier.error(context, temp_type, payload)
   85 
   86         return functools.wraps(f)(wrapped)
   87     return inner
   88 
   89 
   90 OBFUSCATED_MSG = _('Your request could not be handled '
   91                    'because of a problem in the server. '
   92                    'Error Correlation id is: %s')
   93 
   94 
   95 def wrap_controller_exception(func, func_server_error, func_client_error):
   96     """This decorator wraps controllers methods to handle exceptions:
   97 
   98     - if an unhandled Exception or a ZunException with an error code >=500
   99       is catched, raise a http 5xx ClientSideError and correlates it with a log
  100       message
  101 
  102     - if a ZunException is catched and its error code is <500, raise a http
  103       4xx and logs the excp in debug mode
  104 
  105     """
  106     @functools.wraps(func)
  107     def wrapped(*args, **kwargs):
  108         try:
  109             return func(*args, **kwargs)
  110         except Exception as excp:
  111             if isinstance(excp, ZunException):
  112                 http_error_code = excp.code
  113             else:
  114                 http_error_code = 500
  115 
  116             if http_error_code >= 500:
  117                 # log the error message with its associated
  118                 # correlation id
  119                 log_correlation_id = uuidutils.generate_uuid()
  120                 LOG.exception("%(correlation_id)s:%(excp)s",
  121                               {'correlation_id': log_correlation_id,
  122                                'excp': str(excp)})
  123                 # raise a client error with an obfuscated message
  124                 return func_server_error(log_correlation_id, http_error_code)
  125             else:
  126                 # raise a client error the original message
  127                 LOG.debug(excp)
  128                 return func_client_error(excp, http_error_code)
  129     return wrapped
  130 
  131 
  132 def convert_excp_to_err_code(excp_name):
  133     """Convert Exception class name (CamelCase) to error-code (Snake-case)"""
  134     words = re.findall(r'[A-Z]?[a-z]+|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)|\d+',
  135                        excp_name)
  136     return '-'.join([str.lower(word) for word in words])
  137 
  138 
  139 def wrap_pecan_controller_exception(func):
  140     """This decorator wraps pecan controllers to handle exceptions."""
  141     def _func_server_error(log_correlation_id, status_code):
  142         pecan.response.status = status_code
  143         return {
  144             'faultcode': 'Server',
  145             'status_code': status_code,
  146             'title': woutil.status_reasons[status_code],
  147             'description': str(OBFUSCATED_MSG % log_correlation_id),
  148         }
  149 
  150     def _func_client_error(excp, status_code):
  151         pecan.response.status = status_code
  152         return {
  153             'faultcode': 'Client',
  154             'faultstring': convert_excp_to_err_code(excp.__class__.__name__),
  155             'status_code': status_code,
  156             'title': str(excp),
  157             'description': str(excp),
  158         }
  159 
  160     return wrap_controller_exception(func,
  161                                      _func_server_error,
  162                                      _func_client_error)
  163 
  164 
  165 def wrap_keystone_exception(func):
  166     """Wrap keystone exceptions and throw Zun specific exceptions."""
  167     @functools.wraps(func)
  168     def wrapped(*args, **kwargs):
  169         try:
  170             return func(*args, **kwargs)
  171         except keystone_exceptions.AuthorizationFailure:
  172             raise AuthorizationFailure(
  173                 client=func.__name__, message="reason: %s" % sys.exc_info()[1])
  174         except keystone_exceptions.ClientException:
  175             raise AuthorizationFailure(
  176                 client=func.__name__,
  177                 message="unexpected keystone client error occurred: %s"
  178                         % sys.exc_info()[1])
  179     return wrapped
  180 
  181 
  182 class ZunException(Exception):
  183     """Base Zun Exception
  184 
  185     To correctly use this class, inherit from it and define
  186     a 'message' property. That message will get printf'd
  187     with the keyword arguments provided to the constructor.
  188 
  189     """
  190     message = _("An unknown exception occurred.")
  191     code = 500
  192 
  193     def __init__(self, message=None, **kwargs):
  194         self.kwargs = kwargs
  195 
  196         if 'code' not in self.kwargs and hasattr(self, 'code'):
  197             self.kwargs['code'] = self.code
  198 
  199         if message:
  200             self.message = message
  201 
  202         try:
  203             self.message = self.message % kwargs
  204         except KeyError:
  205             # kwargs doesn't match a variable in the message
  206             # log the issue and the kwargs
  207             LOG.exception('Exception in string format operation, '
  208                           'kwargs: %s', kwargs)
  209             try:
  210                 ferr = CONF.fatal_exception_format_errors
  211             except cfg.NoSuchOptError:
  212                 ferr = CONF.oslo_versionedobjects.fatal_exception_format_errors
  213             if ferr:
  214                 raise
  215 
  216         super(ZunException, self).__init__(self.message)
  217 
  218     def __str__(self):
  219         return self.message
  220 
  221     def format_message(self):
  222         if self.__class__.__name__.endswith('_Remote'):
  223             return self.args[0]
  224         else:
  225             return str(self)
  226 
  227 
  228 class ObjectNotFound(ZunException):
  229     message = _("The %(name)s %(id)s could not be found.")
  230 
  231 
  232 class ObjectNotUnique(ZunException):
  233     message = _("The %(name)s already exists.")
  234 
  235 
  236 class ObjectActionError(ZunException):
  237     message = _('Object action %(action)s failed because: %(reason)s')
  238 
  239 
  240 class ResourceNotFound(ObjectNotFound):
  241     message = _("The %(name)s resource %(id)s could not be found.")
  242     code = 404
  243 
  244 
  245 class ResourceExists(ObjectNotUnique):
  246     message = _("The %(name)s resource already exists.")
  247     code = 409
  248 
  249 
  250 class AuthorizationFailure(ZunException):
  251     message = _("%(client)s connection failed. %(message)s")
  252 
  253 
  254 class UnsupportedObjectError(ZunException):
  255     message = _('Unsupported object type %(objtype)s')
  256 
  257 
  258 class IncompatibleObjectVersion(ZunException):
  259     message = _('Version %(objver)s of %(objname)s is not supported')
  260 
  261 
  262 class OrphanedObjectError(ZunException):
  263     message = _('Cannot call %(method)s on orphaned %(objtype)s object')
  264 
  265 
  266 class Invalid(ZunException):
  267     message = _("Unacceptable parameters.")
  268     code = 400
  269 
  270 
  271 class InvalidValue(Invalid):
  272     message = _("Received value '%(value)s' is invalid for type %(type)s.")
  273 
  274 
  275 class ValidationError(Invalid):
  276     message = "%(detail)s"
  277 
  278 
  279 class SchemaValidationError(ValidationError):
  280     message = "%(detail)s"
  281 
  282 
  283 class InvalidUUID(Invalid):
  284     message = _("Expected a uuid but received %(uuid)s.")
  285 
  286 
  287 class InvalidName(Invalid):
  288     message = _("Expected a name but received %(uuid)s.")
  289 
  290 
  291 class InvalidDiscoveryURL(Invalid):
  292     message = _("Received invalid discovery URL '%(discovery_url)s' for "
  293                 "discovery endpoint '%(discovery_endpoint)s'.")
  294 
  295 
  296 class GetDiscoveryUrlFailed(ZunException):
  297     message = _("Failed to get discovery url from '%(discovery_endpoint)s'.")
  298 
  299 
  300 class InvalidUuidOrName(Invalid):
  301     message = _("Expected a name or uuid but received %(uuid)s.")
  302 
  303 
  304 class InvalidIdentity(Invalid):
  305     message = _("Expected an uuid or int but received %(identity)s.")
  306 
  307 
  308 class InvalidCsr(Invalid):
  309     message = _("Received invalid csr %(csr)s.")
  310 
  311 
  312 class HTTPNotFound(ResourceNotFound):
  313     pass
  314 
  315 
  316 class Conflict(ZunException):
  317     message = _('Conflict.')
  318     code = 409
  319 
  320 
  321 class ConflictOptions(Conflict):
  322     message = _('Conflicting options.')
  323 
  324 
  325 class InvalidState(Conflict):
  326     message = _("Invalid resource state.")
  327 
  328 
  329 # Cannot be templated as the error syntax varies.
  330 # msg needs to be constructed when raised.
  331 class InvalidParameterValue(Invalid):
  332     message = _("%(err)s")
  333 
  334 
  335 class InvalidParamInVersion(Invalid):
  336     message = _('Invalid param %(param)s because current request '
  337                 'version is %(req_version)s. %(param)s is only '
  338                 'supported from version %(min_version)s')
  339 
  340 
  341 class InvalidQuotaValue(Invalid):
  342     message = _("Change would make usage less than 0 for the following "
  343                 "resources: %(unders)s")
  344 
  345 
  346 class InvalidQuotaMethodUsage(Invalid):
  347     message = _("Wrong quota method %(method)s used on resource %(res)s")
  348 
  349 
  350 class PatchError(Invalid):
  351     message = _("Couldn't apply patch '%(patch)s'. Reason: %(reason)s")
  352 
  353 
  354 class NotAuthorized(ZunException):
  355     message = _("Not authorized.")
  356     code = 403
  357 
  358 
  359 class ConfigInvalid(ZunException):
  360     message = _("Invalid configuration file. %(error_msg)s")
  361 
  362 
  363 class PolicyNotAuthorized(NotAuthorized):
  364     message = _("Policy doesn't allow %(action)s to be performed.")
  365 
  366 
  367 class ContainerNotFound(HTTPNotFound):
  368     message = _("Container %(container)s could not be found.")
  369 
  370 
  371 class ContainerHostNotUp(ZunException):
  372     message = _("Container %(container)s host %(host)s is not up.")
  373 
  374 
  375 class ComputeNodeNotFound(HTTPNotFound):
  376     message = _("Compute node %(compute_node)s could not be found.")
  377 
  378 
  379 class NetworkNotFound(HTTPNotFound):
  380     message = _("Neutron network %(network)s could not be found.")
  381 
  382 
  383 class RegistryNotFound(HTTPNotFound):
  384     message = _("Registry %(registry)s could not be found.")
  385 
  386 
  387 class NetworkAlreadyExists(ResourceExists):
  388     message = _("A network with %(field)s %(value)s already exists.")
  389 
  390     def __init__(self, field, value):
  391         self.field = field
  392         self.value = value
  393         super(NetworkAlreadyExists, self).__init__(field=field, value=value)
  394 
  395 
  396 class PortNotFound(HTTPNotFound):
  397     message = _("Neutron port %(port)s could not be found.")
  398 
  399 
  400 class VolumeMappingNotFound(HTTPNotFound):
  401     message = _("Volume mapping %(volume_mapping)s could not be found.")
  402 
  403 
  404 class VolumeNotFound(HTTPNotFound):
  405     message = _("Volume %(volume)s could not be found.")
  406 
  407 
  408 class ImageNotFound(Invalid):
  409     message = _("Image %(image)s could not be found.")
  410 
  411 
  412 class OperationNotSupported(ZunException):
  413     message = _("The operation is not supported.")
  414 
  415 
  416 class ZunServiceNotFound(HTTPNotFound):
  417     message = _("Zun service %(binary)s on host %(host)s could not be found.")
  418 
  419 
  420 class ResourceClassNotFound(HTTPNotFound):
  421     message = _("Resource class %(resource_class)s could not be found.")
  422 
  423 
  424 class InventoryNotFound(HTTPNotFound):
  425     message = _("Inventory %(inventory)s could not be found.")
  426 
  427 
  428 class AllocationNotFound(HTTPNotFound):
  429     message = _("Allocation %(allocation)s could not be found.")
  430 
  431 
  432 class ContainerAlreadyExists(ResourceExists):
  433     message = _("A container with %(field)s %(value)s already exists.")
  434 
  435 
  436 class ExecInstanceAlreadyExists(ResourceExists):
  437     message = _("An exec instance with exec_id %(exec_id)s already exists "
  438                 "in container.")
  439 
  440 
  441 class ComputeNodeAlreadyExists(ResourceExists):
  442     message = _("A compute node with %(field)s %(value)s already exists.")
  443 
  444 
  445 class ImageAlreadyExists(ResourceExists):
  446     message = _("An image with tag %(tag)s and repo %(repo)s already exists.")
  447 
  448 
  449 class ZunServiceAlreadyExists(ResourceExists):
  450     message = _("Service %(binary)s on host %(host)s already exists.")
  451 
  452 
  453 class ResourceProviderAlreadyExists(ResourceExists):
  454     message = _("A resource provider with %(field)s %(value)s already exists.")
  455 
  456 
  457 class ResourceClassAlreadyExists(ResourceExists):
  458     message = _("A resource class with %(field)s %(value)s already exists.")
  459 
  460 
  461 class VolumeMappingAlreadyExists(ResourceExists):
  462     message = _("A volume mapping with %(field)s %(value)s already exists.")
  463 
  464 
  465 class VolumeAlreadyExists(ResourceExists):
  466     message = _("A volume with %(field)s %(value)s already exists.")
  467 
  468 
  469 class RegistryAlreadyExists(ResourceExists):
  470     message = _("A registry with %(field)s %(value)s already exists.")
  471 
  472 
  473 class PortNotUsable(Invalid):
  474     message = _("Port %(port)s not usable for the container.")
  475 
  476 
  477 class PortInUse(Invalid):
  478     message = _("Port %(port)s is still in use.")
  479 
  480 
  481 class VolumeNotUsable(Invalid):
  482     message = _("Volume %(volume)s not usable for the container.")
  483 
  484 
  485 class VolumeInUse(Invalid):
  486     message = _("Volume %(volume)s is still in use.")
  487 
  488 
  489 class PortBindingFailed(Invalid):
  490     message = _("Binding failed for port %(port)s, please check neutron "
  491                 "logs for more information.")
  492 
  493 
  494 class UniqueConstraintViolated(ResourceExists):
  495     message = _("A resource with %(fields)s violates unique constraint.")
  496 
  497 
  498 class InvalidStateException(ZunException):
  499     message = _("Cannot %(action)s container %(id)s in %(actual_state)s state")
  500     code = 409
  501 
  502 
  503 class DockerError(ZunException):
  504     message = _("Docker internal error: %(error_msg)s.")
  505 
  506 
  507 class PollTimeOut(ZunException):
  508     message = _("Polling request timed out.")
  509 
  510 
  511 class ServerInError(ZunException):
  512     message = _('Went to status %(resource_status)s due to '
  513                 '"%(status_reason)s"')
  514 
  515 
  516 class ServerUnknownStatus(ZunException):
  517     message = _('%(result)s - Unknown status %(resource_status)s due to '
  518                 '"%(status_reason)s"')
  519 
  520 
  521 class EntityNotFound(ZunException):
  522     message = _("The %(entity)s (%(name)s) could not be found.")
  523 
  524 
  525 class CommandError(ZunException):
  526     message = _("The command: %(cmd)s failed on the system, due to %(error)s")
  527 
  528 
  529 class NoValidHost(ZunException):
  530     message = _("No valid host was found. %(reason)s")
  531 
  532 
  533 class NoInteractiveFlag(Invalid):
  534     message = _("%(msg)s")
  535 
  536 
  537 class CPUPinningUnknown(ZunException):
  538     message = _("CPU set to pin %(requested)s must be a subset of "
  539                 "known CPU set %(cpuset)s")
  540 
  541 
  542 class CPUUnpinningUnknown(Invalid):
  543     message = _("CPU set to unpin %(requested)s must be a subset of "
  544                 "known CPU set %(cpuset)s")
  545 
  546 
  547 class CPUPinningInvalid(Invalid):
  548     message = _("CPU set to pin %(requested)s must be a subset of "
  549                 "free CPU set %(free)s")
  550 
  551 
  552 class CPUUnpinningInvalid(Invalid):
  553     message = _("CPU set to unpin %(requested)s must be a subset of "
  554                 "pinned CPU set %(pinned)s")
  555 
  556 
  557 class NotFound(ZunException):
  558     message = _("Resource could not be found.")
  559     code = 404
  560 
  561 
  562 class SchedulerHostFilterNotFound(NotFound):
  563     message = _("Scheduler Host Filter %(filter_name)s could not be found.")
  564 
  565 
  566 class ClassNotFound(NotFound):
  567     message = _("Class %(class_name)s could not be found: %(exception)s")
  568 
  569 
  570 class ApiVersionsIntersect(ZunException):
  571     message = _("Version of %(name)s %(min_ver)s %(max_ver)s intersects "
  572                 "with another versions.")
  573 
  574 
  575 class ConnectionFailed(ZunException):
  576     message = _("Failed to connect to remote host")
  577 
  578 
  579 class SocketException(ZunException):
  580     message = _("Socket exceptions")
  581 
  582 
  583 class InvalidWebsocketUrl(ZunException):
  584     message = _("Websocket Url invalid")
  585 
  586 
  587 class InvalidWebsocketToken(ZunException):
  588     message = _("Websocket token is invalid")
  589 
  590 
  591 class ResourcesUnavailable(ZunException):
  592     message = _("Insufficient compute resources: %(reason)s.")
  593 
  594 
  595 class MakeFileSystemException(ZunException):
  596     message = _("Unexpected error while make file system")
  597 
  598 
  599 class MountException(ZunException):
  600     message = _("Unexpected error while mount device")
  601 
  602 
  603 class UnmountException(ZunException):
  604     message = _("Unexpected error while do umount")
  605 
  606 
  607 class FileNotFound(ZunException):
  608     message = _("The expected file not exist")
  609 
  610 
  611 class PciConfigInvalidWhitelist(ZunException):
  612     message = _("Invalid PCI devices Whitelist config %(reason)s")
  613 
  614 
  615 class PciDeviceWrongAddressFormat(ZunException):
  616     message = _("The PCI address %(address)s has an incorrect format.")
  617 
  618 
  619 class PciDeviceInvalidDeviceName(ZunException):
  620     message = _("Invalid PCI Whitelist: "
  621                 "The PCI whitelist can specify devname or address,"
  622                 " but not both")
  623 
  624 
  625 class PciDeviceNotFoundById(NotFound):
  626     message = _("PCI device %(id)s not found")
  627 
  628 
  629 class PciDeviceNotFound(NotFound):
  630     message = _("PCI Device %(node_id)s:%(address)s not found.")
  631 
  632 
  633 class PciDevicePoolEmpty(ZunException):
  634     message = _(
  635         "Attempt to consume PCI device %(compute_node_uuid)s:%(address)s "
  636         "from empty pool")
  637 
  638 
  639 class CapsuleAlreadyExists(ResourceExists):
  640     message = _("A capsule with %(field)s %(value)s already exists.")
  641 
  642 
  643 class CapsuleNotFound(HTTPNotFound):
  644     message = _("Capsule %(capsule)s could not be found.")
  645 
  646 
  647 class InvalidCapsuleTemplate(ZunException):
  648     message = _("Invalid capsule template: %(reason)s.")
  649 
  650 
  651 class FailedParseStringToJson(ZunException):
  652     message = _("Failed parse string to json: %(reason)s.")
  653 
  654 
  655 class ExternalNetworkAttachForbidden(NotAuthorized):
  656     message = _("It is not allowed to create an interface on "
  657                 "external network %(network_uuid)s")
  658 
  659 
  660 class PciDeviceInvalidStatus(Invalid):
  661     message = _(
  662         "PCI device %(compute_node_id)s:%(address)s is %(status)s "
  663         "instead of %(hopestatus)s")
  664 
  665 
  666 class PciDeviceVFInvalidStatus(Invalid):
  667     message = _(
  668         "Not all Virtual Functions of PF %(compute_node_id)s:%(address)s "
  669         "are free.")
  670 
  671 
  672 class PciDevicePFInvalidStatus(Invalid):
  673     message = _(
  674         "Physical Function %(compute_node_id)s:%(address)s, related to VF"
  675         " %(compute_node_id)s:%(vf_address)s is %(status)s "
  676         "instead of %(hopestatus)s")
  677 
  678 
  679 class PciDeviceInvalidOwner(Invalid):
  680     message = _(
  681         "PCI device %(compute_node_id)s:%(address)s is owned by %(owner)s "
  682         "instead of %(hopeowner)s")
  683 
  684 
  685 class VolumeCreateFailed(Invalid):
  686     message = _("Volume Creation failed: %(creation_failed)s")
  687 
  688 
  689 class VolumeDeleteFailed(Invalid):
  690     message = _("Volume Deletion failed: %(deletion_failed)s")
  691 
  692 
  693 class SecurityGroupCannotBeApplied(Invalid):
  694     message = _("Security groups cannot apply to the container.")
  695 
  696 
  697 class SecurityGroupCannotBeRemoved(Invalid):
  698     message = _("Security groups cannot be removed from the container.")
  699 
  700 
  701 class ContainerActionNotFound(ZunException):
  702     message = _("Action for request_id %(request_id)s on container"
  703                 " %(container_uuid)s not fount")
  704 
  705 
  706 class ContainerActionEventNotFound(ZunException):
  707     message = _("Event %(event)s not found for action id %(action_id)s")
  708 
  709 
  710 class OverQuota(ZunException):
  711     message = _("Quota exceeded for resources: %(overs)s")
  712     code = 403
  713 
  714 
  715 class QuotaNotFound(NotFound):
  716     message = _("Quota could not be found.")
  717 
  718 
  719 class QuotaUsageNotFound(NotFound):
  720     message = _("Quota usage could not be found")
  721 
  722 
  723 class ProjectQuotaNotFound(QuotaNotFound):
  724     message = _("Quota for project %(project_id)s could not be found.")
  725 
  726 
  727 class QuotaAlreadyExists(ZunException):
  728     message = _("Quota already exists for project %(project_id)s, "
  729                 "resource %(resource)s.")
  730 
  731 
  732 class QuotaClassNotFound(QuotaNotFound):
  733     message = _("Quota class %(class_name)s could not be found.")
  734 
  735 
  736 class QuotaResourceUnknown(QuotaNotFound):
  737     message = _("Unknow quota resources %(unknown)s.")
  738 
  739 
  740 class Base64Exception(Invalid):
  741     message = _("Invalid Base 64 file data")
  742 
  743 
  744 class InvalidEncryptionKey(ZunException):
  745     message = _('Can not decrypt data with the auth_encryption_key '
  746                 'in zun config.')
  747 
  748 
  749 class InvalidReference(ZunException):
  750     message = _('invalid reference')
  751 
  752 
  753 class ReferenceInvalidFormat(InvalidReference):
  754     message = _('invalid reference format')
  755 
  756 
  757 class NameEmpty(InvalidReference):
  758     message = _('repository name must have at least one component')
  759 
  760 
  761 class NameTooLong(InvalidReference):
  762     message = _('repository name must not be more than %(length_max)s '
  763                 'characters')
  764 
  765 
  766 # An exception with this name is used on both sides of the placement/zun
  767 # interaction.
  768 class ResourceProviderInUse(ZunException):
  769     message = _("Resource provider has allocations.")
  770 
  771 
  772 class ResourceProviderRetrievalFailed(ZunException):
  773     message = _("Failed to get resource provider with UUID %(uuid)s")
  774 
  775 
  776 class ResourceProviderAggregateRetrievalFailed(ZunException):
  777     message = _("Failed to get aggregates for resource provider with UUID"
  778                 " %(uuid)s")
  779 
  780 
  781 class ResourceProviderTraitRetrievalFailed(ZunException):
  782     message = _("Failed to get traits for resource provider with UUID"
  783                 " %(uuid)s")
  784 
  785 
  786 class ResourceProviderCreationFailed(ZunException):
  787     message = _("Failed to create resource provider %(name)s")
  788 
  789 
  790 class ResourceProviderDeletionFailed(ZunException):
  791     message = _("Failed to delete resource provider %(uuid)s")
  792 
  793 
  794 class ResourceProviderUpdateFailed(ZunException):
  795     message = _("Failed to update resource provider via URL %(url)s: "
  796                 "%(error)s")
  797 
  798 
  799 class ResourceProviderNotFound(NotFound):
  800     message = _("No such resource provider %(name_or_uuid)s.")
  801 
  802 
  803 class ResourceProviderSyncFailed(ZunException):
  804     message = _("Failed to synchronize the placement service with resource "
  805                 "provider information supplied by the compute host.")
  806 
  807 
  808 class PlacementAPIConnectFailure(ZunException):
  809     message = _("Unable to communicate with the Placement API.")
  810 
  811 
  812 class PlacementAPIConflict(ZunException):
  813     """Any 409 error from placement APIs should use (a subclass of) this
  814     exception.
  815     """
  816     message = _("A conflict was encountered attempting to invoke the "
  817                 "placement API at URL %(url)s: %(error)s")
  818 
  819 
  820 class ResourceProviderUpdateConflict(PlacementAPIConflict):
  821     """A 409 caused by generation mismatch from attempting to update an
  822     existing provider record or its associated data (aggregates, traits, etc.).
  823     """
  824     message = _("A conflict was encountered attempting to update resource "
  825                 "provider %(uuid)s (generation %(generation)d): %(error)s")
  826 
  827 
  828 class InvalidResourceClass(Invalid):
  829     message = _("Resource class '%(resource_class)s' invalid.")
  830 
  831 
  832 class InvalidResourceAmount(Invalid):
  833     message = _("Resource amounts must be integers. Received '%(amount)s'.")
  834 
  835 
  836 class InvalidInventory(Invalid):
  837     message = _("Inventory for '%(resource_class)s' on "
  838                 "resource provider '%(resource_provider)s' invalid.")
  839 
  840 
  841 # An exception with this name is used on both sides of the placement/
  842 # nova interaction.
  843 class InventoryInUse(InvalidInventory):
  844     pass
  845 
  846 
  847 class UsagesRetrievalFailed(ZunException):
  848     message = _("Failed to retrieve usages for project '%(project_id)s' and "
  849                 "user '%(user_id)s'.")
  850 
  851 
  852 class AllocationUpdateFailed(ZunException):
  853     message = _('Failed to update allocations for consumer %(consumer_uuid)s. '
  854                 'Error: %(error)s')
  855 
  856 
  857 class ConsumerAllocationRetrievalFailed(ZunException):
  858     message = _("Failed to retrieve allocations for consumer "
  859                 "%(consumer_uuid)s: %(error)s")
  860 
  861 
  862 class TraitRetrievalFailed(ZunException):
  863     message = _("Failed to get traits for resource provider with UUID"
  864                 " %(uuid)s")
  865 
  866 
  867 class TraitCreationFailed(ZunException):
  868     message = _("Failed to create trait %(name)s: %(error)s")
  869 
  870 
  871 class AllocationMoveFailed(ZunException):
  872     message = _('Failed to move allocations from consumer %(source_consumer)s '
  873                 'to consumer %(target_consumer)s. '
  874                 'Error: %(error)s')
  875 
  876 
  877 class ResourceProviderAllocationRetrievalFailed(ZunException):
  878     message = _("Failed to retrieve allocations for resource provider "
  879                 "%(rp_uuid)s: %(error)s")
  880 
  881 
  882 class ComputeHostNotFound(NotFound):
  883     message = _("Compute host %(host)s could not be found.")
  884 
  885 
  886 class RequestedHostNotFound(NotFound):
  887     message = _("Requested host %(host)s could not be found.")
  888 
  889 
  890 class CNIError(ZunException):
  891     pass
  892 
  893 
  894 class ResourceNotReady(CNIError):
  895     message = _("Resource not ready: %(resource)s")