Passed
Pull Request — master (#214)
by Antonio
03:16
created

build.main   F

Complexity

Total Complexity 105

Size/Duplication

Total Lines 687
Duplicated Lines 0 %

Test Coverage

Coverage 73.63%

Importance

Changes 0
Metric Value
eloc 411
dl 0
loc 687
ccs 282
cts 383
cp 0.7363
rs 2
c 0
b 0
f 0
wmc 105

26 Methods

Rating   Name   Duplication   Size   Complexity  
C Main.load_evcs() 0 28 9
A Main.update_schedule() 0 50 3
A Main.handle_link_up() 0 7 4
A Main.load_circuits_by_interface() 0 13 4
A Main.delete_schedule() 0 35 3
A Main.add_to_dict_of_sets() 0 5 2
A Main.handle_link_down() 0 8 3
B Main.list_schedules() 0 29 5
A Main._is_duplicated_evc() 0 14 4
B Main.create_schedule() 0 76 7
A Main.list_circuits() 0 17 3
C Main._evc_dict_with_instances() 0 40 9
A Main._find_evc_by_schedule_id() 0 21 5
A Main._evc_from_dict() 0 3 1
A Main.get_circuit() 0 16 2
A Main.shutdown() 0 2 1
A Main.setup() 0 23 1
A Main.execute() 0 2 1
B Main.create_circuit() 0 72 6
A Main._link_from_dict() 0 20 4
A Main._uni_from_dict() 0 19 5
A Main.handle_flow_mod_error() 0 11 3
A Main.json_from_request() 0 23 4
C Main.update() 0 52 10
A Main._get_circuits_buffer() 0 13 3
A Main.delete_circuit() 0 33 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 1
from flask import jsonify, request
6 1
from pyof.v0x04.controller2switch.flow_mod import FlowModCommand
7 1
from werkzeug.exceptions import (BadRequest, Conflict, Forbidden,
8
                                 MethodNotAllowed, NotFound,
9
                                 UnsupportedMediaType)
10
11 1
from kytos.core import KytosNApp, log, rest
12 1
from kytos.core.events import KytosEvent
13 1
from kytos.core.helpers import listen_to
14 1
from kytos.core.interface import TAG, UNI
15 1
from kytos.core.link import Link
16 1
from napps.kytos.mef_eline.models import EVC, DynamicPathManager, Path
17 1
from napps.kytos.mef_eline.scheduler import CircuitSchedule, Scheduler
18 1
from napps.kytos.mef_eline.storehouse import StoreHouse
19
20
21 1
class Main(KytosNApp):
22
    """Main class of amlight/mef_eline NApp.
23
24
    This class is the entry point for this napp.
25
    """
26
27 1
    def setup(self):
28
        """Replace the '__init__' method for the KytosNApp subclass.
29
30
        The setup method is automatically called by the controller when your
31
        application is loaded.
32
33
        So, if you have any setup routine, insert it here.
34
        """
35
        # object used to scheduler circuit events
36 1
        self.sched = Scheduler()
37
38
        # object to save and load circuits
39 1
        self.storehouse = StoreHouse(self.controller)
40
41
        # set the controller that will manager the dynamic paths
42 1
        DynamicPathManager.set_controller(self.controller)
43
44
        # dictionary of EVCs created. It acts as a circuit buffer.
45
        # Every create/update/delete must be synced to storehouse.
46 1
        self.circuits = {}
47
48
        # dictionary of EVCs by interface
49 1
        self._circuits_by_interface = {}
50
51 1
    def execute(self):
52
        """Execute once when the napp is running."""
53
54 1
    def shutdown(self):
55
        """Execute when your napp is unloaded.
56
57
        If you have some cleanup procedure, insert it here.
58
        """
59
60 1
    @rest('/v2/evc/', methods=['GET'])
61
    def list_circuits(self):
62
        """Endpoint to return circuits stored.
63
64
        If archived is set to True return all circuits, else only the ones
65
        not archived.
66
        """
67 1
        log.debug('list_circuits /v2/evc')
68 1
        archived = request.args.get('archived', False)
69 1
        circuits = self.storehouse.get_data()
70 1
        if not circuits:
71 1
            return jsonify({}), 200
72 1
        if archived:
73 1
            return jsonify(circuits), 200
74 1
        return jsonify({circuit_id: circuit
75
                        for circuit_id, circuit in circuits.items()
76
                        if not circuit.get('archived', False)}), 200
77
78 1
    @rest('/v2/evc/<circuit_id>', methods=['GET'])
79
    def get_circuit(self, circuit_id):
80
        """Endpoint to return a circuit based on id."""
81 1
        log.debug('get_circuit /v2/evc/%s', circuit_id)
82 1
        circuits = self.storehouse.get_data()
83
84 1
        try:
85 1
            result = circuits[circuit_id]
86 1
        except KeyError:
87 1
            result = f'circuit_id {circuit_id} not found'
88 1
            log.debug('get_circuit result %s %s', result, 404)
89 1
            raise NotFound(result)
90
91 1
        status = 200
92 1
        log.debug('get_circuit result %s %s', result, status)
93 1
        return jsonify(result), status
94
95 1
    @rest('/v2/evc/', methods=['POST'])
96
    def create_circuit(self):
97
        """Try to create a new circuit.
98
99
        Firstly, for EVPL: E-Line NApp verifies if UNI_A's requested C-VID and
100
        UNI_Z's requested C-VID are available from the interfaces' pools. This
101
        is checked when creating the UNI object.
102
103
        Then, E-Line NApp requests a primary and a backup path to the
104
        Pathfinder NApp using the attributes primary_links and backup_links
105
        submitted via REST
106
107
        # For each link composing paths in #3:
108
        #  - E-Line NApp requests a S-VID available from the link VLAN pool.
109
        #  - Using the S-VID obtained, generate abstract flow entries to be
110
        #    sent to FlowManager
111
112
        Push abstract flow entries to FlowManager and FlowManager pushes
113
        OpenFlow entries to datapaths
114
115
        E-Line NApp generates an event to notify all Kytos NApps of a new EVC
116
        creation
117
118
        Finnaly, notify user of the status of its request.
119
        """
120
        # Try to create the circuit object
121 1
        log.debug('create_circuit /v2/evc/')
122 1
        try:
123 1
            data = request.get_json()
124
        except BadRequest:
125
            result = 'The request body is not a well-formed JSON.'
126
            log.debug('create_circuit result %s %s', result, 400)
127
            raise BadRequest(result)
128
129 1
        if data is None:
130 1
            result = 'The request body mimetype is not application/json.'
131 1
            log.debug('create_circuit result %s %s', result, 415)
132 1
            raise UnsupportedMediaType(result)
133 1
        try:
134 1
            evc = self._evc_from_dict(data)
135
        except ValueError as exception:
136
            log.debug('create_circuit result %s %s', exception, 400)
137
            raise BadRequest(str(exception))
138
139
        # verify duplicated evc
140 1
        if self._is_duplicated_evc(evc):
141 1
            result = "The EVC already exists."
142 1
            log.debug('create_circuit result %s %s', result, 409)
143 1
            raise Conflict(result)
144
145
        # store circuit in dictionary
146 1
        self.circuits[evc.id] = evc
147
148
        # save circuit
149 1
        self.storehouse.save_evc(evc)
150
151
        # Schedule the circuit deploy
152 1
        self.sched.add(evc)
153
154
        # Circuit has no schedule, deploy now
155 1
        if not evc.circuit_scheduler:
156 1
            evc.deploy()
157
158
        # Notify users
159 1
        event = KytosEvent(name='kytos.mef_eline.created',
160
                           content=evc.as_dict())
161 1
        self.controller.buffers.app.put(event)
162
163 1
        result = {"circuit_id": evc.id}
164 1
        status = 201
165 1
        log.debug('create_circuit result %s %s', result, status)
166 1
        return jsonify(result), status
167
168 1
    @rest('/v2/evc/<circuit_id>', methods=['PATCH'])
169
    def update(self, circuit_id):
170
        """Update a circuit based on payload.
171
172
        The EVC required attributes (name, uni_a, uni_z) can't be updated.
173
        """
174 1
        log.debug('update /v2/evc/%s', circuit_id)
175 1
        try:
176 1
            evc = self.circuits[circuit_id]
177 1
        except KeyError:
178 1
            result = f'circuit_id {circuit_id} not found'
179 1
            log.debug('update result %s %s', result, 404)
180 1
            raise NotFound(result)
181
182 1
        if evc.archived:
183 1
            result = f'Can\'t update archived EVC'
184 1
            log.debug('update result %s %s', result, 405)
185 1
            raise MethodNotAllowed(['GET'], result)
186
187 1
        try:
188 1
            data = request.get_json()
189 1
        except BadRequest:
190 1
            result = 'The request body is not a well-formed JSON.'
191 1
            log.debug('update result %s %s', result, 400)
192 1
            raise BadRequest(result)
193 1
        if data is None:
194
            result = 'The request body mimetype is not application/json.'
195
            log.debug('update result %s %s', result, 415)
196
            raise UnsupportedMediaType(result)
197
198 1
        try:
199 1
            enable, path = \
200
                evc.update(**self._evc_dict_with_instances(data))
201
        except ValueError as exception:
202
            log.error(exception)
203
            log.debug('update result %s %s', exception, 400)
204
            raise BadRequest(str(exception))
205
206 1
        if evc.is_active():
207 1
            if enable is False:  # disable if active
208
                evc.remove()
209 1
            elif path is not None:  # redeploy if active
210 1
                evc.remove()
211 1
                evc.deploy()
212
        else:
213 1
            if enable is True:  # enable if inactive
214 1
                evc.deploy()
215 1
        result = {evc.id: evc.as_dict()}
216 1
        status = 200
217
218 1
        log.debug('update result %s %s', result, status)
219 1
        return jsonify(result), status
220
221 1
    @rest('/v2/evc/<circuit_id>', methods=['DELETE'])
222
    def delete_circuit(self, circuit_id):
223
        """Remove a circuit.
224
225
        First, the flows are removed from the switches, and then the EVC is
226
        disabled.
227
        """
228 1
        log.debug('delete_circuit /v2/evc/%s', circuit_id)
229 1
        try:
230 1
            evc = self.circuits[circuit_id]
231
        except KeyError:
232
            result = f'circuit_id {circuit_id} not found'
233
            log.debug('delete_circuit result %s %s', result, 404)
234
            raise NotFound(result)
235
236 1
        if evc.archived:
237
            result = f'Circuit {circuit_id} already removed'
238
            log.debug('delete_circuit result %s %s', result, 404)
239
            raise NotFound(result)
240
241 1
        log.info('Removing %s', evc)
242 1
        evc.remove_current_flows()
243 1
        evc.deactivate()
244 1
        evc.disable()
245 1
        self.sched.remove(evc)
246 1
        evc.archive()
247 1
        evc.sync()
248 1
        log.info('EVC removed. %s', evc)
249 1
        result = {'response': f'Circuit {circuit_id} removed'}
250 1
        status = 200
251
252 1
        log.debug('delete_circuit result %s %s', result, status)
253 1
        return jsonify(result), status
254
255 1
    @rest('/v2/evc/schedule', methods=['GET'])
256
    def list_schedules(self):
257
        """Endpoint to return all schedules stored for all circuits.
258
259
        Return a JSON with the following template:
260
        [{"schedule_id": <schedule_id>,
261
         "circuit_id": <circuit_id>,
262
         "schedule": <schedule object>}]
263
        """
264 1
        log.debug('list_schedules /v2/evc/schedule')
265 1
        circuits = self.storehouse.get_data().values()
266 1
        if not circuits:
267 1
            result = {}
268 1
            status = 200
269 1
            return jsonify(result), status
270
271 1
        result = []
272 1
        status = 200
273 1
        for circuit in circuits:
274 1
            circuit_scheduler = circuit.get("circuit_scheduler")
275 1
            if circuit_scheduler:
276 1
                for scheduler in circuit_scheduler:
277 1
                    value = {"schedule_id": scheduler.get("id"),
278
                             "circuit_id": circuit.get("id"),
279
                             "schedule": scheduler}
280 1
                    result.append(value)
281
282 1
        log.debug('list_schedules result %s %s', result, status)
283 1
        return jsonify(result), status
284
285 1
    @rest('/v2/evc/schedule/', methods=['POST'])
286
    def create_schedule(self):
287
        """
288
        Create a new schedule for a given circuit.
289
290
        This service do no check if there are conflicts with another schedule.
291
        Payload example:
292
            {
293
              "circuit_id":"aa:bb:cc",
294
              "schedule": {
295
                "date": "2019-08-07T14:52:10.967Z",
296
                "interval": "string",
297
                "frequency": "1 * * * *",
298
                "action": "create"
299
              }
300
            }
301
        """
302 1
        log.debug('create_schedule /v2/evc/schedule/')
303
304 1
        json_data = self.json_from_request('create_schedule')
305 1
        try:
306 1
            circuit_id = json_data['circuit_id']
307
        except TypeError:
308
            result = 'The payload should have a dictionary.'
309
            log.debug('create_schedule result %s %s', result, 400)
310
            raise BadRequest(result)
311
        except KeyError:
312
            result = 'Missing circuit_id.'
313
            log.debug('create_schedule result %s %s', result, 400)
314
            raise BadRequest(result)
315
316 1
        try:
317 1
            schedule_data = json_data['schedule']
318
        except KeyError:
319
            result = 'Missing schedule data.'
320
            log.debug('create_schedule result %s %s', result, 400)
321
            raise BadRequest(result)
322
323
        # Get EVC from circuits buffer
324 1
        circuits = self._get_circuits_buffer()
325
326
        # get the circuit
327 1
        evc = circuits.get(circuit_id)
328
329
        # get the circuit
330 1
        if not evc:
331
            result = f'circuit_id {circuit_id} not found'
332
            log.debug('create_schedule result %s %s', result, 404)
333
            raise NotFound(result)
334
        # Can not modify circuits deleted and archived
335 1
        if evc.archived:
336
            result = f'Circuit {circuit_id} is archived. Update is forbidden.'
337
            log.debug('create_schedule result %s %s', result, 403)
338
            raise Forbidden(result)
339
340
        # new schedule from dict
341 1
        new_schedule = CircuitSchedule.from_dict(schedule_data)
342
343
        # If there is no schedule, create the list
344 1
        if not evc.circuit_scheduler:
345
            evc.circuit_scheduler = []
346
347
        # Add the new schedule
348 1
        evc.circuit_scheduler.append(new_schedule)
349
350
        # Add schedule job
351 1
        self.sched.add_circuit_job(evc, new_schedule)
352
353
        # save circuit to storehouse
354 1
        evc.sync()
355
356 1
        result = new_schedule.as_dict()
357 1
        status = 201
358
359 1
        log.debug('create_schedule result %s %s', result, status)
360 1
        return jsonify(result), status
361
362 1
    @rest('/v2/evc/schedule/<schedule_id>', methods=['PATCH'])
363
    def update_schedule(self, schedule_id):
364
        """Update a schedule.
365
366
        Change all attributes from the given schedule from a EVC circuit.
367
        The schedule ID is preserved as default.
368
        Payload example:
369
            {
370
              "date": "2019-08-07T14:52:10.967Z",
371
              "interval": "string",
372
              "frequency": "1 * * *",
373
              "action": "create"
374
            }
375
        """
376 1
        log.debug('update_schedule /v2/evc/schedule/%s', schedule_id)
377
378
        # Try to find a circuit schedule
379 1
        evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
380
381
        # Can not modify circuits deleted and archived
382 1
        if not found_schedule:
383
            result = f'schedule_id {schedule_id} not found'
384
            log.debug('update_schedule result %s %s', result, 404)
385
            raise NotFound(result)
386 1
        if evc.archived:
387 1
            result = f'Circuit {evc.id} is archived. Update is forbidden.'
388 1
            log.debug('update_schedule result %s %s', result, 403)
389 1
            raise Forbidden(result)
390
391 1
        data = self.json_from_request('update_schedule')
392
393 1
        new_schedule = CircuitSchedule.from_dict(data)
394 1
        new_schedule.id = found_schedule.id
395
        # Remove the old schedule
396 1
        evc.circuit_scheduler.remove(found_schedule)
397
        # Append the modified schedule
398 1
        evc.circuit_scheduler.append(new_schedule)
399
400
        # Cancel all schedule jobs
401 1
        self.sched.cancel_job(found_schedule.id)
402
        # Add the new circuit schedule
403 1
        self.sched.add_circuit_job(evc, new_schedule)
404
        # Save EVC to the storehouse
405 1
        evc.sync()
406
407 1
        result = new_schedule.as_dict()
408 1
        status = 200
409
410 1
        log.debug('update_schedule result %s %s', result, status)
411 1
        return jsonify(result), status
412
413 1
    @rest('/v2/evc/schedule/<schedule_id>', methods=['DELETE'])
414
    def delete_schedule(self, schedule_id):
415
        """Remove a circuit schedule.
416
417
        Remove the Schedule from EVC.
418
        Remove the Schedule from cron job.
419
        Save the EVC to the Storehouse.
420
        """
421 1
        log.debug('delete_schedule /v2/evc/schedule/%s', schedule_id)
422 1
        evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
423
424
        # Can not modify circuits deleted and archived
425 1
        if not found_schedule:
426
            result = f'schedule_id {schedule_id} not found'
427
            log.debug('delete_schedule result %s %s', result, 404)
428
            raise NotFound(result)
429
430 1
        if evc.archived:
431 1
            result = f'Circuit {evc.id} is archived. Update is forbidden.'
432 1
            log.debug('delete_schedule result %s %s', result, 403)
433 1
            raise Forbidden(result)
434
435
        # Remove the old schedule
436 1
        evc.circuit_scheduler.remove(found_schedule)
437
438
        # Cancel all schedule jobs
439 1
        self.sched.cancel_job(found_schedule.id)
440
        # Save EVC to the storehouse
441 1
        evc.sync()
442
443 1
        result = "Schedule removed"
444 1
        status = 200
445
446 1
        log.debug('delete_schedule result %s %s', result, status)
447 1
        return jsonify(result), status
448
449 1
    def _is_duplicated_evc(self, evc):
450
        """Verify if the circuit given is duplicated with the stored evcs.
451
452
        Args:
453
            evc (EVC): circuit to be analysed.
454
455
        Returns:
456
            boolean: True if the circuit is duplicated, otherwise False.
457
458
        """
459 1
        for circuit in self.circuits.values():
460 1
            if not circuit.archived and circuit == evc:
461 1
                return True
462 1
        return False
463
464 1
    @listen_to('kytos/topology.link_up')
465
    def handle_link_up(self, event):
466
        """Change circuit when link is up or end_maintenance."""
467 1
        log.debug("Event handle_link_up %s", event)
468 1
        for evc in self.circuits.values():
469 1
            if evc.is_enabled() and not evc.archived:
470 1
                evc.handle_link_up(event.content['link'])
471
472 1
    @listen_to('kytos/topology.link_down')
473
    def handle_link_down(self, event):
474
        """Change circuit when link is down or under_mantenance."""
475 1
        log.debug("Event handle_link_down %s", event)
476 1
        for evc in self.circuits.values():
477 1
            if evc.is_affected_by_link(event.content['link']):
478 1
                log.info('handling evc %s' % evc)
479 1
                evc.handle_link_down()
480
481 1
    def load_circuits_by_interface(self, circuits):
482
        """Load circuits in storehouse for in-memory dictionary."""
483 1
        for circuit_id, circuit in circuits.items():
484 1
            intf_a = circuit['uni_a']['interface_id']
485 1
            self.add_to_dict_of_sets(intf_a, circuit_id)
486 1
            intf_z = circuit['uni_z']['interface_id']
487 1
            self.add_to_dict_of_sets(intf_z, circuit_id)
488 1
            for path in ('current_path', 'primary_path', 'backup_path'):
489 1
                for link in circuit[path]:
490 1
                    intf_a = link['endpoint_a']['id']
491 1
                    self.add_to_dict_of_sets(intf_a, circuit_id)
492 1
                    intf_b = link['endpoint_b']['id']
493 1
                    self.add_to_dict_of_sets(intf_b, circuit_id)
494
495 1
    def add_to_dict_of_sets(self, intf, circuit_id):
496
        """Add a single item to the dictionary of circuits by interface."""
497 1
        if intf not in self._circuits_by_interface:
498 1
            self._circuits_by_interface[intf] = set()
499 1
        self._circuits_by_interface[intf].add(circuit_id)
500
501 1
    @listen_to('kytos/topology.port.created')
502
    def load_evcs(self, event):
503
        """Try to load the unloaded EVCs from storehouse."""
504
        log.debug("Event load_evcs %s", event)
505
        circuits = self.storehouse.get_data()
506
        if not self._circuits_by_interface:
507
            self.load_circuits_by_interface(circuits)
508
509
        interface_id = '{}:{}'.format(event.content['switch'],
510
                                      event.content['port'])
511
512
        for circuit_id in self._circuits_by_interface.get(interface_id, []):
513
            if circuit_id in circuits and circuit_id not in self.circuits:
514
                try:
515
                    evc = self._evc_from_dict(circuits[circuit_id])
516
                except ValueError as exception:
517
                    log.info(
518
                        f'Could not load EVC {circuit_id} because {exception}')
519
                    continue
520
                log.info(f'Loading EVC {circuit_id}')
521
                if evc.archived:
522
                    continue
523
                new_evc = self.circuits.setdefault(circuit_id, evc)
524
                if new_evc == evc:
525
                    if evc.is_enabled():
526
                        log.info(f'Trying to deploy EVC {circuit_id}')
527
                        evc.deploy()
528
                    self.sched.add(evc)
529
530 1
    @listen_to('kytos/flow_manager.flow.error')
531
    def handle_flow_mod_error(self, event):
532
        """Handle flow mod errors related to an EVC."""
533 1
        flow = event.content['flow']
534 1
        log.info(f'Flow error: {flow.cookie}')
535 1
        if flow.command != FlowModCommand.OFPFC_ADD:
536
            return
537 1
        evc_id = hex(flow.cookie).lstrip('0x').rstrip('L')
538 1
        evc = self.circuits.get(evc_id)
539 1
        if evc:
540 1
            evc.remove_current_flows()
541
542 1
    def _evc_dict_with_instances(self, evc_dict):
543
        """Convert some dict values to instance of EVC classes.
544
545
        This method will convert: [UNI, Link]
546
        """
547 1
        data = evc_dict.copy()  # Do not modify the original dict
548
549 1
        for attribute, value in data.items():
550
            # Get multiple attributes.
551
            # Ex: uni_a, uni_z
552 1
            if 'uni' in attribute:
553 1
                try:
554 1
                    data[attribute] = self._uni_from_dict(value)
555
                except ValueError as exc:
556
                    raise ValueError(f'Error creating UNI: {exc}')
557
558 1
            if attribute == 'circuit_scheduler':
559 1
                data[attribute] = []
560 1
                for schedule in value:
561 1
                    data[attribute].append(CircuitSchedule.from_dict(schedule))
562
563
            # Get multiple attributes.
564
            # Ex: primary_links,
565
            #     backup_links,
566
            #     current_links_cache,
567
            #     primary_links_cache,
568
            #     backup_links_cache
569 1
            if 'links' in attribute:
570 1
                data[attribute] = [self._link_from_dict(link)
571
                                   for link in value]
572
573
            # Get multiple attributes.
574
            # Ex: current_path,
575
            #     primary_path,
576
            #     backup_path
577 1
            if 'path' in attribute and attribute != 'dynamic_backup_path':
578 1
                data[attribute] = Path([self._link_from_dict(link)
579
                                        for link in value])
580
581 1
        return data
582
583 1
    def _evc_from_dict(self, evc_dict):
584 1
        data = self._evc_dict_with_instances(evc_dict)
585 1
        return EVC(self.controller, **data)
586
587 1
    def _uni_from_dict(self, uni_dict):
588
        """Return a UNI object from python dict."""
589
        if uni_dict is None:
590
            return False
591
592
        interface_id = uni_dict.get("interface_id")
593
        interface = self.controller.get_interface_by_id(interface_id)
594
        if interface is None:
595
            raise ValueError(f'Could not instantiate interface {interface_id}')
596
597
        try:
598
            tag_dict = uni_dict["tag"]
599
        except KeyError:
600
            tag = None
601
        else:
602
            tag = TAG.from_dict(tag_dict)
603
        uni = UNI(interface, tag)
604
605
        return uni
606
607 1
    def _link_from_dict(self, link_dict):
608
        """Return a Link object from python dict."""
609 1
        id_a = link_dict.get('endpoint_a').get('id')
610 1
        id_b = link_dict.get('endpoint_b').get('id')
611
612 1
        endpoint_a = self.controller.get_interface_by_id(id_a)
613 1
        endpoint_b = self.controller.get_interface_by_id(id_b)
614
615 1
        link = Link(endpoint_a, endpoint_b)
616 1
        if 'metadata' in link_dict:
617
            link.extend_metadata(link_dict.get('metadata'))
618
619 1
        s_vlan = link.get_metadata('s_vlan')
620 1
        if s_vlan:
621
            tag = TAG.from_dict(s_vlan)
622
            if tag is False:
623
                error_msg = f'Could not instantiate tag from dict {s_vlan}'
624
                raise ValueError(error_msg)
625
            link.update_metadata('s_vlan', tag)
626 1
        return link
627
628 1
    def _find_evc_by_schedule_id(self, schedule_id):
629
        """
630
        Find an EVC and CircuitSchedule based on schedule_id.
631
632
        :param schedule_id: Schedule ID
633
        :return: EVC and Schedule
634
        """
635 1
        circuits = self._get_circuits_buffer()
636 1
        found_schedule = None
637 1
        evc = None
638
639
        # pylint: disable=unused-variable
640 1
        for c_id, circuit in circuits.items():
641 1
            for schedule in circuit.circuit_scheduler:
642 1
                if schedule.id == schedule_id:
643 1
                    found_schedule = schedule
644 1
                    evc = circuit
645 1
                    break
646 1
            if found_schedule:
647 1
                break
648 1
        return evc, found_schedule
649
650 1
    def _get_circuits_buffer(self):
651
        """
652
        Return the circuit buffer.
653
654
        If the buffer is empty, try to load data from storehouse.
655
        """
656 1
        if not self.circuits:
657
            # Load storehouse circuits to buffer
658 1
            circuits = self.storehouse.get_data()
659 1
            for c_id, circuit in circuits.items():
660 1
                evc = self._evc_from_dict(circuit)
661 1
                self.circuits[c_id] = evc
662 1
        return self.circuits
663
664 1
    @staticmethod
665
    def json_from_request(caller):
666
        """Return a json from request.
667
668
        If it was not possible to get a json from the request, log, for debug,
669
        who was the caller and the error that ocurred, and raise an
670
        Exception.
671
        """
672 1
        try:
673 1
            json_data = request.get_json()
674
        except ValueError as exception:
675
            log.error(exception)
676
            log.debug(f'{caller} result {exception} 400')
677
            raise BadRequest(str(exception))
678
        except BadRequest:
679
            result = 'The request is not a valid JSON.'
680
            log.debug(f'{caller} result {result} 400')
681
            raise BadRequest(result)
682 1
        if json_data is None:
683
            result = 'Content-Type must be application/json'
684
            log.debug(f'{caller} result {result} 415')
685
            raise UnsupportedMediaType(result)
686
        return json_data
687