Test Failed
Pull Request — master (#104)
by Vinicius
05:33
created

build.utils.is_intra_switch_evc()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
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
from typing import Optional
5 1
6 1
from .exceptions import FlowsNotFound, PriorityOverflow
7
from .kytos_api_helper import get_stored_flows as _get_stored_flows
8
9 1
10
async def get_found_stored_flows(cookies: list[int] = None) -> dict[int, list[dict]]:
11 1
    """Get stored flows ensuring that flows are found."""
12 1
    cookies = cookies or []
13 1
    stored_flows = await _get_stored_flows(cookies)
14 1
    for cookie, flows in stored_flows.items():
15 1
        if not flows:
16 1
            raise FlowsNotFound(get_id_from_cookie(cookie))
17
    return stored_flows
18
19 1
20
def has_int_enabled(evc: dict) -> bool:
21 1
    """Check if evc has telemetry."""
22
    return (
23
        "metadata" in evc
24
        and "telemetry" in evc["metadata"]
25
        and isinstance(evc["metadata"]["telemetry"], dict)
26
        and "enabled" in evc["metadata"]["telemetry"]
27
        and evc["metadata"]["telemetry"]["enabled"]
28
    )
29
30 1
31
def get_evc_unis(evc: dict) -> tuple[dict, dict]:
32 1
    """Parse evc for unis."""
33 1
    uni_a_split = evc["uni_a"]["interface_id"].split(":")
34 1
    uni_z_split = evc["uni_z"]["interface_id"].split(":")
35
    return (
36
        {
37
            "interface_id": evc["uni_a"]["interface_id"],
38
            "tag": evc["uni_a"].get("tag", {}),
39
            "port_number": int(uni_a_split[-1]),
40
            "switch": ":".join(uni_a_split[:-1]),
41
        },
42
        {
43
            "interface_id": evc["uni_z"]["interface_id"],
44
            "tag": evc["uni_z"].get("tag", {}),
45
            "port_number": int(uni_z_split[-1]),
46
            "switch": ":".join(uni_z_split[:-1]),
47
        },
48
    )
49
50 1
51
def add_to_apply_actions(
52
    instructions: list[dict], new_instruction: dict, position: int
53
):
54 1
    """Create the actions list"""
55 1
    for instruction in instructions:
56 1
        if instruction["instruction_type"] == "apply_actions":
57 1
            instruction["actions"].insert(position, new_instruction)
58
    return instructions
59
60 1
61
def get_cookie(evc_id: str, cookie_prefix: int) -> int:
62
    """Return the cookie integer from evc id.
63
64
    cookie_prefix is supposed to be the reserved byte value that
65
    mef_eline or telemetry_int uses.
66 1
    """
67
    return int(evc_id, 16) + (cookie_prefix << 56)
68
69 1
70
def get_id_from_cookie(cookie: int) -> str:
71 1
    """Return the evc id given a cookie value."""
72 1
    evc_id = cookie & 0xFFFFFFFFFFFFFF
73
    return f"{evc_id:x}"
74
75 1
76
def is_intra_switch_evc(evc):
77 1
    """Returns if EVC is intra-switch (two UNIs on the same switch)"""
78 1
    uni_a, uni_z = get_evc_unis(evc)
79 1
    if uni_a["switch"] == uni_z["switch"]:
80 1
        return True
81
    return False
82
83 1
84
def modify_actions(actions: list[dict], actions_to_change: list[str], remove=True):
85
    """Change the current actions
86
    If remove == True, remove actions_to_change from actions.
87
    If remove == False, keep actions_to_change, remove everything else
88
    Args:
89
        actions = current list of actions on a flow
90
        actions_to_change = list of actions as strings
91
        remove = boolean
92
    Return
93
        actions
94 1
    """
95 1
    del_indexes = set()
96 1
    for index, action in enumerate(actions):
97 1
        if remove:
98 1
            if action["action_type"] in actions_to_change:
99
                del_indexes.add(index)
100 1
        else:
101 1
            if action["action_type"] not in actions_to_change:
102 1
                del_indexes.add(index)
103
    return [action for i, action in enumerate(actions) if i not in del_indexes]
104
105 1
106
def set_priority(flow: dict, evc_id: str = "") -> dict:
107 1
    """Find a suitable priority number. EP031 describes 100 as the addition."""
108 1
    if flow["flow"]["priority"] + 100 < (2**16 - 2):
109 1
        flow["flow"]["priority"] += 100
110 1
    elif flow["flow"]["priority"] + 1 < (2**16 - 2):
111
        flow["flow"]["priority"] += 1
112 1
    else:
113 1
        raise PriorityOverflow(evc_id, f"Flow {flow} would overflow max priority")
114
    return flow
115
116 1
117
def set_owner(flow: dict) -> dict:
118 1
    """Set flow owner."""
119 1
    flow["flow"]["owner"] = "telemetry_int"
120
    return flow
121
122 1
123
def get_new_cookie(cookie: int, cookie_prefix=settings.INT_COOKIE_PREFIX) -> int:
124 1
    """Convert from mef-eline cookie by replacing the most significant byte."""
125
    return (cookie & 0xFFFFFFFFFFFFFF) + (cookie_prefix << 56)
126
127 1
128
def set_new_cookie(flow: dict) -> dict:
129 1
    """Set new cookie."""
130
    flow["flow"]["cookie"] = get_new_cookie(
131
        flow["flow"]["cookie"], cookie_prefix=settings.INT_COOKIE_PREFIX
132 1
    )
133
    return flow
134
135 1
136
def set_instructions_from_actions(flow: dict) -> dict:
137 1
    """Get intructions or convert from actions."""
138 1
    if "instructions" in flow["flow"]:
139
        return flow
140 1
141
    instructions = [
142
        {
143
            "instruction_type": "apply_actions",
144
            "actions": flow["flow"].get("actions", []),
145
        }
146 1
    ]
147 1
    flow["flow"].pop("actions", None)
148 1
    flow["flow"]["instructions"] = instructions
149
    return flow
150
151
152
def get_svlan_dpid_link(link: dict, dpid: str) -> Optional[int]:
153
    """Try to get svlan of a link if a dpid matches one of the endpoints."""
154
    if any(
155
        (
156
            link["endpoint_a"]["switch"] == dpid and "s_vlan" in link["metadata"],
157
            link["endpoint_b"]["switch"] == dpid and "s_vlan" in link["metadata"],
158
        )
159
    ):
160
        return link["metadata"]["s_vlan"]["value"]
161
    return None
162