Passed
Pull Request — master (#152)
by Antonio
04:16
created

build.main   B

Complexity

Total Complexity 50

Size/Duplication

Total Lines 292
Duplicated Lines 0 %

Test Coverage

Coverage 45.1%

Importance

Changes 0
Metric Value
eloc 164
dl 0
loc 292
ccs 69
cts 153
cp 0.451
rs 8.4
c 0
b 0
f 0
wmc 50

14 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.list_circuits() 0 8 2
A Main.uni_from_dict() 0 18 4
A Main.is_duplicated_evc() 0 14 4
A Main.handle_link_up() 0 6 4
A Main.link_from_dict() 0 20 4
A Main.get_circuit() 0 12 2
A Main.shutdown() 0 2 1
A Main.setup() 0 19 1
A Main.handle_link_down() 0 7 3
A Main.execute() 0 2 1
B Main.create_circuit() 0 59 5
C Main.evc_from_dict() 0 30 11
B Main.update() 0 28 5
A Main.delete_circuit() 0 27 3

How to fix   Complexity   

Complexity

Complex classes like build.main 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
"""Main module of kytos/mef_eline Kytos Network Application.
2
3
NApp to provision circuits from user request.
4
"""
5 2
from flask import jsonify, request
6 2
from werkzeug.exceptions import BadRequest
7
8 2
from kytos.core import KytosNApp, log, rest
9 2
from kytos.core.events import KytosEvent
10 2
from kytos.core.helpers import listen_to
11 2
from kytos.core.interface import TAG, UNI
12 2
from kytos.core.link import Link
13 2
from napps.kytos.mef_eline.models import EVC, DynamicPathManager
14 2
from napps.kytos.mef_eline.scheduler import CircuitSchedule, Scheduler
15 2
from napps.kytos.mef_eline.storehouse import StoreHouse
16
17
18 2
class Main(KytosNApp):
19
    """Main class of amlight/mef_eline NApp.
20
21
    This class is the entry point for this napp.
22
    """
23
24 2
    def setup(self):
25
        """Replace the '__init__' method for the KytosNApp subclass.
26
27
        The setup method is automatically called by the controller when your
28
        application is loaded.
29
30
        So, if you have any setup routine, insert it here.
31
        """
32
        # object used to scheduler circuit events
33 2
        self.sched = Scheduler()
34
35
        # object to save and load circuits
36 2
        self.storehouse = StoreHouse(self.controller)
37
38
        # set the controller that will manager the dynamic paths
39 2
        DynamicPathManager.set_controller(self.controller)
40
41
        # dictionary of EVCs created
42 2
        self.circuits = {}
43
44 2
    def execute(self):
45
        """Execute once when the napp is running."""
46
47 2
    def shutdown(self):
48
        """Execute when your napp is unloaded.
49
50
        If you have some cleanup procedure, insert it here.
51
        """
52
53 2
    @rest('/v2/evc/', methods=['GET'])
54
    def list_circuits(self):
55
        """Endpoint to return all circuits stored."""
56 2
        circuits = self.storehouse.get_data()
57 2
        if not circuits:
58 2
            return jsonify({}), 200
59
60 2
        return jsonify(circuits), 200
61
62 2
    @rest('/v2/evc/<circuit_id>', methods=['GET'])
63
    def get_circuit(self, circuit_id):
64
        """Endpoint to return a circuit based on id."""
65 2
        circuits = self.storehouse.get_data()
66 2
        try:
67 2
            result = circuits[circuit_id]
68 2
            status = 200
69 2
        except KeyError:
70 2
            result = {'response': f'circuit_id {circuit_id} not found'}
71 2
            status = 404
72
73 2
        return jsonify(result), status
74
75 2
    @rest('/v2/evc/', methods=['POST'])
76
    def create_circuit(self):
77
        """Try to create a new circuit.
78
79
        Firstly, for EVPL: E-Line NApp verifies if UNI_A's requested C-VID and
80
        UNI_Z's requested C-VID are available from the interfaces' pools. This
81
        is checked when creating the UNI object.
82
83
        Then, E-Line NApp requests a primary and a backup path to the
84
        Pathfinder NApp using the attributes primary_links and backup_links
85
        submitted via REST
86
87
        # For each link composing paths in #3:
88
        #  - E-Line NApp requests a S-VID available from the link VLAN pool.
89
        #  - Using the S-VID obtained, generate abstract flow entries to be
90
        #    sent to FlowManager
91
92
        Push abstract flow entries to FlowManager and FlowManager pushes
93
        OpenFlow entries to datapaths
94
95
        E-Line NApp generates an event to notify all Kytos NApps of a new EVC
96
        creation
97
98
        Finnaly, notify user of the status of its request.
99
        """
100
        # Try to create the circuit object
101 2
        data = request.get_json()
102
103 2
        if not data:
104 2
            return jsonify("Bad request: The request do not have a json."), 400
105
106 2
        try:
107 2
            evc = self.evc_from_dict(data)
108
        except ValueError as exception:
109
            return jsonify("Bad request: {}".format(exception)), 400
110
111
        # verify duplicated evc
112 2
        if self.is_duplicated_evc(evc):
113 2
            return jsonify("Not Acceptable: This evc already exists."), 409
114
115
        # store circuit in dictionary
116 2
        self.circuits[evc.id] = evc
117
118
        # save circuit
119 2
        self.storehouse.save_evc(evc)
120
121
        # Schedule the circuit deploy
122 2
        self.sched.add(evc)
123
124
        # Circuit has no schedule, deploy now
125 2
        if not evc.circuit_scheduler:
126 2
            evc.deploy()
127
128
        # Notify users
129 2
        event = KytosEvent(name='kytos.mef_eline.created',
130
                           content=evc.as_dict())
131 2
        self.controller.buffers.app.put(event)
132
133 2
        return jsonify({"circuit_id": evc.id}), 201
134
135 2
    @rest('/v2/evc/<circuit_id>', methods=['PATCH'])
136
    def update(self, circuit_id):
137
        """Update a circuit based on payload.
138
139
        The EVC required attributes (name, uni_a, uni_z) can't be updated.
140
        """
141
        try:
142
            evc = self.circuits[circuit_id]
143
            data = request.get_json()
144
            evc.update(**data)
145
            evc.sync()
146
            result = {evc.id: evc.as_dict()}
147
            status = 200
148
        except ValueError as exception:
149
            result = {'response': 'Bad Request: {}'.format(exception)}
150
            status = 400
151
        except TypeError:
152
            result = {'response': 'Content-Type must be application/json'}
153
            status = 415
154
        except BadRequest:
155
            response = 'Bad Request: The request is not in JSON format.'
156
            result = {'response': response}
157
            status = 400
158
        except KeyError:
159
            result = {'response': f'circuit_id {circuit_id} not found'}
160
            status = 404
161
162
        return jsonify(result), status
163
164 2
    @rest('/v2/evc/<circuit_id>', methods=['DELETE'])
165
    def delete_circuit(self, circuit_id):
166
        """Remove a circuit.
167
168
        First, the flows are removed from the switches, and then the EVC is
169
        disabled.
170
        """
171
        try:
172
            evc = self.circuits[circuit_id]
173
            log.info(f'Removing {circuit_id}')
174
            if evc.archived:
175
                result = {'response': f'Circuit {circuit_id} already removed'}
176
                status = 404
177
            else:
178
                evc.remove_current_flows()
179
                evc.deactivate()
180
                evc.disable()
181
                self.sched.remove(evc)
182
                evc.archive()
183
                evc.sync()
184
                result = {'response': f'Circuit {circuit_id} removed'}
185
                status = 200
186
        except KeyError:
187
            result = {'response': f'circuit_id {circuit_id} not found'}
188
            status = 404
189
190
        return jsonify(result), status
191
192 2
    def is_duplicated_evc(self, evc):
193
        """Verify if the circuit given is duplicated with the stored evcs.
194
195
        Args:
196
            evc (EVC): circuit to be analysed.
197
198
        Returns:
199
            boolean: True if the circuit is duplicated, otherwise False.
200
201
        """
202 2
        for circuit in self.circuits.values():
203 2
            if not circuit.archived and circuit == evc:
204 2
                return True
205 2
        return False
206
207 2
    @listen_to('kytos/topology.link_up')
208
    def handle_link_up(self, event):
209
        """Change circuit when link is up or end_maintenance."""
210
        for evc in self.circuits.values():
211
            if evc.is_enabled() and not evc.archived:
212
                evc.handle_link_up(event.content['link'])
213
214 2
    @listen_to('kytos/topology.link_down')
215
    def handle_link_down(self, event):
216
        """Change circuit when link is down or under_mantenance."""
217
        for evc in self.circuits.values():
218
            if evc.is_affected_by_link(event.content['link']):
219
                log.info('handling evc %s' % evc)
220
                evc.handle_link_down()
221
222 2
    def evc_from_dict(self, evc_dict):
223
        """Convert some dict values to instance of EVC classes.
224
225
        This method will convert: [UNI, Link]
226
        """
227 2
        data = evc_dict.copy()  # Do not modify the original dict
228
229 2
        for attribute, value in data.items():
230
231 2
            if 'uni' in attribute:
232 2
                try:
233 2
                    data[attribute] = self.uni_from_dict(value)
234
                except ValueError as exc:
235
                    raise ValueError(f'Error creating UNI: {exc}')
236
237 2
            if attribute == 'circuit_scheduler':
238
                data[attribute] = []
239
                for schedule in value:
240
                    data[attribute].append(CircuitSchedule.from_dict(schedule))
241
242 2
            if 'link' in attribute:
243
                if value:
244
                    data[attribute] = self.link_from_dict(value)
245
246 2
            if 'path' in attribute and attribute != 'dynamic_backup_path':
247
                if value:
248
                    data[attribute] = [self.link_from_dict(link)
249
                                       for link in value]
250
251 2
        return EVC(self.controller, **data)
252
253 2
    def uni_from_dict(self, uni_dict):
254
        """Return a UNI object from python dict."""
255
        if uni_dict is None:
256
            return False
257
258
        interface_id = uni_dict.get("interface_id")
259
        interface = self.controller.get_interface_by_id(interface_id)
260
        if interface is None:
261
            raise ValueError(f'Could not instantiate interface {interface_id}')
262
263
        tag_dict = uni_dict.get("tag")
264
        tag = TAG.from_dict(tag_dict)
265
        if tag is False:
266
            raise ValueError(f'Could not instantiate tag from dict {tag_dict}')
267
268
        uni = UNI(interface, tag)
269
270
        return uni
271
272 2
    def link_from_dict(self, link_dict):
273
        """Return a Link object from python dict."""
274
        id_a = link_dict.get('endpoint_a').get('id')
275
        id_b = link_dict.get('endpoint_b').get('id')
276
277
        endpoint_a = self.controller.get_interface_by_id(id_a)
278
        endpoint_b = self.controller.get_interface_by_id(id_b)
279
280
        link = Link(endpoint_a, endpoint_b)
281
        if 'metadata' in link_dict:
282
            link.extend_metadata(link_dict.get('metadata'))
283
284
        s_vlan = link.get_metadata('s_vlan')
285
        if s_vlan:
286
            tag = TAG.from_dict(s_vlan)
287
            if tag is False:
288
                error_msg = f'Could not instantiate tag from dict {s_vlan}'
289
                raise ValueError(error_msg)
290
            link.update_metadata('s_vlan', tag)
291
        return link
292