Passed
Pull Request — master (#116)
by Antonio
05:06
created

build.main   B

Complexity

Total Complexity 46

Size/Duplication

Total Lines 291
Duplicated Lines 0 %

Test Coverage

Coverage 42.18%

Importance

Changes 0
Metric Value
eloc 158
dl 0
loc 291
ccs 62
cts 147
cp 0.4218
rs 8.72
c 0
b 0
f 0
wmc 46

14 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.setup() 0 16 1
A Main.get_circuit() 0 13 2
A Main.shutdown() 0 2 1
A Main.execute() 0 2 1
A Main.list_circuits() 0 8 2
A Main.is_duplicated_evc() 0 20 4
B Main.create_circuit() 0 56 5
A Main.update() 0 24 3
A Main.delete_circuit() 0 15 1
A Main.uni_from_dict() 0 18 4
A Main.handle_link_up() 0 13 3
A Main.link_from_dict() 0 20 4
A Main.handle_link_down() 0 15 4
C Main.evc_from_dict() 0 30 11

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