Debian Codegraph @

neutron_lib/plugins/utils.py

raw
1 # Copyright 2013 Cisco Systems, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # 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, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
13 # under the License.
14
15 import collections
16 import contextlib
17 import hashlib
18
19 from oslo_config import cfg
20 from oslo_log import log as logging
21 from oslo_utils import encodeutils
22 from oslo_utils import excutils
23 from webob import exc as web_exc
24
25 from neutron_lib._i18n import _
26 from neutron_lib.api import attributes
27 from neutron_lib.api.definitions import network as net_apidef
28 from neutron_lib.api.definitions import port as port_apidef
29 from neutron_lib.api.definitions import portbindings as pb
30 from neutron_lib.api.definitions import portbindings_extended as pb_ext
31 from neutron_lib.api.definitions import subnet as subnet_apidef
32 from neutron_lib import constants
33 from neutron_lib import exceptions
34
35
36 LOG = logging.getLogger(__name__)
37 INTERFACE_HASH_LEN = 6
38
39
40 def _is_valid_range(val, min_val, max_val):
41 try:
42 # NOTE: use str value to not permit booleans
43 val = int(str(val))
44 return min_val <= val <= max_val
45 except (ValueError, TypeError):
46 return False
47
48
49 def is_valid_vlan_tag(vlan):
50 """Validate a VLAN tag.
51
52 :param vlan: The VLAN tag to validate.
53 :returns: True if vlan is a number that is a valid VLAN tag.
54 """
55 return _is_valid_range(
56 vlan, constants.MIN_VLAN_TAG, constants.MAX_VLAN_TAG)
57
58
59 def is_valid_gre_id(gre_id):
60 """Validate a GRE ID.
61
62 :param gre_id: The GRE ID to validate.
63 :returns: True if gre_id is a number that's a valid GRE ID.
64 """
65 return _is_valid_range(
66 gre_id, constants.MIN_GRE_ID, constants.MAX_GRE_ID)
67
68
69 def is_valid_vxlan_vni(vni):
70 """Validate a VXLAN VNI.
71
72 :param vni: The VNI to validate.
73 :returns: True if vni is a number that's a valid VXLAN VNI.
74 """
75 return _is_valid_range(
76 vni, constants.MIN_VXLAN_VNI, constants.MAX_VXLAN_VNI)
77
78
79 def is_valid_geneve_vni(vni):
80 """Validate a Geneve VNI
81
82 :param vni: The VNI to validate.
83 :returns: True if vni is a number that's a valid Geneve VNI.
84 """
85 return _is_valid_range(
86 vni, constants.MIN_GENEVE_VNI, constants.MAX_GENEVE_VNI)
87
88
89 _TUNNEL_MAPPINGS = {
90 constants.TYPE_GRE: is_valid_gre_id,
91 constants.TYPE_VXLAN: is_valid_vxlan_vni,
92 constants.TYPE_GENEVE: is_valid_geneve_vni
93 }
94
95
96 def verify_tunnel_range(tunnel_range, tunnel_type):
97 """Verify a given tunnel range is valid given it's tunnel type.
98
99 Existing validation is done for GRE, VXLAN and GENEVE types as per
100 _TUNNEL_MAPPINGS.
101
102 :param tunnel_range: An iterable who's 0 index is the min tunnel range
103 and who's 1 index is the max tunnel range.
104 :param tunnel_type: The tunnel type of the range.
105 :returns: None if the tunnel_range is valid.
106 :raises: NetworkTunnelRangeError if tunnel_range is invalid.
107 """
108 if tunnel_type in _TUNNEL_MAPPINGS:
109 for ident in tunnel_range:
110 if not _TUNNEL_MAPPINGS[tunnel_type](ident):
111 raise exceptions.NetworkTunnelRangeError(
112 tunnel_range=tunnel_range,
113 error=_("%(id)s is not a valid %(type)s identifier") %
114 {'id': ident, 'type': tunnel_type})
115 if tunnel_range[1] < tunnel_range[0]:
116 raise exceptions.NetworkTunnelRangeError(
117 tunnel_range=tunnel_range,
118 error=_("End of tunnel range is less "
119 "than start of tunnel range"))
120
121
122 def _raise_invalid_tag(vlan_str, vlan_range):
123 """Raise an exception for invalid tag."""
124 raise exceptions.NetworkVlanRangeError(
125 vlan_range=vlan_range,
126 error=_("%s is not a valid VLAN tag") % vlan_str)
127
128
129 def verify_vlan_range(vlan_range):
130 """Verify a VLAN range is valid.
131
132 :param vlan_range: An iterable who's 0 index is the min tunnel range
133 and who's 1 index is the max tunnel range.
134 :returns: None if the vlan_range is valid.
135 :raises: NetworkVlanRangeError if vlan_range is not valid.
136 """
137 for vlan_tag in vlan_range:
138 if not is_valid_vlan_tag(vlan_tag):
139 _raise_invalid_tag(str(vlan_tag), vlan_range)
140 if vlan_range[1] < vlan_range[0]:
141 raise exceptions.NetworkVlanRangeError(
142 vlan_range=vlan_range,
143 error=_("End of VLAN range is less than start of VLAN range"))
144
145
146 def parse_network_vlan_range(network_vlan_range):
147 """Parse a well formed network VLAN range string.
148
149 The network VLAN range string has the format:
150 network[:vlan_begin:vlan_end]
151
152 :param network_vlan_range: The network VLAN range string to parse.
153 :returns: A tuple who's 1st element is the network name and 2nd
154 element is the VLAN range parsed from network_vlan_range.
155 :raises: NetworkVlanRangeError if network_vlan_range is malformed.
156 PhysicalNetworkNameError if network_vlan_range is missing a network
157 name.
158 """
159 entry = network_vlan_range.strip()
160 if ':' in entry:
161 if entry.count(':') != 2:
162 raise exceptions.NetworkVlanRangeError(
163 vlan_range=entry,
164 error=_("Need exactly two values for VLAN range"))
165 network, vlan_min, vlan_max = entry.split(':')
166 if not network:
167 raise exceptions.PhysicalNetworkNameError()
168
169 try:
170 vlan_min = int(vlan_min)
171 except ValueError:
172 _raise_invalid_tag(vlan_min, entry)
173
174 try:
175 vlan_max = int(vlan_max)
176 except ValueError:
177 _raise_invalid_tag(vlan_max, entry)
178
179 vlan_range = (vlan_min, vlan_max)
180 verify_vlan_range(vlan_range)
181 return network, vlan_range
182 else:
183 return entry, None
184
185
186 def parse_network_vlan_ranges(network_vlan_ranges_cfg_entries):
187 """Parse a list of well formed network VLAN range string.
188
189 Behaves like parse_network_vlan_range, but parses a list of
190 network VLAN strings into an ordered dict.
191
192 :param network_vlan_ranges_cfg_entries: The list of network VLAN
193 strings to parse.
194 :returns: An OrderedDict who's keys are network names and values are
195 the list of VLAN ranges parsed.
196 :raises: See parse_network_vlan_range.
197 """
198 networks = collections.OrderedDict()
199 for entry in network_vlan_ranges_cfg_entries:
200 network, vlan_range = parse_network_vlan_range(entry)
201 if vlan_range:
202 if networks.get(network) == [constants.VLAN_VALID_RANGE]:
203 continue
204 networks.setdefault(network, []).append(vlan_range)
205 else:
206 networks[network] = [constants.VLAN_VALID_RANGE]
207 return networks
208
209
210 def in_pending_status(status):
211 """Return True if status is a form of pending"""
212 return status in (constants.PENDING_CREATE,
213 constants.PENDING_UPDATE,
214 constants.PENDING_DELETE)
215
216
217 @contextlib.contextmanager
218 def delete_port_on_error(core_plugin, context, port_id):
219 """A decorator that deletes a port upon exception.
220
221 This decorator can be used to wrap a block of code that
222 should delete a port if an exception is raised during the block's
223 execution.
224
225 :param core_plugin: The core plugin implementing the delete_port method to
226 call.
227 :param context: The context.
228 :param port_id: The port's ID.
229 :returns: None
230 """
231 try:
232 yield
233 except Exception:
234 with excutils.save_and_reraise_exception():
235 try:
236 core_plugin.delete_port(context, port_id,
237 l3_port_check=False)
238 except exceptions.PortNotFound:
239 LOG.debug("Port %s not found", port_id)
240 except Exception:
241 LOG.exception("Failed to delete port: %s", port_id)
242
243
244 @contextlib.contextmanager
245 def update_port_on_error(core_plugin, context, port_id, revert_value):
246 """A decorator that updates a port upon exception.
247
248 This decorator can be used to wrap a block of code that
249 should update a port if an exception is raised during the block's
250 execution.
251
252 :param core_plugin: The core plugin implementing the update_port method to
253 call.
254 :param context: The context.
255 :param port_id: The port's ID.
256 :param revert_value: The value to revert on the port object.
257 :returns: None
258 """
259 try:
260 yield
261 except Exception:
262 with excutils.save_and_reraise_exception():
263 try:
264 core_plugin.update_port(context, port_id,
265 {'port': revert_value})
266 except Exception:
267 LOG.exception("Failed to update port: %s", port_id)
268
269
270 def get_interface_name(name, prefix='', max_len=constants.DEVICE_NAME_MAX_LEN):
271 """Construct an interface name based on the prefix and name.
272
273 The interface name can not exceed the maximum length passed in. Longer
274 names are hashed to help ensure uniqueness.
275 """
276 requested_name = prefix + name
277
278 if len(requested_name) <= max_len:
279 return requested_name
280
281 # We can't just truncate because interfaces may be distinguished
282 # by an ident at the end. A hash over the name should be unique.
283 # Leave part of the interface name on for easier identification
284 if (len(prefix) + INTERFACE_HASH_LEN) > max_len:
285 raise ValueError(_("Too long prefix provided. New name would exceed "
286 "given length for an interface name."))
287
288 namelen = max_len - len(prefix) - INTERFACE_HASH_LEN
289 hashed_name = hashlib.new('sha1', usedforsecurity=False)
290 hashed_name.update(encodeutils.to_utf8(name))
291 new_name = (
292 f'{prefix}{name[0:namelen]}'
293 f'{hashed_name.hexdigest()[0:INTERFACE_HASH_LEN]}')
294 LOG.info("The requested interface name %(requested_name)s exceeds the "
295 "%(limit)d character limitation. It was shortened to "
296 "%(new_name)s to fit.",
297 {'requested_name': requested_name,
298 'limit': max_len, 'new_name': new_name})
299 return new_name
300
301
302 def _fixup_res_dict(context, attr_name, res_dict, check_allow_post=True):
303 attr_info = attributes.RESOURCES[attr_name]
304 attr_ops = attributes.AttributeInfo(attr_info)
305 try:
306 attr_ops.populate_project_id(context, res_dict, True)
307 attributes.populate_project_info(attr_info)
308 attr_ops.verify_attributes(res_dict)
309 except web_exc.HTTPBadRequest as e:
310 # convert webob exception into ValueError as these functions are
311 # for internal use. webob exception doesn't make sense.
312 raise ValueError(e.detail) from e
313 attr_ops.fill_post_defaults(res_dict, check_allow_post=check_allow_post)
314 attr_ops.convert_values(res_dict)
315 return res_dict
316
317
318 def create_network(core_plugin, context, net, check_allow_post=True):
319 net_data = _fixup_res_dict(context, net_apidef.COLLECTION_NAME,
320 net.get(net_apidef.RESOURCE_NAME, {}),
321 check_allow_post=check_allow_post)
322 return core_plugin.create_network(
323 context, {net_apidef.RESOURCE_NAME: net_data})
324
325
326 def create_subnet(core_plugin, context, subnet, check_allow_post=True):
327 subnet_data = _fixup_res_dict(context, subnet_apidef.COLLECTION_NAME,
328 subnet.get(subnet_apidef.RESOURCE_NAME, {}),
329 check_allow_post=check_allow_post)
330 return core_plugin.create_subnet(
331 context, {subnet_apidef.RESOURCE_NAME: subnet_data})
332
333
334 def create_port(core_plugin, context, port, check_allow_post=True):
335 port_data = _fixup_res_dict(context, port_apidef.COLLECTION_NAME,
336 port.get(port_apidef.RESOURCE_NAME, {}),
337 check_allow_post=check_allow_post)
338 return core_plugin.create_port(
339 context, {port_apidef.RESOURCE_NAME: port_data})
340
341
342 def get_deployment_physnet_mtu():
343 """Retrieves global physical network MTU setting.
344
345 Plugins should use this function to retrieve the MTU set by the operator
346 that is equal to or less than the MTU of their nodes' physical interfaces.
347 Note that it is the responsibility of the plugin to deduct the value of
348 any encapsulation overhead required before advertising it to VMs.
349
350 Note that this function depends on the global_physnet_mtu config option
351 being registered in the global CONF.
352
353 :returns: The global_physnet_mtu from the global CONF.
354 """
355 return cfg.CONF.global_physnet_mtu
356
357
358 def get_port_binding_by_status_and_host(bindings, status, host='',
359 raise_if_not_found=False,
360 port_id=None):
361 """Returns from an iterable the binding with the specified status and host.
362
363 The input iterable can contain zero or one binding in status ACTIVE
364 and zero or many bindings in status INACTIVE. As a consequence, to
365 unequivocally retrieve an inactive binding, the caller must specify a non
366 empty value for host. If host is the empty string, the first binding
367 satisfying the specified status will be returned. If no binding is found
368 with the specified status and host, None is returned or PortBindingNotFound
369 is raised if raise_if_not_found is True
370
371 :param bindings: An iterable containing port bindings
372 :param status: The status of the port binding to return. Possible values
373 are ACTIVE or INACTIVE as defined in
374 :file:`neutron_lib/constants.py`.
375 :param host: str representing the host of the binding to return.
376 :param raise_if_not_found: If a binding is not found and this parameter is
377 True, a PortBindingNotFound exception is raised
378 :param port_id: The id of the binding's port
379 :returns: The searched for port binding or None if it is not found
380 :raises: PortBindingNotFound if the binding is not found and
381 raise_if_not_found is True
382 """
383 for binding in bindings:
384 if binding[pb_ext.STATUS] == status:
385 if not host or binding[pb_ext.HOST] == host:
386 return binding
387 if raise_if_not_found:
388 raise exceptions.PortBindingNotFound(port_id=port_id, host=host)
389
390
391 def can_port_be_bound_to_virtual_bridge(port):
392 """Returns if port can be bound to a virtual bridge (e.g.: LB, OVS)
393
394 :param port: (dict) A port dictionary.
395 :returns: True if the port VNIC type is 'normal' or 'smart-nic'; False in
396 any other case.
397 """
398 return port[pb.VNIC_TYPE] in [pb.VNIC_NORMAL, pb.VNIC_SMARTNIC]