Passed
Pull Request — master (#59)
by Italo Valcy
03:08
created

build.utils   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 151
Duplicated Lines 0 %

Test Coverage

Coverage 94.9%

Importance

Changes 0
Metric Value
eloc 109
dl 0
loc 151
rs 8.4
c 0
b 0
f 0
ccs 93
cts 98
cp 0.949
wmc 50

9 Functions

Rating   Name   Duplication   Size   Complexity  
A find_endpoint() 0 10 3
A convert_entries() 0 14 4
A convert_list_entries() 0 7 1
A get_stored_flows() 0 14 5
F _compare_endpoints() 0 20 15
D clean_circuits() 0 36 13
A prepare_list_json() 0 8 3
A prepare_json() 0 3 1
A format_result() 0 14 5

How to fix   Complexity   

Complexity

Complex classes like build.utils often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""Utility functions to be used in this Napp"""
2
3 1
import requests
4 1
from kytos.core import KytosEvent
5 1
from napps.amlight.sdntrace_cp import settings
6
7
8 1
def get_stored_flows(dpids: list = None, state: str = "installed"):
9
    """Get stored flows from flow_manager napps."""
10 1
    api_url = f'{settings.FLOW_MANAGER_URL}/stored_flows'
11 1
    if dpids:
12
        str_dpids = ''
13
        for dpid in dpids:
14
            str_dpids += f'&dpid={dpid}'
15
        api_url += '/?'+str_dpids[1:]
16 1
    if state:
17 1
        char = '&' if dpids else '/?'
18 1
        api_url += char+f'state={state}'
19 1
    result = requests.get(api_url)
20 1
    flows_from_manager = result.json()
21 1
    return flows_from_manager
22
23
24 1
def convert_entries(entries):
25
    """ Transform entries dictionary in a plain dictionary suitable for
26
        matching
27
28
    :param entries: dict
29
    :return: plain dict
30
    """
31 1
    new_entries = {}
32 1
    for entry in entries['trace'].values():
33 1
        for field, value in entry.items():
34 1
            new_entries[field] = value
35 1
    if 'dl_vlan' in new_entries:
36 1
        new_entries['dl_vlan'] = [new_entries['dl_vlan']]
37 1
    return new_entries
38
39
40 1
def convert_list_entries(entries):
41
    """ Transform a list of entries dictionary in a list
42
    of plain dictionary suitable for matching
43
    :param entries: list(dict)
44
    :return: list(plain dict)
45
    """
46 1
    return [convert_entries(entry) for entry in entries]
47
48
49 1
def find_endpoint(switch, port):
50
    """ Find where switch/port is connected. If it is another switch,
51
    returns the interface it is connected to, otherwise returns None """
52
53 1
    interface = switch.get_interface_by_port_no(port)
54 1
    if interface.link:
55 1
        if interface == interface.link.endpoint_a:
56 1
            return interface.link.endpoint_b
57 1
        return interface.link.endpoint_a
58 1
    return None
59
60
61 1
def prepare_list_json(trace_result):
62
    """Prepare return list of json for REST call."""
63 1
    result = []
64 1
    for trace_step in trace_result:
65 1
        result.append(trace_step['in'])
66 1
    if result:
67 1
        result[-1]["out"] = trace_result[-1].get("out")
68 1
    return result
69
70
71 1
def prepare_json(trace_result):
72
    """Prepare return json for REST call."""
73 1
    return {'result': prepare_list_json(trace_result)}
74
75
76 1
def format_result(trace):
77
    """Format the result for automate circuit finding"""
78 1
    result = []
79 1
    for step in trace:
80 1
        new_result = {'dpid': step['in']['dpid'],
81
                      'in_port': step['in']['port']}
82 1
        if 'out' in step:
83 1
            new_result.update({'out_port': step['out']['port']})
84 1
            if 'vlan' in step['out']:
85 1
                new_result.update({'out_vlan': step['out']['vlan']})
86 1
        if 'vlan' in step['in']:
87 1
            new_result.update({'in_vlan': step['in']['vlan']})
88 1
        result.append(new_result)
89 1
    return result
90
91
92 1
def clean_circuits(circuits, controller):
93
    """Remove sub-circuits."""
94 1
    cleaned_circuits = []
95 1
    event = KytosEvent(name='amlight/kytos_courier.slack_send')
96 1
    content = {
97
        'channel': settings.SLACK_CHANNEL,
98
        'source': 'amlight/sdntrace_cp'
99
    }
100 1
    for circuit in circuits:
101 1
        sub = False
102 1
        for other in circuits:
103 1
            if circuit['circuit'] == other['circuit']:
104 1
                continue
105 1
            sub = True
106 1
            for step in circuit['circuit']:
107 1
                if step not in other['circuit']:
108 1
                    sub = False
109 1
                    break
110 1
            if sub:
111 1
                break
112 1
        if not sub:
113 1
            cleaned_circuits.append(circuit)
114
115 1
    for circuit in cleaned_circuits:
116 1
        has_return = False
117 1
        for other in cleaned_circuits:
118 1
            if _compare_endpoints(circuit['circuit'][0],
119
                                  other['circuit'][-1]) \
120
                    and _compare_endpoints(circuit['circuit'][-1],
121
                                           other['circuit'][0]):
122
                has_return = True
123 1
        if not has_return:
124 1
            content['m_body'] = f"Circuit {circuit['circuit']} has no way back"
125 1
            event.content['message'] = content
126 1
            controller.buffers.app.put(event)
127 1
    return cleaned_circuits
128
129
130
# pylint: disable=too-many-return-statements
131 1
def _compare_endpoints(endpoint1, endpoint2):
132 1
    if endpoint1['dpid'] != endpoint2['dpid']:
133 1
        return False
134 1
    if (
135
        'in_port' not in endpoint1
136
        or 'out_port' not in endpoint2
137
        or endpoint1['in_port'] != endpoint2['out_port']
138
    ):
139 1
        return False
140 1
    if 'in_vlan' in endpoint1 and 'out_vlan' in endpoint2:
141 1
        if endpoint1['in_vlan'] != endpoint2['out_vlan']:
142 1
            return False
143 1
    elif 'in_vlan' in endpoint1 or 'out_vlan' in endpoint2:
144 1
        return False
145 1
    if 'out_vlan' in endpoint1 and 'in_vlan' in endpoint2:
146 1
        if endpoint1['out_vlan'] != endpoint2['in_vlan']:
147 1
            return False
148 1
    elif 'out_vlan' in endpoint1 or 'in_vlan' in endpoint2:
149 1
        return False
150
    return True
151