summaryrefslogtreecommitdiff
path: root/neutronclient/common/exceptions.py
blob: 443f781554c754042cc5b58dd1d1846e97e9f949 (plain)
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# Copyright 2011 VMware, Inc
# 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.

from oslo_utils import encodeutils

from neutronclient._i18n import _

"""
Neutron base exception handling.

Exceptions are classified into three categories:
* Exceptions corresponding to exceptions from neutron server:
  This type of exceptions should inherit one of exceptions
  in HTTP_EXCEPTION_MAP.
* Exceptions from client library:
  This type of exceptions should inherit NeutronClientException.
* Exceptions from CLI code:
  This type of exceptions should inherit NeutronCLIError.
"""


# NOTE: This method is defined here to avoid
# an import loop between common.utils and this module.
def _safe_decode_dict(kwargs):
    for k, v in kwargs.items():
        kwargs[k] = encodeutils.safe_decode(v)
    return kwargs


class NeutronException(Exception):
    """Base Neutron Exception.

    To correctly use this class, inherit from it and define
    a 'message' property. That message will get printf'd
    with the keyword arguments provided to the constructor.
    """
    message = _("An unknown exception occurred.")

    def __init__(self, message=None, **kwargs):
        if message:
            self.message = message
        try:
            self._error_string = self.message % _safe_decode_dict(kwargs)
        except Exception:
            # at least get the core message out if something happened
            self._error_string = self.message

    def __str__(self):
        return self._error_string


class NeutronClientException(NeutronException):
    """Base exception which exceptions from Neutron are mapped into.

    NOTE: on the client side, we use different exception types in order
    to allow client library users to handle server exceptions in try...except
    blocks. The actual error message is the one generated on the server side.
    """

    status_code = 0
    req_ids_msg = _("Neutron server returns request_ids: %s")
    request_ids = []

    def __init__(self, message=None, **kwargs):
        self.request_ids = kwargs.get('request_ids')
        if 'status_code' in kwargs:
            self.status_code = kwargs['status_code']
        if self.request_ids:
            req_ids_msg = self.req_ids_msg % self.request_ids
            if message:
                message = _('%(msg)s\n%(id)s') % {'msg': message,
                                                  'id': req_ids_msg}
            else:
                message = req_ids_msg
        super(NeutronClientException, self).__init__(message, **kwargs)


# Base exceptions from Neutron

class BadRequest(NeutronClientException):
    status_code = 400


class Unauthorized(NeutronClientException):
    status_code = 401
    message = _("Unauthorized: bad credentials.")


class Forbidden(NeutronClientException):
    status_code = 403
    message = _("Forbidden: your credentials don't give you access to this "
                "resource.")


class NotFound(NeutronClientException):
    status_code = 404


class Conflict(NeutronClientException):
    status_code = 409


class InternalServerError(NeutronClientException):
    status_code = 500


class ServiceUnavailable(NeutronClientException):
    status_code = 503


HTTP_EXCEPTION_MAP = {
    400: BadRequest,
    401: Unauthorized,
    403: Forbidden,
    404: NotFound,
    409: Conflict,
    500: InternalServerError,
    503: ServiceUnavailable,
}


# Exceptions mapped to Neutron server exceptions
# These are defined if a user of client library needs specific exception.
# Exception name should be <Neutron Exception Name> + 'Client'
# e.g., NetworkNotFound -> NetworkNotFoundClient

class NetworkNotFoundClient(NotFound):
    pass


class PortNotFoundClient(NotFound):
    pass


class StateInvalidClient(BadRequest):
    pass


class NetworkInUseClient(Conflict):
    pass


class PortInUseClient(Conflict):
    pass


class IpAddressInUseClient(Conflict):
    pass


class IpAddressAlreadyAllocatedClient(Conflict):
    pass


class InvalidIpForNetworkClient(BadRequest):
    pass


class InvalidIpForSubnetClient(BadRequest):
    pass


class OverQuotaClient(Conflict):
    pass


class IpAddressGenerationFailureClient(Conflict):
    pass


class MacAddressInUseClient(Conflict):
    pass


class HostNotCompatibleWithFixedIpsClient(Conflict):
    pass


class ExternalIpAddressExhaustedClient(BadRequest):
    pass


# Exceptions from client library

class NoAuthURLProvided(Unauthorized):
    message = _("auth_url was not provided to the Neutron client")


class EndpointNotFound(NeutronClientException):
    message = _("Could not find Service or Region in Service Catalog.")


class EndpointTypeNotFound(NeutronClientException):
    message = _("Could not find endpoint type %(type_)s in Service Catalog.")


class AmbiguousEndpoints(NeutronClientException):
    message = _("Found more than one matching endpoint in Service Catalog: "
                "%(matching_endpoints)")


class RequestURITooLong(NeutronClientException):
    """Raised when a request fails with HTTP error 414."""

    def __init__(self, **kwargs):
        self.excess = kwargs.get('excess', 0)
        super(RequestURITooLong, self).__init__(**kwargs)


class ConnectionFailed(NeutronClientException):
    message = _("Connection to neutron failed: %(reason)s")


class SslCertificateValidationError(NeutronClientException):
    message = _("SSL certificate validation has failed: %(reason)s")


class MalformedResponseBody(NeutronClientException):
    message = _("Malformed response body: %(reason)s")


class InvalidContentType(NeutronClientException):
    message = _("Invalid content type %(content_type)s.")


# Command line exceptions

class NeutronCLIError(NeutronException):
    """Exception raised when command line parsing fails."""
    pass


class CommandError(NeutronCLIError):
    pass


class UnsupportedVersion(NeutronCLIError):
    """Indicates usage of an unsupported API version

    Indicates that the user is trying to use an unsupported version of
    the API.
    """
    pass


class NeutronClientNoUniqueMatch(NeutronCLIError):
    message = _("Multiple %(resource)s matches found for name '%(name)s',"
                " use an ID to be more specific.")