Passed
Pull Request — master (#36)
by
unknown
04:19 queued 21s
created

build.main   A

Complexity

Total Complexity 21

Size/Duplication

Total Lines 145
Duplicated Lines 0 %

Test Coverage

Coverage 93.51%

Importance

Changes 0
Metric Value
eloc 90
dl 0
loc 145
rs 10
c 0
b 0
f 0
ccs 72
cts 77
cp 0.9351
wmc 21

8 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.trace_step() 0 18 4
A Main.update_circuits() 0 6 2
A Main.shutdown() 0 8 1
A Main.setup() 0 15 1
A Main.has_loop() 0 8 4
A Main.execute() 0 2 1
B Main.tracepath() 0 44 7
A Main.trace() 0 6 1
1
"""Main module of amlight/sdntrace_cp Kytos Network Application.
2
3
Run tracepaths on OpenFlow in the Control Plane
4
"""
5
6 1
from datetime import datetime
7
8 1
from flask import jsonify, request
9 1
from kytos.core import KytosNApp, log, rest
10 1
from kytos.core.helpers import listen_to
11 1
from napps.amlight.flow_stats.main import Main as FlowManager
12 1
from napps.amlight.sdntrace_cp import settings
13 1
from napps.amlight.sdntrace_cp.automate import Automate
14 1
from napps.amlight.sdntrace_cp.utils import (convert_entries, find_endpoint,
15
                                             prepare_json)
16
17
18 1
class Main(KytosNApp):
19
    """Main class of amlight/sdntrace_cp NApp.
20
21
    This application gets the list of flows from the switches
22
    and uses it to trace paths without using the data plane.
23
    """
24
25 1
    def setup(self):
26
        """Replace the '__init__' method for the KytosNApp subclass.
27
28
        The setup method is automatically called by the controller when your
29
        application is loaded.
30
31
        """
32 1
        log.info("Starting Kytos SDNTrace CP App!")
33
34 1
        self.traces = {}
35 1
        self.last_id = 30000
36 1
        self.automate = Automate(self)
37 1
        self.automate.schedule_traces(self.automate.run_traces)
38 1
        important_traces = self.automate.run_important_traces
39 1
        self.automate.schedule_important_traces(important_traces)
40
41 1
    def execute(self):
42
        """This method is executed right after the setup method execution.
43
44
        You can also use this method in loop mode if you add to the above setup
45
        method a line like the following example:
46
47
            self.execute_as_loop(30)  # 30-second interval.
48
        """
49
50 1
    def shutdown(self):
51
        """This method is executed when your napp is unloaded.
52
53
        If you have some cleanup procedure, insert it here.
54
        """
55
        id_set = {'automatic_traces', 'automatic_important_traces'}
56
        self.automate.unschedule_id(id_set)
57
        self.automate.sheduler_shutdown(wait=False)
58
59 1
    @rest('/trace', methods=['PUT'])
60 1
    def trace(self):
61
        """Trace a path."""
62 1
        entries = request.get_json()
63 1
        result = self.tracepath(entries)
64 1
        return jsonify(prepare_json(result))
65
66 1
    def tracepath(self, entries):
67
        """Trace a path for a packet represented by entries."""
68 1
        self.last_id += 1
69 1
        trace_id = self.last_id
70 1
        entries = convert_entries(entries)
71 1
        trace_result = []
72 1
        trace_type = 'starting'
73
74 1
        do_trace = True
75 1
        while do_trace:
76 1
            trace_step = {'in': {'dpid': entries['dpid'],
77
                                 'port': entries['in_port'],
78
                                 'time': str(datetime.now()),
79
                                 'type': trace_type}}
80 1
            if 'vlan_vid' in entries:
81 1
                trace_step['in'].update({'vlan': entries['vlan_vid'][-1]})
82 1
            switch = self.controller.get_switch_by_dpid(entries['dpid'])
83 1
            result = self.trace_step(switch, entries)
84 1
            if result:
85 1
                out = {'port': result['out_port']}
86 1
                if 'vlan_vid' in result['entries']:
87
                    out.update({'vlan': result['entries']['vlan_vid'][-1]})
88 1
                trace_step.update({
89
                    'out': out
90
                })
91 1
                if 'dpid' in result:
92 1
                    next_step = {'dpid': result['dpid'],
93
                                 'port': result['in_port']}
94 1
                    if self.has_loop(next_step, trace_result):
95 1
                        do_trace = False
96
                    else:
97 1
                        entries = result['entries']
98 1
                        entries['dpid'] = result['dpid']
99 1
                        entries['in_port'] = result['in_port']
100 1
                        trace_type = 'trace'
101
                else:
102
                    do_trace = False
103
            else:
104 1
                do_trace = False
105 1
            trace_result.append(trace_step)
106 1
        self.traces.update({
107
            trace_id: trace_result
108
        })
109 1
        return trace_result
110
111 1
    @staticmethod
112 1
    def has_loop(trace_step, trace_result):
113
        """Check if there is a loop in the trace result."""
114 1
        for trace in trace_result:
115 1
            if trace['in']['dpid'] == trace_step['dpid'] and \
116
                            trace['in']['port'] == trace_step['port']:
117 1
                return True
118 1
        return False
119
120 1
    @staticmethod
121 1
    def trace_step(switch, entries):
122
        """Perform a trace step.
123
124
        Match the given fields against the switch's list of flows."""
125 1
        flow, entries, port = FlowManager.match_and_apply(switch, entries)
126 1
        if not flow or not port:
127 1
            return None
128
129 1
        endpoint = find_endpoint(switch, port)
130 1
        if endpoint is None:
131 1
            return {'out_port': port,
132
                    'entries': entries}
133
134 1
        return {'dpid': endpoint.switch.dpid,
135
                'in_port': endpoint.port_number,
136
                'out_port': port,
137
                'entries': entries}
138
139 1
    @listen_to('amlight/flow_stats.flows_updated')
140 1
    def update_circuits(self, event):
141
        """Update the list of circuits after a flow change."""
142
        # pylint: disable=unused-argument
143 1
        if settings.FIND_CIRCUITS_IN_FLOWS:
144
            self.automate.find_circuits()
145