Passed
Pull Request — master (#35)
by Vinicius
02:26
created

build.utils.modify_actions()   A

Complexity

Conditions 5

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 9
nop 3
dl 0
loc 20
ccs 9
cts 9
cp 1
crap 5
rs 9.3333
c 0
b 0
f 0
1
""" Support function for main.py """
2
3 1
from napps.kytos.telemetry_int import settings
4
5 1
from kytos.core import Controller
6
7 1
from .exceptions import FlowsNotFound, PriorityOverflow, ProxyPortNotFound
8 1
from .kytos_api_helper import get_evcs
9 1
from .kytos_api_helper import get_stored_flows as _get_stored_flows
10 1
from .proxy_port import ProxyPort
11
12
13 1
async def get_found_stored_flows(cookies: list[int] = None) -> dict[int, list[dict]]:
14
    """Get stored flows ensuring that flows are found."""
15
    cookies = cookies or []
16
    stored_flows = await _get_stored_flows()
17
    for cookie, flows in stored_flows.items():
18
        if not flows:
19
            raise FlowsNotFound(get_id_from_cookie(cookie))
20
    return stored_flows
21
22
23 1
def get_evc_with_telemetry() -> dict:
24
    """Retrieve the list of EVC IDs and list those with
25
    metadata {"telemetry": {"enabled": true}}"""
26
27
    evc_ids = {"evcs_with_telemetry": []}
28
    for evc in get_evcs().values():
29
        if has_int_enabled(evc):
30
            evc_ids["evcs_with_telemetry"].append(evc["id"])
31
    return evc_ids
32
33
34 1
def has_int_enabled(evc: dict) -> bool:
35
    """Check if evc has telemetry."""
36 1
    return (
37
        "telemetry" in evc["metadata"]
38
        and isinstance(evc["metadata"]["telemetry"], dict)
39
        and "enabled" in evc["metadata"]["telemetry"]
40
        and evc["metadata"]["telemetry"]["enabled"]
41
    )
42
43
44 1
def get_evc_unis(evc: dict) -> tuple[dict, dict]:
45
    """Parse evc for unis."""
46 1
    uni_a_split = evc["uni_a"]["interface_id"].split(":")
47 1
    uni_z_split = evc["uni_z"]["interface_id"].split(":")
48 1
    return (
49
        {
50
            "interface_id": evc["uni_a"]["interface_id"],
51
            "tag": evc["uni_a"].get("tag", {}),
52
            "port_number": int(uni_a_split[-1]),
53
            "switch": ":".join(uni_a_split[:-1]),
54
        },
55
        {
56
            "interface_id": evc["uni_z"]["interface_id"],
57
            "tag": evc["uni_z"].get("tag", {}),
58
            "port_number": int(uni_z_split[-1]),
59
            "switch": ":".join(uni_z_split[:-1]),
60
        },
61
    )
62
63
64 1
def get_proxy_port_or_raise(
65
    controller: Controller, intf_id: str, evc_id: str
66
) -> ProxyPort:
67
    """Return a ProxyPort assigned to a UNI or raise."""
68
69 1
    interface = controller.get_interface_by_id(intf_id)
70 1
    if not interface:
71 1
        raise ProxyPortNotFound(evc_id, f"UNI interface {intf_id} not found")
72
73 1
    if "proxy_port" not in interface.metadata:
74 1
        raise ProxyPortNotFound(evc_id, f"proxy_port metadata not found in {intf_id}")
75
76 1
    source_intf = interface.switch.get_interface_by_port_no(
77
        interface.metadata.get("proxy_port")
78
    )
79 1
    if not source_intf:
80
        raise ProxyPortNotFound(
81
            evc_id,
82
            f"proxy_port of {intf_id} source interface not found",
83
        )
84
85 1
    pp = ProxyPort(controller, source_intf)
86
87 1
    if not pp.destination:
88 1
        raise ProxyPortNotFound(
89
            evc_id,
90
            f"proxy_port of {intf_id} destination interface not found",
91
        )
92 1
    return pp
93
94
95 1
def add_to_apply_actions(
96
    instructions: list[dict], new_instruction: dict, position: int
97
):
98
    """Create the actions list"""
99 1
    for instruction in instructions:
100 1
        if instruction["instruction_type"] == "apply_actions":
101 1
            instruction["actions"].insert(position, new_instruction)
102 1
    return instructions
103
104
105 1
def get_cookie(evc_id: str, cookie_prefix: int) -> int:
106
    """Return the cookie integer from evc id.
107
108
    cookie_prefix is supposed to be the reserved byte value that
109
    mef_eline or telemetry_int uses.
110
    """
111
    return int(evc_id, 16) + (cookie_prefix << 56)
112
113
114 1
def get_id_from_cookie(cookie: int) -> str:
115
    """Return the evc id given a cookie value."""
116 1
    evc_id = cookie & 0xFFFFFFFFFFFFFF
117 1
    return f"{evc_id:x}"
118
119
120 1
def is_intra_switch_evc(evc):
121
    """Returns if EVC is intra-switch (two UNIs on the same switch)"""
122 1
    uni_a, uni_z = get_evc_unis(evc)
123 1
    if uni_a["switch"] == uni_z["switch"]:
124 1
        return True
125 1
    return False
126
127
128 1
def modify_actions(actions: list[dict], actions_to_change: list[str], remove=True):
129
    """Change the current actions
130
    If remove == True, remove actions_to_change from actions.
131
    If remove == False, keep actions_to_change, remove everything else
132
    Args:
133
        actions = current list of actions on a flow
134
        actions_to_change = list of actions as strings
135
        remove = boolean
136
    Return
137
        actions
138
    """
139 1
    del_indexes = set()
140 1
    for index, action in enumerate(actions):
141 1
        if remove:
142 1
            if action["action_type"] in actions_to_change:
143 1
                del_indexes.add(index)
144
        else:
145 1
            if action["action_type"] not in actions_to_change:
146 1
                del_indexes.add(index)
147 1
    return [action for i, action in enumerate(actions) if i not in del_indexes]
148
149
150 1
def set_priority(flow: dict, evc_id: str = "") -> dict:
151
    """Find a suitable priority number. EP031 describes 100 as the addition."""
152
    if flow["flow"]["priority"] + 100 < (2**16 - 2):
153
        flow["flow"]["priority"] += 100
154
    elif flow["flow"]["priority"] + 1 < (2**16 - 2):
155
        flow["flow"]["priority"] += 1
156
    else:
157
        raise PriorityOverflow(evc_id, f"Flow {flow} would overflow max priority")
158
    return flow
159
160
161 1
def set_owner(flow: dict) -> dict:
162
    """Set flow owner."""
163 1
    flow["flow"]["owner"] = "telemetry_int"
164 1
    return flow
165
166
167 1
def set_table_group(flow: dict, table_group="base") -> dict:
168
    """Set flow owner."""
169 1
    flow["flow"]["table_group"] = table_group
170 1
    return flow
171
172
173 1
def get_new_cookie(cookie: int, cookie_prefix=settings.INT_COOKIE_PREFIX) -> int:
174
    """Convert from mef-eline cookie by replacing the most significant byte."""
175 1
    return (cookie & 0xFFFFFFFFFFFFFF) + (cookie_prefix << 56)
176
177
178 1
def set_new_cookie(flow: dict) -> dict:
179
    """Set new cookie."""
180 1
    flow["flow"]["cookie"] = get_new_cookie(
181
        flow["flow"]["cookie"], cookie_prefix=settings.INT_COOKIE_PREFIX
182
    )
183 1
    return flow
184
185
186 1
def set_instructions_from_actions(flow: dict) -> dict:
187
    """Get intructions or convert from actions."""
188 1
    if "instructions" in flow["flow"]:
189 1
        return flow
190
191 1
    instructions = [
192
        {
193
            "instruction_type": "apply_actions",
194
            "actions": flow["flow"].get("actions", []),
195
        }
196
    ]
197 1
    flow["flow"].pop("actions", None)
198 1
    flow["flow"]["instructions"] = instructions
199
    return flow
200