File: exception.py

package info (click to toggle)
python-ironic-lib 7.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 532 kB
  • sloc: python: 3,631; makefile: 20; sh: 2
file content (201 lines) | stat: -rw-r--r-- 6,995 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    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.

"""Ironic base exception handling.

Includes decorator for re-raising Ironic-type exceptions.

SHOULD include dedicated exception logging.

"""

import collections
from http import client as http_client
import json
import logging

from oslo_config import cfg
from oslo_utils import excutils

from ironic_lib.common.i18n import _


LOG = logging.getLogger(__name__)

exc_log_opts = [
    cfg.BoolOpt('fatal_exception_format_errors',
                default=False,
                help=_('Used if there is a formatting error when generating '
                       'an exception message (a programming error). If True, '
                       'raise an exception; if False, use the unformatted '
                       'message.'),
                deprecated_group='DEFAULT'),
]

CONF = cfg.CONF
CONF.register_opts(exc_log_opts, group='ironic_lib')


def list_opts():
    """Entry point for oslo-config-generator."""
    return [('ironic_lib', exc_log_opts)]


def _ensure_exception_kwargs_serializable(exc_class_name, kwargs):
    """Ensure that kwargs are serializable

    Ensure that all kwargs passed to exception constructor can be passed over
    RPC, by trying to convert them to JSON, or, as a last resort, to string.
    If it is not possible, unserializable kwargs will be removed, letting the
    receiver to handle the exception string as it is configured to.

    :param exc_class_name: a IronicException class name.
    :param kwargs: a dictionary of keyword arguments passed to the exception
        constructor.
    :returns: a dictionary of serializable keyword arguments.
    """
    serializers = [(json.dumps, _('when converting to JSON')),
                   (str, _('when converting to string'))]
    exceptions = collections.defaultdict(list)
    serializable_kwargs = {}
    for k, v in kwargs.items():
        for serializer, msg in serializers:
            try:
                serializable_kwargs[k] = serializer(v)
                exceptions.pop(k, None)
                break
            except Exception as e:
                exceptions[k].append(
                    '(%(serializer_type)s) %(e_type)s: %(e_contents)s' %
                    {'serializer_type': msg, 'e_contents': e,
                     'e_type': e.__class__.__name__})
    if exceptions:
        LOG.error("One or more arguments passed to the %(exc_class)s "
                  "constructor as kwargs can not be serialized. The "
                  "serialized arguments: %(serialized)s. These "
                  "unserialized kwargs were dropped because of the "
                  "exceptions encountered during their "
                  "serialization:\n%(errors)s",
                  dict(errors=';\n'.join("%s: %s" % (k, '; '.join(v))
                                         for k, v in exceptions.items()),
                       exc_class=exc_class_name,
                       serialized=serializable_kwargs))
        # We might be able to actually put the following keys' values into
        # format string, but there is no guarantee, drop it just in case.
        for k in exceptions:
            del kwargs[k]
    return serializable_kwargs


class IronicException(Exception):
    """Base Ironic Exception

    To correctly use this class, inherit from it and define
    a '_msg_fmt' property. That _msg_fmt will get printf'd
    with the keyword arguments provided to the constructor.

    If you need to access the message from an exception you should use
    str(exc)

    """

    _msg_fmt = _("An unknown exception occurred.")
    code = 500
    headers = {}
    safe = False

    def __init__(self, message=None, **kwargs):
        self.kwargs = _ensure_exception_kwargs_serializable(
            self.__class__.__name__, kwargs)

        if 'code' not in self.kwargs:
            try:
                self.kwargs['code'] = self.code
            except AttributeError:
                pass
        else:
            self.code = int(kwargs['code'])

        if not message:
            try:
                message = self._msg_fmt % kwargs

            except Exception:
                with excutils.save_and_reraise_exception() as ctxt:
                    # kwargs doesn't match a variable in the message
                    # log the issue and the kwargs
                    prs = ', '.join('%s=%s' % pair for pair in kwargs.items())
                    LOG.exception('Exception in string format operation '
                                  '(arguments %s)', prs)
                    if not CONF.ironic_lib.fatal_exception_format_errors:
                        # at least get the core message out if something
                        # happened
                        message = self._msg_fmt
                        ctxt.reraise = False

        super(IronicException, self).__init__(message)


class InstanceDeployFailure(IronicException):
    _msg_fmt = _("Failed to deploy instance: %(reason)s")


class FileSystemNotSupported(IronicException):
    _msg_fmt = _("Failed to create a file system. "
                 "File system %(fs)s is not supported.")


class InvalidMetricConfig(IronicException):
    _msg_fmt = _("Invalid value for metrics config option: %(reason)s")


class ServiceLookupFailure(IronicException):
    _msg_fmt = _("Cannot find %(service)s service through multicast")


class ServiceRegistrationFailure(IronicException):
    _msg_fmt = _("Cannot register %(service)s service: %(error)s")


class BadRequest(IronicException):
    code = http_client.BAD_REQUEST


class Unauthorized(IronicException):
    code = http_client.UNAUTHORIZED
    headers = {'WWW-Authenticate': 'Basic realm="Baremetal API"'}


class ConfigInvalid(IronicException):
    _msg_fmt = _("Invalid configuration file. %(error_msg)s")


class CatalogNotFound(IronicException):
    _msg_fmt = _("Service type %(service_type)s with endpoint type "
                 "%(endpoint_type)s not found in keystone service catalog.")


class KeystoneUnauthorized(IronicException):
    _msg_fmt = _("Not authorized in Keystone.")


class KeystoneFailure(IronicException):
    pass


class MetricsNotSupported(IronicException):
    _msg_fmt = _("Metrics action is not supported. You may need to "
                 "adjust the [metrics] section in ironic.conf.")