Passed
Pull Request — master (#92)
by Jose
02:13
created

build.main.Main.handle_errors()   B

Complexity

Conditions 7

Size

Total Lines 38
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 10.3549

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 38
ccs 13
cts 22
cp 0.5909
rs 7.8799
c 0
b 0
f 0
cc 7
nop 2
crap 10.3549
1
"""kytos/flow_manager NApp installs, lists and deletes switch flows."""
2 1
from collections import OrderedDict
3
4 1
from flask import jsonify, request
5 1
from pyof.v0x01.asynchronous.error_msg import BadActionCode
6 1
from pyof.v0x01.common.phy_port import PortConfig
7
8 1
from kytos.core import KytosEvent, KytosNApp, log, rest
9 1
from kytos.core.helpers import listen_to
10 1
from napps.kytos.of_core.flow import FlowFactory
11
12 1
from .exceptions import InvalidCommandError
13 1
from .settings import FLOWS_DICT_MAX_SIZE
14
15
16 1
class Main(KytosNApp):
17
    """Main class to be used by Kytos controller."""
18
19 1
    def setup(self):
20
        """Replace the 'init' method for the KytosApp subclass.
21
22
        The setup method is automatically called by the run method.
23
        Users shouldn't call this method directly.
24
        """
25 1
        log.debug("flow-manager starting")
26 1
        self._flow_mods_sent = OrderedDict()
27 1
        self._flow_mods_sent_max_size = FLOWS_DICT_MAX_SIZE
28
29 1
    def execute(self):
30
        """Run once on NApp 'start' or in a loop.
31
32
        The execute method is called by the run method of KytosNApp class.
33
        Users shouldn't call this method directly.
34
        """
35
36 1
    def shutdown(self):
37
        """Shutdown routine of the NApp."""
38
        log.debug("flow-manager stopping")
39
40 1
    @rest('v2/flows')
41 1
    @rest('v2/flows/<dpid>')
42 1
    def list(self, dpid=None):
43
        """Retrieve all flows from a switch identified by dpid.
44
45
        If no dpid is specified, return all flows from all switches.
46
        """
47 1
        if dpid is None:
48 1
            switches = self.controller.switches.values()
49
        else:
50 1
            switches = [self.controller.get_switch_by_dpid(dpid)]
51
52 1
        switch_flows = {}
53
54 1
        for switch in switches:
55 1
            flows_dict = [flow.as_dict() for flow in switch.flows]
56 1
            switch_flows[switch.dpid] = {'flows': flows_dict}
57
58 1
        return jsonify(switch_flows)
59
60 1
    @rest('v2/flows', methods=['POST'])
61 1
    @rest('v2/flows/<dpid>', methods=['POST'])
62 1
    def add(self, dpid=None):
63
        """Install new flows in the switch identified by dpid.
64
65
        If no dpid is specified, install flows in all switches.
66
        """
67 1
        return self._send_flow_mods_from_request(dpid, "add")
68
69 1
    @rest('v2/delete', methods=['POST'])
70 1
    @rest('v2/delete/<dpid>', methods=['POST'])
71 1
    @rest('v2/flows', methods=['DELETE'])
72 1
    @rest('v2/flows/<dpid>', methods=['DELETE'])
73 1
    def delete(self, dpid=None):
74
        """Delete existing flows in the switch identified by dpid.
75
76
        If no dpid is specified, delete flows from all switches.
77
        """
78 1
        return self._send_flow_mods_from_request(dpid, "delete")
79
80 1
    def _get_all_switches_enabled(self):
81
        """Get a list of all switches enabled."""
82 1
        switches = self.controller.switches.values()
83 1
        return [switch for switch in switches if switch.is_enabled()]
84
85 1
    def _send_flow_mods_from_request(self, dpid, command):
86
        """Install FlowsMods from request."""
87 1
        flows_dict = request.get_json()
88
89 1
        if flows_dict is None:
90 1
            return jsonify({"response": 'flows dict is none.'}), 404
91
92 1
        if dpid:
93 1
            switch = self.controller.get_switch_by_dpid(dpid)
94 1
            if not switch:
95 1
                return jsonify({"response": 'dpid not found.'}), 404
96 1
            elif switch.is_enabled() is False:
97 1
                return jsonify({"response": 'switch is disabled.'}), 404
98
            else:
99 1
                self._install_flows(command, flows_dict, [switch])
100
        else:
101 1
            self._install_flows(command, flows_dict,
102
                                self._get_all_switches_enabled())
103
104 1
        return jsonify({"response": "FlowMod Messages Sent"})
105
106 1
    def _install_flows(self, command, flows_dict, switches=[]):
107
        """Execute all procedures to install flows in the switches.
108
109
        Args:
110
            command: Flow command to be installed
111
            flows_dict: Dictionary with flows to be installed in the switches.
112
            switches: A list of switches
113
        """
114 1
        for switch in switches:
115 1
            serializer = FlowFactory.get_class(switch)
116 1
            flows = flows_dict.get('flows', [])
117 1
            for flow_dict in flows:
118 1
                flow = serializer.from_dict(flow_dict, switch)
119 1
                if command == "delete":
120
                    flow_mod = flow.as_of_delete_flow_mod()
121 1
                elif command == "add":
122 1
                    flow_mod = flow.as_of_add_flow_mod()
123
                else:
124
                    raise InvalidCommandError
125 1
                self._send_flow_mod(flow.switch, flow_mod)
126 1
                self._add_flow_mod_sent(flow_mod.header.xid, flow, command)
127
128 1
                self._send_napp_event(switch, flow, command)
129
130 1
    def _add_flow_mod_sent(self, xid, flow, command):
131
        """Add the flow mod to the list of flow mods sent."""
132 1
        if len(self._flow_mods_sent) >= self._flow_mods_sent_max_size:
133
            self._flow_mods_sent.popitem(last=False)
134 1
        self._flow_mods_sent[xid] = (flow, command)
135
136 1
    def _send_flow_mod(self, switch, flow_mod):
137 1
        event_name = 'kytos/flow_manager.messages.out.ofpt_flow_mod'
138
139 1
        content = {'destination': switch.connection,
140
                   'message': flow_mod}
141
142 1
        event = KytosEvent(name=event_name, content=content)
143 1
        self.controller.buffers.msg_out.put(event)
144
145 1
    def _send_napp_event(self, switch, flow, command, **kwargs):
146
        """Send an Event to other apps informing about a FlowMod."""
147 1
        if command == 'add':
148 1
            name = 'kytos/flow_manager.flow.added'
149 1
        elif command == 'delete':
150 1
            name = 'kytos/flow_manager.flow.removed'
151 1
        elif command == 'error':
152 1
            name = 'kytos/flow_manager.flow.error'
153
        else:
154
            raise InvalidCommandError
155 1
        content = {'datapath': switch,
156
                   'flow': flow}
157 1
        content.update(kwargs)
158 1
        event_app = KytosEvent(name, content)
159 1
        self.controller.buffers.app.put(event_app)
160
161 1
    @listen_to('.*.of_core.*.ofpt_error')
162
    def handle_errors(self, event):
163
        """Receive OpenFlow error and send a event.
164
165
        The event is sent only if the error is related to a request made
166
        by flow_manager.
167
        """
168 1
        message = event.content["message"]
169
170 1
        connection = event.source
171 1
        switch = connection.switch
172
173 1
        xid = message.header.xid.value
174 1
        error_type = message.error_type
175 1
        error_code = message.code
176 1
        error_data = message.data.pack()
177
178
        # Get the packet responsible for the error
179 1
        error_packet = connection.protocol.unpack(error_data)
180
181 1
        if message.code == BadActionCode.OFPBAC_BAD_OUT_PORT:
182
            for action in error_packet.actions:
183
                try:
184
                    iface = switch.get_interface_by_port_no(action.port.value)
185
                except AttributeError:
186
                    iface = switch.get_interface_by_port_no(action.port)
187
188
                # Set interface to drop packets forwarded to it
189
                if iface:
190
                    iface.config = PortConfig.OFPPC_NO_FWD
191 1
        try:
192 1
            flow, error_command = self._flow_mods_sent[xid]
193
        except KeyError:
194
            pass
195
        else:
196 1
            self._send_napp_event(flow.switch, flow, 'error',
197
                                  error_command=error_command,
198
                                  error_type=error_type, error_code=error_code)
199