| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2024, Sabari Jaganathan (@sajagana) <[email protected]> |
| 4 |
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
|
| 6 |
from __future__ import absolute_import, division, print_function |
| 7 |
|
| 8 |
__metaclass__ = type |
| 9 |
import copy |
| 10 |
|
| 11 |
|
| 12 |
def generate_api_endpoint(path, **kwargs): |
| 13 |
""" |
| 14 |
Generates an API endpoint with query strings based on the provided keyword arguments. |
| 15 |
|
| 16 |
:param path: The base URL of the API endpoint. -> Str |
| 17 |
:param kwargs: Keyword arguments representing query parameters. -> Dict |
| 18 |
:return: A string representing the full API endpoint with query parameters. -> Str |
| 19 |
""" |
| 20 |
return path if not kwargs else "{0}?{1}".format(path, "&".join(["{0}={1}".format(key, value) for key, value in kwargs.items()])) |
| 21 |
|
| 22 |
|
| 23 |
def append_update_ops_data(ops, existing_data, update_path, replace_data=None, remove_data=None): |
| 24 |
""" |
| 25 |
Append Update ops payload data. |
| 26 |
:param ops: Variable which contains the PATCH replace actions for the update operation -> List |
| 27 |
:param existing_data: Variable which contains the existing data -> Dict |
| 28 |
:param update_path: The object path is used to update an existing object -> Str |
| 29 |
:param replace_data: Defaults to None when not specified, expected a dictionary object. Which contains the attribute to be updated and its new value -> Dict |
| 30 |
:param remove_data: Defaults to None when not specified, expected a list of string or tuple, value used to clear the existing configuration -> List |
| 31 |
:return: None |
| 32 |
If attributes is not empty then the ops and existing_data are updated with the input value. |
| 33 |
|
| 34 |
Sample Existing Data: |
| 35 |
--------------------- |
| 36 |
existing_data = { |
| 37 |
"name": "name", |
| 38 |
"description": "description", |
| 39 |
"bfdMultiHopPol": { |
| 40 |
"adminState": "enabled", |
| 41 |
"minRxInterval": 250, |
| 42 |
"ifControl": {"adminState": "enabled"}, |
| 43 |
}, |
| 44 |
"bfdPol": { |
| 45 |
"adminState": "enabled", |
| 46 |
"detectionMultiplier": 3, |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
ops = [] |
| 51 |
update_path = "/tenantPolicyTemplate/template/l3OutIntfPolGroups/0" |
| 52 |
replace_data = { |
| 53 |
("name"): "new_name", |
| 54 |
"description": "new_description", |
| 55 |
("ospfIntfPol"): dict(ifControl=dict(adminState="disabled"), cost=0), |
| 56 |
} |
| 57 |
remove_data = [("bfdMultiHopPol", "ifControl", "adminState"), "bfdPol"] |
| 58 |
|
| 59 |
append_update_ops_data(ops, existing_data, update_path, replace_data, remove_data) |
| 60 |
|
| 61 |
Standard Output Data: |
| 62 |
--------------------- |
| 63 |
{ |
| 64 |
"bfdMultiHopPol": { |
| 65 |
"adminState": "enabled", |
| 66 |
"minRxInterval": 250, |
| 67 |
"ifControl": {}, |
| 68 |
}, |
| 69 |
"name": "new_name", |
| 70 |
"description": "new_description", |
| 71 |
"ospfIntfPol": { |
| 72 |
"ifControl": { |
| 73 |
"adminState": "disabled", |
| 74 |
}, |
| 75 |
"cost": 0, |
| 76 |
}, |
| 77 |
} |
| 78 |
|
| 79 |
API Input Data: |
| 80 |
--------------- |
| 81 |
[ |
| 82 |
{"op": "replace", "path": "/tenantPolicyTemplate/template/l3OutIntfPolGroups/1/name", "value": "new_name"}, |
| 83 |
{"op": "replace", "path": "/tenantPolicyTemplate/template/l3OutIntfPolGroups/1/description", "value": "new_description"}, |
| 84 |
{ |
| 85 |
"op": "replace", |
| 86 |
"path": "/tenantPolicyTemplate/template/l3OutIntfPolGroups/1/ospfIntfPol", |
| 87 |
"value": {"ifControl": {"adminState": "disabled"}, "cost": 0}, |
| 88 |
}, |
| 89 |
{"op": "remove", "path": "/tenantPolicyTemplate/template/l3OutIntfPolGroups/1/bfdPol"}, |
| 90 |
{"op": "remove", "path": "/tenantPolicyTemplate/template/l3OutIntfPolGroups/1/bfdMultiHopPol/ifControl/adminState"}, |
| 91 |
] |
| 92 |
""" |
| 93 |
|
| 94 |
def recursive_add_replace(data, path, keys, new_value): |
| 95 |
key = keys[0] |
| 96 |
if len(keys) == 1: |
| 97 |
# Update the existing configuration |
| 98 |
if new_value is not None and data.get(key) != new_value: |
| 99 |
operation = "replace" if data.get(key) is not None else "add" |
| 100 |
data[key] = new_value |
| 101 |
ops.append( |
| 102 |
dict( |
| 103 |
op=operation, |
| 104 |
path="{}/{}".format(path, key), |
| 105 |
value=copy.deepcopy(new_value), |
| 106 |
) |
| 107 |
) |
| 108 |
elif key in data: |
| 109 |
recursive_add_replace(data[key], "{}/{}".format(path, key), keys[1:], new_value) |
| 110 |
|
| 111 |
def recursive_delete(data, path, keys): |
| 112 |
key = keys[0] |
| 113 |
if len(keys) == 1: |
| 114 |
# Clear the existing configuration |
| 115 |
if key in data: |
| 116 |
data.pop(key) |
| 117 |
ops.append( |
| 118 |
dict( |
| 119 |
op="remove", |
| 120 |
path="{}/{}".format(path, key), |
| 121 |
) |
| 122 |
) |
| 123 |
elif key in data: |
| 124 |
recursive_delete(data[key], "{}/{}".format(path, key), keys[1:]) |
| 125 |
|
| 126 |
if replace_data: |
| 127 |
if not isinstance(replace_data, dict): |
| 128 |
raise TypeError("replace_data must be a dict") |
| 129 |
|
| 130 |
for key, value in replace_data.items(): |
| 131 |
recursive_add_replace(existing_data, update_path, key if isinstance(key, tuple) else (key,), value) |
| 132 |
|
| 133 |
if remove_data: |
| 134 |
if not isinstance(remove_data, list): |
| 135 |
raise TypeError("remove_data must be a list of string or tuples") |
| 136 |
|
| 137 |
for key in remove_data: |
| 138 |
recursive_delete(existing_data, update_path, key if isinstance(key, tuple) else (key,)) |
| 139 |
|
| 140 |
|
| 141 |
def check_if_all_elements_are_none(values): |
| 142 |
""" |
| 143 |
Checks if all elements in the provided iterable are None |
| 144 |
|
| 145 |
:param values: An iterable containing values to be checked -> Iterable[Any] |
| 146 |
:return: True if all elements are None, False otherwise -> Bool |
| 147 |
""" |
| 148 |
return all(value is None for value in values) |
| 149 |
|
| 150 |
|
| 151 |
def snake_to_camel(snake_str, upper_case_components=None): |
| 152 |
if snake_str is not None and "_" in snake_str: |
| 153 |
if upper_case_components is None: |
| 154 |
upper_case_components = [] |
| 155 |
components = snake_str.split("_") |
| 156 |
camel_case_str = components[0] |
| 157 |
|
| 158 |
for component in components[1:]: |
| 159 |
if component in upper_case_components: |
| 160 |
camel_case_str += component.upper() |
| 161 |
else: |
| 162 |
camel_case_str += component.title() |
| 163 |
|
| 164 |
return camel_case_str |
| 165 |
else: |
| 166 |
return snake_str |
| 167 |
|
| 168 |
|
| 169 |
def delete_none_values(obj_to_sanitize, recursive=True): |
| 170 |
""" |
| 171 |
Removes keys with None values from a Python object, which can be either a list or a dictionary. |
| 172 |
Optionally performs the operation recursively on nested structures. |
| 173 |
|
| 174 |
:param obj_to_sanitize: The Python object to sanitize from None values. -> List or Dict |
| 175 |
:param recursive: A boolean flag indicating whether to recursively sanitize nested objects. Defaults to True. -> bool |
| 176 |
:return: A sanitized copy of the original Python object, with all keys with None values removed. -> List or Dict |
| 177 |
""" |
| 178 |
if isinstance(obj_to_sanitize, dict): |
| 179 |
sanitized_dict = {} |
| 180 |
for item_key, item_value in obj_to_sanitize.items(): |
| 181 |
if recursive and isinstance(item_value, (dict, list)): |
| 182 |
sanitized_dict[item_key] = delete_none_values(item_value, recursive) |
| 183 |
elif item_value is not None: |
| 184 |
sanitized_dict[item_key] = item_value |
| 185 |
return sanitized_dict |
| 186 |
|
| 187 |
elif isinstance(obj_to_sanitize, list): |
| 188 |
sanitized_list = [] |
| 189 |
for item in obj_to_sanitize: |
| 190 |
if recursive and isinstance(item, (dict, list)): |
| 191 |
sanitized_list.append(delete_none_values(item, recursive)) |
| 192 |
elif item is not None: |
| 193 |
sanitized_list.append(item) |
| 194 |
return sanitized_list |
| 195 |
|
| 196 |
else: |
| 197 |
raise TypeError("Object to sanitize must be of type list or dict. Got {}".format(type(obj_to_sanitize))) |
| 198 |
|
| 199 |
|
| 200 |
def format_annotations_list(mso_values, annotations): |
| 201 |
""" |
| 202 |
Format the list of annotations for the payload to be sent |
| 203 |
:param mso_values: The payload to be sent -> Dict |
| 204 |
:param annotations: The initial list of annotations -> Dict |
| 205 |
:return: Assign the formated list of annotations to the payload under key 'tagAnnotations' -> None |
| 206 |
""" |
| 207 |
if annotations: |
| 208 |
mso_values["tagAnnotations"] = [ |
| 209 |
{ |
| 210 |
"tagKey": annotation.get("key"), |
| 211 |
"tagValue": annotation.get("value"), |
| 212 |
} |
| 213 |
for annotation in annotations |
| 214 |
] |