| 1 |
# Licensed under the Apache License, Version 2.0 (the "License"); |
| 2 |
# you may not use this file except in compliance with the License. |
| 3 |
# You may obtain 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, |
| 9 |
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or |
| 10 |
# implied. |
| 11 |
# See the License for the specific language governing permissions and |
| 12 |
# limitations under the License. |
| 13 |
|
| 14 |
from collections import abc |
| 15 |
import decimal |
| 16 |
import random |
| 17 |
import weakref |
| 18 |
|
| 19 |
from oslo_log import log as logging |
| 20 |
from oslo_utils import timeutils |
| 21 |
from oslo_utils import uuidutils |
| 22 |
|
| 23 |
from neutron_lib._i18n import _ |
| 24 |
|
| 25 |
|
| 26 |
LOG = logging.getLogger(__name__) |
| 27 |
|
| 28 |
|
| 29 |
def parse_mappings(mapping_list, unique_values=True, unique_keys=True): |
| 30 |
"""Parse a list of mapping strings into a dictionary. |
| 31 |
|
| 32 |
:param mapping_list: A list of strings of the form '<key>:<value>'. |
| 33 |
:param unique_values: Values must be unique if True. |
| 34 |
:param unique_keys: Keys must be unique if True, else implies that keys |
| 35 |
and values are not unique. |
| 36 |
:returns: A dict mapping keys to values or to list of values. |
| 37 |
:raises ValueError: Upon malformed data or duplicate keys. |
| 38 |
""" |
| 39 |
mappings = {} |
| 40 |
for mapping in mapping_list: |
| 41 |
mapping = mapping.strip() |
| 42 |
if not mapping: |
| 43 |
continue |
| 44 |
split_result = mapping.split(':') |
| 45 |
if len(split_result) != 2: |
| 46 |
raise ValueError(_("Invalid mapping: '%s'") % mapping) |
| 47 |
key = split_result[0].strip() |
| 48 |
if not key: |
| 49 |
raise ValueError(_("Missing key in mapping: '%s'") % mapping) |
| 50 |
value = split_result[1].strip() |
| 51 |
if not value: |
| 52 |
raise ValueError(_("Missing value in mapping: '%s'") % mapping) |
| 53 |
if unique_keys: |
| 54 |
if key in mappings: |
| 55 |
raise ValueError(_("Key %(key)s in mapping: '%(mapping)s' not " |
| 56 |
"unique") % {'key': key, |
| 57 |
'mapping': mapping}) |
| 58 |
if unique_values and value in mappings.values(): |
| 59 |
raise ValueError(_("Value %(value)s in mapping: '%(mapping)s' " |
| 60 |
"not unique") % {'value': value, |
| 61 |
'mapping': mapping}) |
| 62 |
mappings[key] = value |
| 63 |
else: |
| 64 |
mappings.setdefault(key, []) |
| 65 |
if value not in mappings[key]: |
| 66 |
mappings[key].append(value) |
| 67 |
return mappings |
| 68 |
|
| 69 |
|
| 70 |
def compare_elements(a, b): |
| 71 |
"""Compare elements if a and b have same elements. |
| 72 |
|
| 73 |
This method doesn't consider ordering. |
| 74 |
|
| 75 |
:param a: The first item to compare. |
| 76 |
:param b: The second item to compare. |
| 77 |
:returns: True if a and b have the same elements, False otherwise. |
| 78 |
""" |
| 79 |
return set(a or []) == set(b or []) |
| 80 |
|
| 81 |
|
| 82 |
def safe_sort_key(value): |
| 83 |
"""Return value hash or build one for dictionaries. |
| 84 |
|
| 85 |
:param value: The value to build a hash for. |
| 86 |
:returns: The value sorted. |
| 87 |
""" |
| 88 |
if isinstance(value, abc.Mapping): |
| 89 |
return sorted(value.items()) |
| 90 |
return value |
| 91 |
|
| 92 |
|
| 93 |
def dict2str(dic): |
| 94 |
"""Build a str representation of a dict. |
| 95 |
|
| 96 |
:param dic: The dict to build a str representation for. |
| 97 |
:returns: The dict in str representation that is a k=v command list for |
| 98 |
each item in dic. |
| 99 |
""" |
| 100 |
return ','.join(f"{key}={val}" |
| 101 |
for key, val in sorted(dic.items())) |
| 102 |
|
| 103 |
|
| 104 |
def str2dict(string): |
| 105 |
"""Parse a str representation of a dict into its dict form. |
| 106 |
|
| 107 |
This is the inverse of dict2str() |
| 108 |
|
| 109 |
:param string: The string to parse. |
| 110 |
:returns: A dict constructed from the str representation in string. |
| 111 |
""" |
| 112 |
res_dict = {} |
| 113 |
for keyvalue in string.split(','): |
| 114 |
(key, value) = keyvalue.split('=', 1) |
| 115 |
res_dict[key] = value |
| 116 |
return res_dict |
| 117 |
|
| 118 |
|
| 119 |
def dict2tuple(d): |
| 120 |
"""Build a tuple from a dict. |
| 121 |
|
| 122 |
:param d: The dict to coherence into a tuple. |
| 123 |
:returns: The dict d in tuple form. |
| 124 |
""" |
| 125 |
items = list(d.items()) |
| 126 |
items.sort() |
| 127 |
return tuple(items) |
| 128 |
|
| 129 |
|
| 130 |
def diff_list_of_dict(old_list, new_list): |
| 131 |
"""Given 2 lists of dicts, return a tuple containing the diff. |
| 132 |
|
| 133 |
:param old_list: The old list of dicts to diff. |
| 134 |
:param new_list: The new list of dicts to diff. |
| 135 |
:returns: A tuple where the first item is a list of the added dicts in |
| 136 |
the diff and the second item is the removed dicts. |
| 137 |
""" |
| 138 |
new_set = {dict2str(i) for i in new_list} |
| 139 |
old_set = {dict2str(i) for i in old_list} |
| 140 |
added = new_set - old_set |
| 141 |
removed = old_set - new_set |
| 142 |
return [str2dict(a) for a in added], [str2dict(r) for r in removed] |
| 143 |
|
| 144 |
|
| 145 |
def get_random_string(length): |
| 146 |
"""Get a random hex string of the specified length. |
| 147 |
|
| 148 |
:param length: The length for the hex string. |
| 149 |
:returns: A random hex string of the said length. |
| 150 |
""" |
| 151 |
return "{0:0{1}x}".format(random.getrandbits(length * 4), length) |
| 152 |
|
| 153 |
|
| 154 |
def camelize(s): |
| 155 |
"""Camelize a str that uses _ as a camelize token. |
| 156 |
|
| 157 |
:param s: The str to camelize that contains a _ at each index where a new |
| 158 |
camelized word starts. |
| 159 |
:returns: The camelized str. |
| 160 |
""" |
| 161 |
return ''.join(s.replace('_', ' ').title().split()) |
| 162 |
|
| 163 |
|
| 164 |
def round_val(val): |
| 165 |
"""Round the value. |
| 166 |
|
| 167 |
:param val: The value to round. |
| 168 |
:returns: The value rounded using the half round up scheme. |
| 169 |
""" |
| 170 |
# we rely on decimal module since it behaves consistently across Python |
| 171 |
# versions (2.x vs. 3.x) |
| 172 |
return int(decimal.Decimal(val).quantize(decimal.Decimal('1'), |
| 173 |
rounding=decimal.ROUND_HALF_UP)) |
| 174 |
|
| 175 |
|
| 176 |
def safe_decode_utf8(s): |
| 177 |
"""Safe decode a str from UTF. |
| 178 |
|
| 179 |
:param s: The str to decode. |
| 180 |
:returns: The decoded str. |
| 181 |
""" |
| 182 |
if isinstance(s, bytes): |
| 183 |
return s.decode('utf-8', 'surrogateescape') |
| 184 |
return s |
| 185 |
|
| 186 |
|
| 187 |
weak_method = weakref.WeakMethod |
| 188 |
|
| 189 |
|
| 190 |
def make_weak_ref(f): |
| 191 |
"""Make a weak reference to a function accounting for bound methods. |
| 192 |
|
| 193 |
:param f: The callable to make a weak ref for. |
| 194 |
:returns: A weak ref to f. |
| 195 |
""" |
| 196 |
return weak_method(f) if hasattr(f, '__self__') else weakref.ref(f) |
| 197 |
|
| 198 |
|
| 199 |
def resolve_ref(ref): |
| 200 |
"""Handles dereference of weakref. |
| 201 |
|
| 202 |
:param ref: The weak ref to resolve. |
| 203 |
:returns: The resolved reference. |
| 204 |
""" |
| 205 |
if isinstance(ref, weakref.ref): |
| 206 |
ref = ref() |
| 207 |
return ref |
| 208 |
|
| 209 |
|
| 210 |
def timecost(f): |
| 211 |
call_id = uuidutils.generate_uuid() |
| 212 |
message_base = (f"Time-cost: call {call_id} function {f.__name__} ") |
| 213 |
end_message = (message_base + "took %(seconds).3fs seconds to run") |
| 214 |
|
| 215 |
@timeutils.time_it(LOG, message=end_message, min_duration=None) |
| 216 |
def wrapper(*args, **kwargs): |
| 217 |
LOG.debug(message_base + "start") |
| 218 |
ret = f(*args, **kwargs) |
| 219 |
return ret |
| 220 |
return wrapper |