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

build.utils.set_table_group()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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