bbfbb2ff275813e37dc9bd651840af4aff31f6aa
[openstack-build/neutron-build.git] / neutron / common / exceptions.py
1 # Copyright 2011 VMware, Inc
2 # All Rights Reserved.
3 #
4 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
5 #    not use this file except in compliance with the License. You may obtain
6 #    a copy of the License at
7 #
8 #         http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #    Unless required by applicable law or agreed to in writing, software
11 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 #    License for the specific language governing permissions and limitations
14 #    under the License.
15
16 """
17 Neutron base exception handling.
18 """
19
20 from oslo_utils import excutils
21 import six
22
23 from neutron._i18n import _
24
25
26 class NeutronException(Exception):
27     """Base Neutron Exception.
28
29     To correctly use this class, inherit from it and define
30     a 'message' property. That message will get printf'd
31     with the keyword arguments provided to the constructor.
32     """
33     message = _("An unknown exception occurred.")
34
35     def __init__(self, **kwargs):
36         try:
37             super(NeutronException, self).__init__(self.message % kwargs)
38             self.msg = self.message % kwargs
39         except Exception:
40             with excutils.save_and_reraise_exception() as ctxt:
41                 if not self.use_fatal_exceptions():
42                     ctxt.reraise = False
43                     # at least get the core message out if something happened
44                     super(NeutronException, self).__init__(self.message)
45
46     if six.PY2:
47         def __unicode__(self):
48             return unicode(self.msg)
49
50     def __str__(self):
51         return self.msg
52
53     def use_fatal_exceptions(self):
54         return False
55
56
57 class BadRequest(NeutronException):
58     message = _('Bad %(resource)s request: %(msg)s.')
59
60
61 class NotFound(NeutronException):
62     pass
63
64
65 class Conflict(NeutronException):
66     pass
67
68
69 class NotAuthorized(NeutronException):
70     message = _("Not authorized.")
71
72
73 class ServiceUnavailable(NeutronException):
74     message = _("The service is unavailable.")
75
76
77 class AdminRequired(NotAuthorized):
78     message = _("User does not have admin privileges: %(reason)s.")
79
80
81 class ObjectNotFound(NotFound):
82     message = _("Object %(id)s not found.")
83
84
85 class NetworkNotFound(NotFound):
86     message = _("Network %(net_id)s could not be found.")
87
88
89 class SubnetNotFound(NotFound):
90     message = _("Subnet %(subnet_id)s could not be found.")
91
92
93 class SubnetPoolNotFound(NotFound):
94     message = _("Subnet pool %(subnetpool_id)s could not be found.")
95
96
97 class PortNotFound(NotFound):
98     message = _("Port %(port_id)s could not be found.")
99
100
101 class QosPolicyNotFound(NotFound):
102     message = _("QoS policy %(policy_id)s could not be found.")
103
104
105 class QosRuleNotFound(NotFound):
106     message = _("QoS rule %(rule_id)s for policy %(policy_id)s "
107                 "could not be found.")
108
109
110 class PortNotFoundOnNetwork(NotFound):
111     message = _("Port %(port_id)s could not be found "
112                 "on network %(net_id)s.")
113
114
115 class PortQosBindingNotFound(NotFound):
116     message = _("QoS binding for port %(port_id)s and policy %(policy_id)s "
117                 "could not be found.")
118
119
120 class NetworkQosBindingNotFound(NotFound):
121     message = _("QoS binding for network %(net_id)s and policy %(policy_id)s "
122                 "could not be found.")
123
124
125 class PolicyFileNotFound(NotFound):
126     message = _("Policy configuration policy.json could not be found.")
127
128
129 class PolicyInitError(NeutronException):
130     message = _("Failed to init policy %(policy)s because %(reason)s.")
131
132
133 class PolicyCheckError(NeutronException):
134     message = _("Failed to check policy %(policy)s because %(reason)s.")
135
136
137 class StateInvalid(BadRequest):
138     message = _("Unsupported port state: %(port_state)s.")
139
140
141 class InUse(NeutronException):
142     message = _("The resource is in use.")
143
144
145 class QosPolicyInUse(InUse):
146     message = _("QoS Policy %(policy_id)s is used by "
147                 "%(object_type)s %(object_id)s.")
148
149
150 class NetworkInUse(InUse):
151     message = _("Unable to complete operation on network %(net_id)s. "
152                 "There are one or more ports still in use on the network.")
153
154
155 class SubnetInUse(InUse):
156     message = _("Unable to complete operation on subnet %(subnet_id)s "
157                 "%(reason)s.")
158
159     def __init__(self, **kwargs):
160         if 'reason' not in kwargs:
161             kwargs['reason'] = _("One or more ports have an IP allocation "
162                                  "from this subnet.")
163         super(SubnetInUse, self).__init__(**kwargs)
164
165
166 class SubnetPoolInUse(InUse):
167     message = _("Unable to complete operation on subnet pool "
168                 "%(subnet_pool_id)s. %(reason)s.")
169
170     def __init__(self, **kwargs):
171         if 'reason' not in kwargs:
172             kwargs['reason'] = _("Two or more concurrent subnets allocated.")
173         super(SubnetPoolInUse, self).__init__(**kwargs)
174
175
176 class PortInUse(InUse):
177     message = _("Unable to complete operation on port %(port_id)s "
178                 "for network %(net_id)s. Port already has an attached "
179                 "device %(device_id)s.")
180
181
182 class ServicePortInUse(InUse):
183     message = _("Port %(port_id)s cannot be deleted directly via the "
184                 "port API: %(reason)s.")
185
186
187 class DhcpPortInUse(InUse):
188     message = _("Port %(port_id)s is already acquired by another DHCP agent")
189
190
191 class PortBound(InUse):
192     message = _("Unable to complete operation on port %(port_id)s, "
193                 "port is already bound, port type: %(vif_type)s, "
194                 "old_mac %(old_mac)s, new_mac %(new_mac)s.")
195
196
197 class MacAddressInUse(InUse):
198     message = _("Unable to complete operation for network %(net_id)s. "
199                 "The mac address %(mac)s is in use.")
200
201
202 class HostRoutesExhausted(BadRequest):
203     # NOTE(xchenum): probably make sense to use quota exceeded exception?
204     message = _("Unable to complete operation for %(subnet_id)s. "
205                 "The number of host routes exceeds the limit %(quota)s.")
206
207
208 class DNSNameServersExhausted(BadRequest):
209     # NOTE(xchenum): probably make sense to use quota exceeded exception?
210     message = _("Unable to complete operation for %(subnet_id)s. "
211                 "The number of DNS nameservers exceeds the limit %(quota)s.")
212
213
214 class InvalidIpForNetwork(BadRequest):
215     message = _("IP address %(ip_address)s is not a valid IP "
216                 "for any of the subnets on the specified network.")
217
218
219 class InvalidIpForSubnet(BadRequest):
220     message = _("IP address %(ip_address)s is not a valid IP "
221                 "for the specified subnet.")
222
223
224 class IpAddressInUse(InUse):
225     message = _("Unable to complete operation for network %(net_id)s. "
226                 "The IP address %(ip_address)s is in use.")
227
228
229 class VlanIdInUse(InUse):
230     message = _("Unable to create the network. "
231                 "The VLAN %(vlan_id)s on physical network "
232                 "%(physical_network)s is in use.")
233
234
235 class FlatNetworkInUse(InUse):
236     message = _("Unable to create the flat network. "
237                 "Physical network %(physical_network)s is in use.")
238
239
240 class TunnelIdInUse(InUse):
241     message = _("Unable to create the network. "
242                 "The tunnel ID %(tunnel_id)s is in use.")
243
244
245 class TenantNetworksDisabled(ServiceUnavailable):
246     message = _("Tenant network creation is not enabled.")
247
248
249 class ResourceExhausted(ServiceUnavailable):
250     pass
251
252
253 class NoNetworkAvailable(ResourceExhausted):
254     message = _("Unable to create the network. "
255                 "No tenant network is available for allocation.")
256
257
258 class NoNetworkFoundInMaximumAllowedAttempts(ServiceUnavailable):
259     message = _("Unable to create the network. "
260                 "No available network found in maximum allowed attempts.")
261
262
263 class SubnetMismatchForPort(BadRequest):
264     message = _("Subnet on port %(port_id)s does not match "
265                 "the requested subnet %(subnet_id)s.")
266
267
268 class MalformedRequestBody(BadRequest):
269     message = _("Malformed request body: %(reason)s.")
270
271
272 class Invalid(NeutronException):
273     def __init__(self, message=None):
274         self.message = message
275         super(Invalid, self).__init__()
276
277
278 class InvalidInput(BadRequest):
279     message = _("Invalid input for operation: %(error_message)s.")
280
281
282 class InvalidAllocationPool(BadRequest):
283     message = _("The allocation pool %(pool)s is not valid.")
284
285
286 class UnsupportedPortDeviceOwner(Conflict):
287     message = _("Operation %(op)s is not supported for device_owner "
288                 "%(device_owner)s on port %(port_id)s.")
289
290
291 class OverlappingAllocationPools(Conflict):
292     message = _("Found overlapping allocation pools: "
293                 "%(pool_1)s %(pool_2)s for subnet %(subnet_cidr)s.")
294
295
296 class OutOfBoundsAllocationPool(BadRequest):
297     message = _("The allocation pool %(pool)s spans "
298                 "beyond the subnet cidr %(subnet_cidr)s.")
299
300
301 class MacAddressGenerationFailure(ServiceUnavailable):
302     message = _("Unable to generate unique mac on network %(net_id)s.")
303
304
305 class IpAddressGenerationFailure(Conflict):
306     message = _("No more IP addresses available on network %(net_id)s.")
307
308
309 class BridgeDoesNotExist(NeutronException):
310     message = _("Bridge %(bridge)s does not exist.")
311
312
313 class PreexistingDeviceFailure(NeutronException):
314     message = _("Creation failed. %(dev_name)s already exists.")
315
316
317 class QuotaResourceUnknown(NotFound):
318     message = _("Unknown quota resources %(unknown)s.")
319
320
321 class OverQuota(Conflict):
322     message = _("Quota exceeded for resources: %(overs)s.")
323
324
325 class QuotaMissingTenant(BadRequest):
326     message = _("Tenant-id was missing from quota request.")
327
328
329 class InvalidQuotaValue(Conflict):
330     message = _("Change would make usage less than 0 for the following "
331                 "resources: %(unders)s.")
332
333
334 class InvalidSharedSetting(Conflict):
335     message = _("Unable to reconfigure sharing settings for network "
336                 "%(network)s. Multiple tenants are using it.")
337
338
339 class InvalidExtensionEnv(BadRequest):
340     message = _("Invalid extension environment: %(reason)s.")
341
342
343 class ExtensionsNotFound(NotFound):
344     message = _("Extensions not found: %(extensions)s.")
345
346
347 class InvalidContentType(NeutronException):
348     message = _("Invalid content type %(content_type)s.")
349
350
351 class ExternalIpAddressExhausted(BadRequest):
352     message = _("Unable to find any IP address on external "
353                 "network %(net_id)s.")
354
355
356 class TooManyExternalNetworks(NeutronException):
357     message = _("More than one external network exists.")
358
359
360 class InvalidConfigurationOption(NeutronException):
361     message = _("An invalid value was provided for %(opt_name)s: "
362                 "%(opt_value)s.")
363
364
365 class GatewayConflictWithAllocationPools(InUse):
366     message = _("Gateway ip %(ip_address)s conflicts with "
367                 "allocation pool %(pool)s.")
368
369
370 class GatewayIpInUse(InUse):
371     message = _("Current gateway ip %(ip_address)s already in use "
372                 "by port %(port_id)s. Unable to update.")
373
374
375 class NetworkVlanRangeError(NeutronException):
376     message = _("Invalid network VLAN range: '%(vlan_range)s' - '%(error)s'.")
377
378     def __init__(self, **kwargs):
379         # Convert vlan_range tuple to 'start:end' format for display
380         if isinstance(kwargs['vlan_range'], tuple):
381             kwargs['vlan_range'] = "%d:%d" % kwargs['vlan_range']
382         super(NetworkVlanRangeError, self).__init__(**kwargs)
383
384
385 class PhysicalNetworkNameError(NeutronException):
386     message = _("Empty physical network name.")
387
388
389 class NetworkTunnelRangeError(NeutronException):
390     message = _("Invalid network tunnel range: "
391                 "'%(tunnel_range)s' - %(error)s.")
392
393     def __init__(self, **kwargs):
394         # Convert tunnel_range tuple to 'start:end' format for display
395         if isinstance(kwargs['tunnel_range'], tuple):
396             kwargs['tunnel_range'] = "%d:%d" % kwargs['tunnel_range']
397         super(NetworkTunnelRangeError, self).__init__(**kwargs)
398
399
400 class NetworkVxlanPortRangeError(NeutronException):
401     message = _("Invalid network VXLAN port range: '%(vxlan_range)s'.")
402
403
404 class VxlanNetworkUnsupported(NeutronException):
405     message = _("VXLAN network unsupported.")
406
407
408 class DuplicatedExtension(NeutronException):
409     message = _("Found duplicate extension: %(alias)s.")
410
411
412 class DeviceIDNotOwnedByTenant(Conflict):
413     message = _("The following device_id %(device_id)s is not owned by your "
414                 "tenant or matches another tenants router.")
415
416
417 class InvalidCIDR(BadRequest):
418     message = _("Invalid CIDR %(input)s given as IP prefix.")
419
420
421 class RouterNotCompatibleWithAgent(NeutronException):
422     message = _("Router '%(router_id)s' is not compatible with this agent.")
423
424
425 class DvrHaRouterNotSupported(NeutronException):
426     message = _("Router '%(router_id)s' cannot be both DVR and HA.")
427
428
429 class FailToDropPrivilegesExit(SystemExit):
430     """Exit exception raised when a drop privileges action fails."""
431     code = 99
432
433
434 class FloatingIpSetupException(NeutronException):
435     def __init__(self, message=None):
436         self.message = message
437         super(FloatingIpSetupException, self).__init__()
438
439
440 class IpTablesApplyException(NeutronException):
441     def __init__(self, message=None):
442         self.message = message
443         super(IpTablesApplyException, self).__init__()
444
445
446 class NetworkIdOrRouterIdRequiredError(NeutronException):
447     message = _('Both network_id and router_id are None. '
448                 'One must be provided.')
449
450
451 class AbortSyncRouters(NeutronException):
452     message = _("Aborting periodic_sync_routers_task due to an error.")
453
454
455 # Shared *aas exceptions, pending them being refactored out of Neutron
456 # proper.
457
458 class FirewallInternalDriverError(NeutronException):
459     """Fwaas exception for all driver errors.
460
461     On any failure or exception in the driver, driver should log it and
462     raise this exception to the agent
463     """
464     message = _("%(driver)s: Internal driver error.")
465
466
467 class MissingMinSubnetPoolPrefix(BadRequest):
468     message = _("Unspecified minimum subnet pool prefix.")
469
470
471 class EmptySubnetPoolPrefixList(BadRequest):
472     message = _("Empty subnet pool prefix list.")
473
474
475 class PrefixVersionMismatch(BadRequest):
476     message = _("Cannot mix IPv4 and IPv6 prefixes in a subnet pool.")
477
478
479 class UnsupportedMinSubnetPoolPrefix(BadRequest):
480     message = _("Prefix '%(prefix)s' not supported in IPv%(version)s pool.")
481
482
483 class IllegalSubnetPoolPrefixBounds(BadRequest):
484     message = _("Illegal prefix bounds: %(prefix_type)s=%(prefixlen)s, "
485                 "%(base_prefix_type)s=%(base_prefixlen)s.")
486
487
488 class IllegalSubnetPoolPrefixUpdate(BadRequest):
489     message = _("Illegal update to prefixes: %(msg)s.")
490
491
492 class SubnetAllocationError(NeutronException):
493     message = _("Failed to allocate subnet: %(reason)s.")
494
495
496 class AddressScopePrefixConflict(Conflict):
497     message = _("Failed to associate address scope: subnetpools "
498                 "within an address scope must have unique prefixes.")
499
500
501 class IllegalSubnetPoolAssociationToAddressScope(BadRequest):
502     message = _("Illegal subnetpool association: subnetpool %(subnetpool_id)s "
503                 "cannot be associated with address scope "
504                 "%(address_scope_id)s.")
505
506
507 class IllegalSubnetPoolIpVersionAssociationToAddressScope(BadRequest):
508     message = _("Illegal subnetpool association: subnetpool %(subnetpool_id)s "
509                 "cannot associate with address scope %(address_scope_id)s "
510                 "because subnetpool ip_version is not %(ip_version)s.")
511
512
513 class IllegalSubnetPoolUpdate(BadRequest):
514     message = _("Illegal subnetpool update : %(reason)s.")
515
516
517 class MinPrefixSubnetAllocationError(BadRequest):
518     message = _("Unable to allocate subnet with prefix length %(prefixlen)s, "
519                 "minimum allowed prefix is %(min_prefixlen)s.")
520
521
522 class MaxPrefixSubnetAllocationError(BadRequest):
523     message = _("Unable to allocate subnet with prefix length %(prefixlen)s, "
524                 "maximum allowed prefix is %(max_prefixlen)s.")
525
526
527 class SubnetPoolDeleteError(BadRequest):
528     message = _("Unable to delete subnet pool: %(reason)s.")
529
530
531 class SubnetPoolQuotaExceeded(OverQuota):
532     message = _("Per-tenant subnet pool prefix quota exceeded.")
533
534
535 class DeviceNotFoundError(NeutronException):
536     message = _("Device '%(device_name)s' does not exist.")
537
538
539 class NetworkSubnetPoolAffinityError(BadRequest):
540     message = _("Subnets hosted on the same network must be allocated from "
541                 "the same subnet pool.")
542
543
544 class ObjectActionError(NeutronException):
545     message = _('Object action %(action)s failed because: %(reason)s.')
546
547
548 class CTZoneExhaustedError(NeutronException):
549     message = _("IPtables conntrack zones exhausted, iptables rules cannot "
550                 "be applied.")