Debian Codegraph @

neutron_lib/api/converters.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License"); you may
2 # not use this file except in compliance with the License. You may obtain
3 # a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 # License for the specific language governing permissions and limitations
11 # under the License.
12
13 import copy
14 import uuid
15
16 import netaddr
17
18 from oslo_config import cfg
19 from oslo_utils import strutils
20
21 from neutron_lib._i18n import _
22 from neutron_lib.api import validators
23 from neutron_lib import constants
24 from neutron_lib import exceptions as n_exc
25 from neutron_lib.placement import utils as pl_utils
26 from neutron_lib.utils import net as net_utils
27
28
29 def convert_to_boolean(data):
30 """Convert a data value into a python bool.
31
32 :param data: The data value to convert to a python bool. This function
33 supports string types, bools, and ints for conversion of representation
34 to python bool.
35 :returns: The bool value of 'data' if it can be coerced.
36 :raises InvalidInput: If the value can't be coerced to a python bool.
37 """
38 try:
39 return strutils.bool_from_string(data, strict=True)
40 except ValueError as e:
41 msg = _("'%s' cannot be converted to boolean") % data
42 raise n_exc.InvalidInput(error_message=msg) from e
43
44
45 def convert_to_boolean_if_not_none(data):
46 """Uses convert_to_boolean() on the data if the data is not None.
47
48 :param data: The data value to convert.
49 :returns: The 'data' returned from convert_to_boolean() if 'data' is not
50 None. None is returned if data is None.
51 """
52 if data is not None:
53 return convert_to_boolean(data)
54
55
56 def convert_to_int(data):
57 """Convert a data value to a python int.
58
59 :param data: The data value to convert to a python int via python's
60 built-in int() constructor.
61 :returns: The int value of the data.
62 :raises InvalidInput: If the value can't be converted to an int.
63 """
64 try:
65 return int(data)
66 except (ValueError, TypeError) as e:
67 msg = _("'%s' is not an integer") % data
68 raise n_exc.InvalidInput(error_message=msg) from e
69
70
71 def convert_to_int_if_not_none(data):
72 """Uses convert_to_int() on the data if the data is not None.
73
74 :param data: The data value to convert.
75 :returns: The 'data' returned from convert_to_int() if 'data' is not None.
76 None is returned if data is None.
77 """
78 if data is not None:
79 return convert_to_int(data)
80 return data
81
82
83 def convert_to_positive_float_or_none(val):
84 """Converts a value to a python float if the value is positive.
85
86 :param val: The value to convert to a positive python float.
87 :returns: The value as a python float. If the val is None, None is
88 returned.
89 :raises ValueError, InvalidInput: A ValueError is raised if the 'val'
90 is a float, but is negative. InvalidInput is raised if 'val' can't be
91 converted to a python float.
92 """
93 # NOTE(salv-orlando): This conversion function is currently used by
94 # a vendor specific extension only at the moment It is used for
95 # port's RXTX factor in neutron.plugins.vmware.extensions.qos.
96 # It is deemed however generic enough to be in this module as it
97 # might be used in future for other API attributes.
98 if val is None:
99 return
100 try:
101 val = float(val)
102 if val < 0:
103 raise ValueError()
104 except (ValueError, TypeError) as e:
105 msg = _("'%s' must be a non negative decimal") % val
106 raise n_exc.InvalidInput(error_message=msg) from e
107 return val
108
109
110 def convert_kvp_str_to_list(data):
111 """Convert a value of the form 'key=value' to ['key', 'value'].
112
113 :param data: The string to parse for a key value pair.
114 :returns: A list where element 0 is the key and element 1 is the value.
115 :raises InvalidInput: If 'data' is not a key value string.
116 """
117 kvp = [x.strip() for x in data.split('=', 1)]
118 if len(kvp) == 2 and kvp[0]:
119 return kvp
120 msg = _("'%s' is not of the form <key>=[value]") % data
121 raise n_exc.InvalidInput(error_message=msg)
122
123
124 def convert_kvp_list_to_dict(kvp_list):
125 """Convert a list of 'key=value' strings to a dict.
126
127 :param kvp_list: A list of key value pair strings. For more info on the
128 format see; convert_kvp_str_to_list().
129 :returns: A dict who's key value pairs are populated by parsing 'kvp_list'.
130 :raises InvalidInput: If any of the key value strings are malformed.
131 """
132 if kvp_list == ['True']:
133 # No values were provided (i.e. '--flag-name')
134 return {}
135 kvp_map = {}
136 for kvp_str in kvp_list:
137 key, value = convert_kvp_str_to_list(kvp_str)
138 kvp_map.setdefault(key, set())
139 kvp_map[key].add(value)
140 return {x: list(y) for x, y in kvp_map.items()}
141
142
143 def convert_none_to_empty_list(value):
144 """Convert value to an empty list if it's None.
145
146 :param value: The value to convert.
147 :returns: An empty list of 'value' is None, otherwise 'value'.
148 """
149 return [] if value is None else value
150
151
152 def convert_none_to_empty_dict(value):
153 """Convert the value to an empty dict if it's None.
154
155 :param value: The value to convert.
156 :returns: An empty dict if 'value' is None, otherwise 'value'.
157 """
158 return {} if value is None else value
159
160
161 def convert_none_to_empty_string(value):
162 """Convert the value to an empty string if it's None.
163
164 :param value: The value to convert.
165 :returns: An empty string if 'value' is None, otherwise 'value'.
166 """
167 return '' if value is None else value
168
169
170 def convert_to_list(data):
171 """Convert a value into a list.
172
173 :param data: The value to convert.
174 :return: A new list wrapped around 'data' whereupon the list is empty
175 if 'data' is None.
176 """
177 if data is None:
178 return []
179 elif hasattr(data, '__iter__') and not isinstance(data, str):
180 return list(data)
181 else:
182 return [data]
183
184
185 def convert_allocation_pools_to_canonical_format(value):
186 """Convert allocation pools to canonical format.
187
188 :param value: The allocation pools which need to be checked.
189 :returns: Allocation pools with addresses in canonical format.
190 :raises InvalidInput: If the value is not a list of allocation pools.
191 """
192 if value is None:
193 return []
194 try:
195 return [
196 {
197 k: convert_ip_to_canonical_format(v)
198 for k, v in pool.items()
199 }
200 for pool in value
201 ]
202 except Exception as e:
203 raise n_exc.InvalidInput(
204 error_message=_("Invalid data format for allocation pools")) from e
205
206
207 def convert_ip_to_canonical_format(value):
208 """IP Address is validated and then converted to canonical format.
209
210 :param value: The IP Address which needs to be checked.
211 :returns: - None if 'value' is None,
212 - 'value' if 'value' is IPv4 address,
213 - 'value' if 'value' is not an IP Address
214 - canonical IPv6 address if 'value' is IPv6 address.
215
216 """
217 try:
218 ip = netaddr.IPAddress(value)
219 if ip.version == constants.IP_VERSION_6:
220 return str(ip.format(dialect=netaddr.ipv6_compact))
221 except Exception: # noqa: S110
222 # netaddr may raise all kinds of exceptions (ValueError,
223 # AttributeError...) if the input is not a valid IP address. Instead of
224 # catching them one by one, just catch all exceptions at once.
225 # Obviously, it would be better if netaddr raised a particular
226 # exception specific to the library. But we don't control it.
227 pass
228 return value
229
230
231 def convert_cidr_to_canonical_format(value):
232 """CIDR is validated and converted to canonical format.
233
234 :param value: The CIDR which needs to be checked.
235 :returns: - 'value' if 'value' is CIDR with IPv4 address,
236 - CIDR with canonical IPv6 address if 'value' is IPv6 CIDR.
237 :raises: InvalidInput if 'value' is None, not a valid CIDR or
238 invalid IP Format.
239 """
240 error_message = _("%s is not in a CIDR format") % value
241 try:
242 cidr = netaddr.IPNetwork(value)
243 return str(convert_ip_to_canonical_format(
244 cidr.ip)) + "/" + str(cidr.prefixlen)
245 except netaddr.core.AddrFormatError as e:
246 raise n_exc.InvalidInput(error_message=error_message) from e
247
248
249 def convert_string_to_case_insensitive(data):
250 """Convert a string value into a lower case string.
251
252 This effectively makes the string case-insensitive.
253
254 :param data: The value to convert.
255 :return: The lower-cased string representation of the value, or None is
256 'data' is None.
257 :raises InvalidInput: If the value is not a string.
258 """
259 try:
260 return data.lower()
261 except AttributeError as e:
262 error_message = _("Input value %s must be string type") % data
263 raise n_exc.InvalidInput(error_message=error_message) from e
264
265
266 def convert_to_protocol(data):
267 """Validate that a specified IP protocol is valid.
268
269 For the authoritative list mapping protocol names to numbers, see the IANA:
270 http://www.iana.org/assignments/protocol-numbers/protocol-numbers.xhtml
271
272 :param data: The value to verify is an IP protocol.
273 :returns: If data is an int between 0 and 255 or None, return that; if
274 data is a string then return it lower-cased if it matches one of the
275 allowed protocol names.
276 :raises exceptions.InvalidInput: If data is an int < 0, an
277 int > 255, or a string that does not match one of the allowed protocol
278 names.
279 """
280
281 if data is None:
282 return
283 val = convert_string_to_case_insensitive(data)
284 if val in constants.IPTABLES_PROTOCOL_MAP:
285 return data
286
287 error_message = _("IP protocol '%s' is not supported. Only protocol "
288 "names and their integer representation (0 to "
289 "255) are supported") % data
290 try:
291 if validators.validate_range(convert_to_int(data), [0, 255]) is None:
292 return data
293 else:
294 raise n_exc.InvalidInput(error_message=error_message)
295 except n_exc.InvalidInput as e:
296 raise n_exc.InvalidInput(error_message=error_message) from e
297
298
299 def convert_to_string(data):
300 """Convert a data value into a string.
301
302 :param data: The data value to convert to a string.
303 :returns: The string value of 'data' if data is not None
304 """
305
306 if data is not None:
307 return str(data)
308
309
310 def convert_prefix_forced_case(data, prefix):
311 """If <prefix> is a prefix of data, case insensitive, then force its case
312
313 This converter forces the case of a given prefix of a string.
314
315 Example, with prefix="Foo":
316 * 'foobar' converted into 'Foobar'
317 * 'fOozar' converted into 'Foozar'
318 * 'FOObaz' converted into 'Foobaz'
319
320 :param data: The data to convert
321 :returns: if data is a string starting with <prefix> in a case insensitive
322 comparison, then the return value is data with this prefix
323 replaced by <prefix>
324 """
325 plen = len(prefix)
326 if (isinstance(data, str) and len(data) >= plen and
327 data[0:plen].lower() == prefix.lower()):
328 return prefix + data[plen:]
329 return data
330
331
332 def convert_uppercase_ip(data):
333 """Uppercase "ip" if present at start of data case-insensitive
334
335 Can be used for instance to accept both "ipv4" and "IPv4".
336
337 :param data: The data to convert
338 :returns: if data is a string starting with "ip" case insensitive, then
339 the return value is data with the first two letter uppercased
340 """
341 return convert_prefix_forced_case(data, "IP")
342
343
344 def convert_to_mac_if_none(data):
345 """Convert to a random mac address if data is None
346
347 :param data: The data value
348 :return: Random mac address if data is None, else return data.
349 """
350 if data is None:
351 return net_utils.get_random_mac(cfg.CONF.base_mac.split(':'))
352
353 return data
354
355
356 def convert_to_sanitized_mac_address(mac_address):
357 """Return a MAC address with format xx:xx:xx:xx:xx:xx
358
359 :param mac_address: (string, netaddr.EUI) The MAC address value
360 :return: A string with the MAC address formatted. If the MAC address
361 provided is invalid, the same input value is returned; the goal
362 of this method is not to validate it.
363 """
364 try:
365 if isinstance(mac_address, netaddr.EUI):
366 _mac_address = copy.deepcopy(mac_address)
367 _mac_address.dialect = netaddr.mac_unix_expanded
368 return str(_mac_address)
369 return str(netaddr.EUI(mac_address, dialect=netaddr.mac_unix_expanded))
370 except netaddr.core.AddrFormatError:
371 return mac_address
372
373
374 def convert_to_sanitized_binding_profile_allocation(allocation, port_id,
375 min_bw_rules):
376 """Return binding-profile.allocation in the new format
377
378 :param allocation: binding-profile.allocation attribute containting a
379 string with RP UUID
380 :param port_id: ID of the port that is being sanitized
381 :param min_bw_rules: A list of minimum bandwidth rules associated with the
382 port.
383 :return: A dict with allocation in {'<group_uuid>': '<rp_uuid>'} format.
384 """
385 if isinstance(allocation, dict):
386 return allocation
387
388 group_id = str(
389 pl_utils.resource_request_group_uuid(uuid.UUID(port_id), min_bw_rules))
390 return {group_id: allocation}