Passed
Pull Request — master (#195)
by Antonio
03:15
created

build.main   F

Complexity

Total Complexity 101

Size/Duplication

Total Lines 674
Duplicated Lines 0 %

Test Coverage

Coverage 68.1%

Importance

Changes 0
Metric Value
eloc 400
dl 0
loc 674
ccs 254
cts 373
cp 0.681
rs 2
c 0
b 0
f 0
wmc 101

25 Methods

Rating   Name   Duplication   Size   Complexity  
A Main.list_circuits() 0 17 3
C Main._evc_dict_with_instances() 0 40 9
C Main.load_evcs() 0 28 9
A Main.update_schedule() 0 50 3
A Main._find_evc_by_schedule_id() 0 21 5
A Main._evc_from_dict() 0 3 1
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.get_circuit() 0 16 2
A Main.add_to_dict_of_sets() 0 5 2
A Main.shutdown() 0 2 1
A Main.setup() 0 23 1
A Main.handle_link_down() 0 8 3
A Main.execute() 0 2 1
B Main.create_circuit() 0 73 6
B Main.list_schedules() 0 29 5
A Main._link_from_dict() 0 20 4
A Main._uni_from_dict() 0 18 4
A Main._is_duplicated_evc() 0 14 4
A Main.json_from_request() 0 23 4
C Main.update() 0 52 10
B Main.create_schedule() 0 76 7
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 werkzeug.exceptions import (BadRequest, Conflict, Forbidden,
7
                                 MethodNotAllowed, NotFound,
8
                                 UnsupportedMediaType)
9
10 1
from kytos.core import KytosNApp, log, rest
11 1
from kytos.core.events import KytosEvent
12 1
from kytos.core.helpers import listen_to
13 1
from kytos.core.interface import TAG, UNI
14 1
from kytos.core.link import Link
15 1
from napps.kytos.mef_eline.models import EVC, DynamicPathManager, Path
16 1
from napps.kytos.mef_eline.scheduler import CircuitSchedule, Scheduler
17 1
from napps.kytos.mef_eline.storehouse import StoreHouse
18
19
20 1
class Main(KytosNApp):
21
    """Main class of amlight/mef_eline NApp.
22
23
    This class is the entry point for this napp.
24
    """
25
26 1
    def setup(self):
27
        """Replace the '__init__' method for the KytosNApp subclass.
28
29
        The setup method is automatically called by the controller when your
30
        application is loaded.
31
32
        So, if you have any setup routine, insert it here.
33
        """
34
        # object used to scheduler circuit events
35 1
        self.sched = Scheduler()
36
37
        # object to save and load circuits
38 1
        self.storehouse = StoreHouse(self.controller)
39
40
        # set the controller that will manager the dynamic paths
41 1
        DynamicPathManager.set_controller(self.controller)
42
43
        # dictionary of EVCs created. It acts as a circuit buffer.
44
        # Every create/update/delete must be synced to storehouse.
45 1
        self.circuits = {}
46
47
        # dictionary of EVCs by interface
48 1
        self._circuits_by_interface = {}
49
50 1
    def execute(self):
51
        """Execute once when the napp is running."""
52
53 1
    def shutdown(self):
54
        """Execute when your napp is unloaded.
55
56
        If you have some cleanup procedure, insert it here.
57
        """
58
59 1
    @rest('/v2/evc/', methods=['GET'])
60
    def list_circuits(self):
61
        """Endpoint to return circuits stored.
62
63
        If archived is set to True return all circuits, else only the ones
64
        not archived.
65
        """
66 1
        log.debug('list_circuits /v2/evc')
67 1
        archived = request.args.get('archived', False)
68 1
        circuits = self.storehouse.get_data()
69 1
        if not circuits:
70 1
            return jsonify({}), 200
71 1
        if archived:
72 1
            return jsonify(circuits), 200
73 1
        return jsonify({circuit_id: circuit
74
                        for circuit_id, circuit in circuits.items()
75
                        if not circuit.get('archived', False)}), 200
76
77 1
    @rest('/v2/evc/<circuit_id>', methods=['GET'])
78
    def get_circuit(self, circuit_id):
79
        """Endpoint to return a circuit based on id."""
80 1
        log.debug('get_circuit /v2/evc/%s', circuit_id)
81 1
        circuits = self.storehouse.get_data()
82
83 1
        try:
84 1
            result = circuits[circuit_id]
85 1
        except KeyError:
86 1
            result = f'circuit_id {circuit_id} not found'
87 1
            log.debug('get_circuit result %s %s', result, 404)
88 1
            raise NotFound(result)
89
90 1
        status = 200
91 1
        log.debug('get_circuit result %s %s', result, status)
92 1
        return jsonify(result), status
93
94 1
    @rest('/v2/evc/', methods=['POST'])
95
    def create_circuit(self):
96
        """Try to create a new circuit.
97
98
        Firstly, for EVPL: E-Line NApp verifies if UNI_A's requested C-VID and
99
        UNI_Z's requested C-VID are available from the interfaces' pools. This
100
        is checked when creating the UNI object.
101
102
        Then, E-Line NApp requests a primary and a backup path to the
103
        Pathfinder NApp using the attributes primary_links and backup_links
104
        submitted via REST
105
106
        # For each link composing paths in #3:
107
        #  - E-Line NApp requests a S-VID available from the link VLAN pool.
108
        #  - Using the S-VID obtained, generate abstract flow entries to be
109
        #    sent to FlowManager
110
111
        Push abstract flow entries to FlowManager and FlowManager pushes
112
        OpenFlow entries to datapaths
113
114
        E-Line NApp generates an event to notify all Kytos NApps of a new EVC
115
        creation
116
117
        Finnaly, notify user of the status of its request.
118
        """
119
        # Try to create the circuit object
120 1
        log.debug('create_circuit /v2/evc/')
121 1
        try:
122 1
            data = request.get_json()
123
        except BadRequest:
124
            result = 'The request body is not a well-formed JSON.'
125
            log.debug('create_circuit result %s %s', result, 400)
126
            raise BadRequest(result)
127
128 1
        if data is None:
129 1
            result = 'The request body mimetype is not application/json.'
130 1
            log.debug('create_circuit result %s %s', result, 415)
131 1
            raise UnsupportedMediaType(result)
132 1
        try:
133 1
            evc = self._evc_from_dict(data)
134
        except ValueError as exception:
135
            result = "{}".format(exception)
136
            log.debug('create_circuit result %s %s', result, 400)
137
            raise BadRequest(result)
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
            result = f'Can\'t update archived EVC'
184
            log.debug('update result %s %s', result, 405)
185
            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
        log.debug('delete_circuit /v2/evc/%s', circuit_id)
229
        try:
230
            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
        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
        log.info('Removing %s', evc)
242
        evc.remove_current_flows()
243
        evc.deactivate()
244
        evc.disable()
245
        self.sched.remove(evc)
246
        evc.archive()
247
        evc.sync()
248
        log.info('EVC removed. %s', evc)
249
        result = {'response': f'Circuit {circuit_id} removed'}
250
        status = 200
251
252
        log.debug('delete_circuit result %s %s', result, status)
253
        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
    def _evc_dict_with_instances(self, evc_dict):
531
        """Convert some dict values to instance of EVC classes.
532
533
        This method will convert: [UNI, Link]
534
        """
535 1
        data = evc_dict.copy()  # Do not modify the original dict
536
537 1
        for attribute, value in data.items():
538
            # Get multiple attributes.
539
            # Ex: uni_a, uni_z
540 1
            if 'uni' in attribute:
541 1
                try:
542 1
                    data[attribute] = self._uni_from_dict(value)
543
                except ValueError as exc:
544
                    raise ValueError(f'Error creating UNI: {exc}')
545
546 1
            if attribute == 'circuit_scheduler':
547 1
                data[attribute] = []
548 1
                for schedule in value:
549 1
                    data[attribute].append(CircuitSchedule.from_dict(schedule))
550
551
            # Get multiple attributes.
552
            # Ex: primary_links,
553
            #     backup_links,
554
            #     current_links_cache,
555
            #     primary_links_cache,
556
            #     backup_links_cache
557 1
            if 'links' in attribute:
558 1
                data[attribute] = [self._link_from_dict(link)
559
                                   for link in value]
560
561
            # Get multiple attributes.
562
            # Ex: current_path,
563
            #     primary_path,
564
            #     backup_path
565 1
            if 'path' in attribute and attribute != 'dynamic_backup_path':
566 1
                data[attribute] = Path([self._link_from_dict(link)
567
                                        for link in value])
568
569 1
        return data
570
571 1
    def _evc_from_dict(self, evc_dict):
572 1
        data = self._evc_dict_with_instances(evc_dict)
573 1
        return EVC(self.controller, **data)
574
575 1
    def _uni_from_dict(self, uni_dict):
576
        """Return a UNI object from python dict."""
577
        if uni_dict is None:
578
            return False
579
580
        interface_id = uni_dict.get("interface_id")
581
        interface = self.controller.get_interface_by_id(interface_id)
582
        if interface is None:
583
            raise ValueError(f'Could not instantiate interface {interface_id}')
584
585
        tag_dict = uni_dict.get("tag")
586
        tag = TAG.from_dict(tag_dict)
587
        if tag is False:
588
            raise ValueError(f'Could not instantiate tag from dict {tag_dict}')
589
590
        uni = UNI(interface, tag)
591
592
        return uni
593
594 1
    def _link_from_dict(self, link_dict):
595
        """Return a Link object from python dict."""
596 1
        id_a = link_dict.get('endpoint_a').get('id')
597 1
        id_b = link_dict.get('endpoint_b').get('id')
598
599 1
        endpoint_a = self.controller.get_interface_by_id(id_a)
600 1
        endpoint_b = self.controller.get_interface_by_id(id_b)
601
602 1
        link = Link(endpoint_a, endpoint_b)
603 1
        if 'metadata' in link_dict:
604
            link.extend_metadata(link_dict.get('metadata'))
605
606 1
        s_vlan = link.get_metadata('s_vlan')
607 1
        if s_vlan:
608
            tag = TAG.from_dict(s_vlan)
609
            if tag is False:
610
                error_msg = f'Could not instantiate tag from dict {s_vlan}'
611
                raise ValueError(error_msg)
612
            link.update_metadata('s_vlan', tag)
613 1
        return link
614
615 1
    def _find_evc_by_schedule_id(self, schedule_id):
616
        """
617
        Find an EVC and CircuitSchedule based on schedule_id.
618
619
        :param schedule_id: Schedule ID
620
        :return: EVC and Schedule
621
        """
622 1
        circuits = self._get_circuits_buffer()
623 1
        found_schedule = None
624 1
        evc = None
625
626
        # pylint: disable=unused-variable
627 1
        for c_id, circuit in circuits.items():
628 1
            for schedule in circuit.circuit_scheduler:
629 1
                if schedule.id == schedule_id:
630 1
                    found_schedule = schedule
631 1
                    evc = circuit
632 1
                    break
633 1
            if found_schedule:
634 1
                break
635 1
        return evc, found_schedule
636
637 1
    def _get_circuits_buffer(self):
638
        """
639
        Return the circuit buffer.
640
641
        If the buffer is empty, try to load data from storehouse.
642
        """
643 1
        if not self.circuits:
644
            # Load storehouse circuits to buffer
645 1
            circuits = self.storehouse.get_data()
646 1
            for c_id, circuit in circuits.items():
647 1
                evc = self._evc_from_dict(circuit)
648 1
                self.circuits[c_id] = evc
649 1
        return self.circuits
650
651 1
    @staticmethod
652
    def json_from_request(caller):
653
        """Return a json from request.
654
655
        If it was not possible to get a json from the request, log, for debug,
656
        who was the caller and the error that ocurred, and raise an
657
        Exception.
658
        """
659 1
        try:
660 1
            json_data = request.get_json()
661
        except ValueError as exception:
662
            log.error(exception)
663
            log.debug(f'{caller} result {exception} 400')
664
            raise BadRequest(str(exception))
665
        except BadRequest:
666
            result = 'The request is not a valid JSON.'
667
            log.debug(f'{caller} result {result} 400')
668
            raise BadRequest(result)
669 1
        if json_data is None:
670
            result = 'Content-Type must be application/json'
671
            log.debug(f'{caller} result {result} 415')
672
            raise UnsupportedMediaType(result)
673
        return json_data
674