Passed
Pull Request — master (#255)
by
unknown
03:49
created

build.main.Main.on_link_up()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1.037

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
crap 1.037
rs 10
c 0
b 0
f 0
1
# pylint: disable=protected-access
2 1
"""Main module of kytos/mef_eline Kytos Network Application.
3
4
NApp to provision circuits from user request.
5
"""
6 1
import time
7 1
from threading import Lock
8
9 1
from flask import jsonify, request
10 1
from werkzeug.exceptions import (BadRequest, Conflict, Forbidden,
11
                                 MethodNotAllowed, NotFound,
12
                                 UnsupportedMediaType)
13
14 1
from kytos.core import KytosNApp, log, rest
15 1
from kytos.core.helpers import listen_to
16 1
from kytos.core.interface import TAG, UNI
17 1
from kytos.core.link import Link
18 1
from napps.kytos.mef_eline import controllers, settings
19 1
from napps.kytos.mef_eline.exceptions import InvalidPath
20 1
from napps.kytos.mef_eline.models import (EVC, DynamicPathManager, EVCDeploy,
21
                                          Path)
22 1
from napps.kytos.mef_eline.scheduler import CircuitSchedule, Scheduler
23 1
from napps.kytos.mef_eline.utils import emit_event, load_spec, validate
24
25
26
# pylint: disable=too-many-public-methods
27 1
class Main(KytosNApp):
28
    """Main class of amlight/mef_eline NApp.
29
30
    This class is the entry point for this napp.
31
    """
32
33 1
    spec = load_spec()
34
35 1
    def setup(self):
36
        """Replace the '__init__' method for the KytosNApp subclass.
37
38
        The setup method is automatically called by the controller when your
39
        application is loaded.
40
41
        So, if you have any setup routine, insert it here.
42
        """
43
        # object used to scheduler circuit events
44 1
        self.sched = Scheduler()
45
46
        # object to save and load circuits
47 1
        self.mongo_controller = self.get_eline_controller()
48 1
        self.mongo_controller.bootstrap_indexes()
49
50
        # set the controller that will manager the dynamic paths
51 1
        DynamicPathManager.set_controller(self.controller)
52
53
        # dictionary of EVCs created. It acts as a circuit buffer.
54
        # Every create/update/delete must be synced to mongodb.
55 1
        self.circuits = {}
56
57 1
        self._lock = Lock()
58 1
        self.execute_as_loop(settings.DEPLOY_EVCS_INTERVAL)
59
60 1
        self.load_all_evcs()
61
62 1
    def get_evcs_by_svc_level(self) -> list:
63
        """Get circuits sorted by desc service level and asc creation_time.
64
65
        In the future, as more ops are offloaded it should be get from the DB.
66
        """
67 1
        return sorted(self.circuits.values(),
68
                      key=lambda x: (-x.service_level, x.creation_time))
69
70 1
    @staticmethod
71 1
    def get_eline_controller():
72
        """Return the ELineController instance."""
73
        return controllers.ELineController()
74
75 1
    def execute(self):
76
        """Execute once when the napp is running."""
77 1
        if self._lock.locked():
78 1
            return
79 1
        log.debug("Starting consistency routine")
80 1
        with self._lock:
81 1
            self.execute_consistency()
82 1
        log.debug("Finished consistency routine")
83
84 1
    def execute_consistency(self):
85
        """Execute consistency routine."""
86 1
        circuits_to_check = {}
87 1
        stored_circuits = self.mongo_controller.get_circuits()['circuits']
88 1
        for circuit in self.get_evcs_by_svc_level():
89 1
            stored_circuits.pop(circuit.id, None)
90 1
            if (
91
                circuit.is_enabled()
92
                and not circuit.is_active()
93
                and not circuit.lock.locked()
94
                and not circuit.has_recent_removed_flow()
95
                and not circuit.is_recent_updated()
96
            ):
97 1
                circuits_to_check[circuit.id] = circuit
98 1
        circuits_checked = EVCDeploy.check_list_traces(circuits_to_check)
99 1
        for circuit_id, circuit in circuits_to_check.items():
100 1
            is_checked = circuits_checked.get(circuit_id)
101 1
            if is_checked:
102 1
                circuit.execution_rounds = 0
103 1
                log.info(f"{circuit} enabled but inactive - activating")
104 1
                with circuit.lock:
105 1
                    circuit.activate()
106 1
                    circuit.sync()
107
            else:
108 1
                circuit.execution_rounds += 1
109 1
                if circuit.execution_rounds > settings.WAIT_FOR_OLD_PATH:
110 1
                    log.info(f"{circuit} enabled but inactive - redeploy")
111 1
                    with circuit.lock:
112 1
                        circuit.deploy()
113 1
        for circuit_id in stored_circuits:
114 1
            log.info(f"EVC found in mongodb but unloaded {circuit_id}")
115 1
            self._load_evc(stored_circuits[circuit_id])
116
117 1
    def shutdown(self):
118
        """Execute when your napp is unloaded.
119
120
        If you have some cleanup procedure, insert it here.
121
        """
122
123 1
    @rest("/v2/evc/", methods=["GET"])
124 1
    def list_circuits(self):
125
        """Endpoint to return circuits stored.
126
127
        archive query arg if defined (not null) will be filtered
128
        accordingly, by default only non archived evcs will be listed
129
        """
130 1
        log.debug("list_circuits /v2/evc")
131 1
        archived = request.args.get("archived", "false").lower()
132 1
        archived_to_optional = {"null": None, "true": True, "false": False}
133 1
        archived = archived_to_optional.get(archived, False)
134 1
        circuits = self.mongo_controller.get_circuits(archived=archived)
135 1
        circuits = circuits['circuits']
136 1
        return jsonify(circuits), 200
137
138 1
    @rest("/v2/evc/<circuit_id>", methods=["GET"])
139 1
    def get_circuit(self, circuit_id):
140
        """Endpoint to return a circuit based on id."""
141 1
        log.debug("get_circuit /v2/evc/%s", circuit_id)
142 1
        circuit = self.mongo_controller.get_circuit(circuit_id)
143 1
        if not circuit:
144 1
            result = f"circuit_id {circuit_id} not found"
145 1
            log.debug("get_circuit result %s %s", result, 404)
146 1
            raise NotFound(result)
147 1
        status = 200
148 1
        log.debug("get_circuit result %s %s", circuit, status)
149 1
        return jsonify(circuit), status
150
151 1
    @rest("/v2/evc/", methods=["POST"])
152 1
    @validate(spec)
153 1
    def create_circuit(self, data):
154
        """Try to create a new circuit.
155
156
        Firstly, for EVPL: E-Line NApp verifies if UNI_A's requested C-VID and
157
        UNI_Z's requested C-VID are available from the interfaces' pools. This
158
        is checked when creating the UNI object.
159
160
        Then, E-Line NApp requests a primary and a backup path to the
161
        Pathfinder NApp using the attributes primary_links and backup_links
162
        submitted via REST
163
164
        # For each link composing paths in #3:
165
        #  - E-Line NApp requests a S-VID available from the link VLAN pool.
166
        #  - Using the S-VID obtained, generate abstract flow entries to be
167
        #    sent to FlowManager
168
169
        Push abstract flow entries to FlowManager and FlowManager pushes
170
        OpenFlow entries to datapaths
171
172
        E-Line NApp generates an event to notify all Kytos NApps of a new EVC
173
        creation
174
175
        Finnaly, notify user of the status of its request.
176
        """
177
        # Try to create the circuit object
178 1
        log.debug("create_circuit /v2/evc/")
179
180 1
        try:
181 1
            evc = self._evc_from_dict(data)
182 1
        except ValueError as exception:
183 1
            log.debug("create_circuit result %s %s", exception, 400)
184 1
            raise BadRequest(str(exception)) from BadRequest
185
186 1
        if evc.primary_path:
187
            try:
188
                evc.primary_path.is_valid(
189
                    evc.uni_a.interface.switch,
190
                    evc.uni_z.interface.switch,
191
                    bool(evc.circuit_scheduler),
192
                )
193
            except InvalidPath as exception:
194
                raise BadRequest(
195
                    f"primary_path is not valid: {exception}"
196
                ) from exception
197 1
        if evc.backup_path:
198
            try:
199
                evc.backup_path.is_valid(
200
                    evc.uni_a.interface.switch,
201
                    evc.uni_z.interface.switch,
202
                    bool(evc.circuit_scheduler),
203
                )
204
            except InvalidPath as exception:
205
                raise BadRequest(
206
                    f"backup_path is not valid: {exception}"
207
                ) from exception
208
209
        # verify duplicated evc
210 1
        if self._is_duplicated_evc(evc):
211 1
            result = "The EVC already exists."
212 1
            log.debug("create_circuit result %s %s", result, 409)
213 1
            raise Conflict(result)
214
215 1
        try:
216 1
            evc._validate_has_primary_or_dynamic()
217 1
        except ValueError as exception:
218 1
            raise BadRequest(str(exception)) from exception
219
220
        # store circuit in dictionary
221 1
        self.circuits[evc.id] = evc
222
223
        # save circuit
224 1
        evc.sync()
225
226
        # Schedule the circuit deploy
227 1
        self.sched.add(evc)
228
229
        # Circuit has no schedule, deploy now
230 1
        if not evc.circuit_scheduler:
231 1
            with evc.lock:
232 1
                evc.deploy()
233
234
        # Notify users
235 1
        result = {"circuit_id": evc.id}
236 1
        status = 201
237 1
        log.debug("create_circuit result %s %s", result, status)
238 1
        emit_event(self.controller, _name="created", **{
239
            "id": evc.id,
240
            "name": evc.name,
241
            "metadata": evc.metadata,
242
            "active": evc._active,
243
            "enabled": evc._enabled,
244
            "uni_a": evc.uni_a,
245
            "uni_z": evc.uni_z
246
        })
247 1
        return jsonify(result), status
248
249 1
    @listen_to('kytos/flow_manager.flow.removed')
250 1
    def on_flow_delete(self, event):
251
        """Capture delete messages to keep track when flows got removed."""
252
        self.handle_flow_delete(event)
253
254 1
    def handle_flow_delete(self, event):
255
        """Keep track when the EVC got flows removed by deriving its cookie."""
256 1
        flow = event.content["flow"]
257 1
        evc = self.circuits.get(EVC.get_id_from_cookie(flow.cookie))
258 1
        if evc:
259 1
            log.debug("Flow removed in EVC %s", evc.id)
260 1
            evc.set_flow_removed_at()
261
262 1
    @rest("/v2/evc/<circuit_id>", methods=["PATCH"])
263 1
    def update(self, circuit_id):
264
        """Update a circuit based on payload.
265
266
        The EVC required attributes (name, uni_a, uni_z) can't be updated.
267
        """
268 1
        log.debug("update /v2/evc/%s", circuit_id)
269 1
        try:
270 1
            evc = self.circuits[circuit_id]
271 1
        except KeyError:
272 1
            result = f"circuit_id {circuit_id} not found"
273 1
            log.debug("update result %s %s", result, 404)
274 1
            raise NotFound(result) from NotFound
275
276 1
        if evc.archived:
277 1
            result = "Can't update archived EVC"
278 1
            log.debug("update result %s %s", result, 405)
279 1
            raise MethodNotAllowed(["GET"], result)
280
281 1
        try:
282 1
            data = request.get_json()
283 1
        except BadRequest:
284 1
            result = "The request body is not a well-formed JSON."
285 1
            log.debug("update result %s %s", result, 400)
286 1
            raise BadRequest(result) from BadRequest
287 1
        if data is None:
288 1
            result = "The request body mimetype is not application/json."
289 1
            log.debug("update result %s %s", result, 415)
290 1
            raise UnsupportedMediaType(result) from UnsupportedMediaType
291
292 1
        try:
293 1
            enable, redeploy = evc.update(
294
                **self._evc_dict_with_instances(data)
295
            )
296 1
        except ValueError as exception:
297 1
            log.error(exception)
298 1
            log.debug("update result %s %s", exception, 400)
299 1
            raise BadRequest(str(exception)) from BadRequest
300
301 1
        if evc.is_active():
302
            if enable is False:  # disable if active
303
                with evc.lock:
304
                    evc.remove()
305
            elif redeploy is not None:  # redeploy if active
306
                with evc.lock:
307
                    evc.remove()
308
                    evc.deploy()
309
        else:
310 1
            if enable is True:  # enable if inactive
311 1
                with evc.lock:
312 1
                    evc.deploy()
313 1
        result = {evc.id: evc.as_dict()}
314 1
        status = 200
315
316 1
        log.debug("update result %s %s", result, status)
317 1
        emit_event(self.controller, "updated", evc_id=evc.id, data=data)
318 1
        return jsonify(result), status
319
320 1
    @rest("/v2/evc/<circuit_id>", methods=["DELETE"])
321 1
    def delete_circuit(self, circuit_id):
322
        """Remove a circuit.
323
324
        First, the flows are removed from the switches, and then the EVC is
325
        disabled.
326
        """
327 1
        log.debug("delete_circuit /v2/evc/%s", circuit_id)
328 1
        try:
329 1
            evc = self.circuits[circuit_id]
330 1
        except KeyError:
331 1
            result = f"circuit_id {circuit_id} not found"
332 1
            log.debug("delete_circuit result %s %s", result, 404)
333 1
            raise NotFound(result) from NotFound
334
335 1
        if evc.archived:
336 1
            result = f"Circuit {circuit_id} already removed"
337 1
            log.debug("delete_circuit result %s %s", result, 404)
338 1
            raise NotFound(result) from NotFound
339
340 1
        log.info("Removing %s", evc)
341 1
        with evc.lock:
342 1
            evc.remove_current_flows()
343 1
            evc.remove_failover_flows(sync=False)
344 1
            evc.deactivate()
345 1
            evc.disable()
346 1
            self.sched.remove(evc)
347 1
            evc.archive()
348 1
            evc.sync()
349 1
        log.info("EVC removed. %s", evc)
350 1
        result = {"response": f"Circuit {circuit_id} removed"}
351 1
        status = 200
352
353 1
        log.debug("delete_circuit result %s %s", result, status)
354 1
        emit_event(self.controller, "deleted", evc_id=evc.id)
355 1
        return jsonify(result), status
356
357 1
    @rest("v2/evc/<circuit_id>/metadata", methods=["GET"])
358 1
    def get_metadata(self, circuit_id):
359
        """Get metadata from an EVC."""
360 1
        try:
361 1
            return (
362
                jsonify({"metadata": self.circuits[circuit_id].metadata}),
363
                200,
364
            )
365
        except KeyError as error:
366
            raise NotFound(f"circuit_id {circuit_id} not found.") from error
367
368 1
    @rest("v2/evc/<circuit_id>/metadata", methods=["POST"])
369 1
    def add_metadata(self, circuit_id):
370
        """Add metadata to an EVC."""
371 1
        try:
372 1
            metadata = request.get_json()
373 1
            content_type = request.content_type
374 1
        except BadRequest as error:
375 1
            result = "The request body is not a well-formed JSON."
376 1
            raise BadRequest(result) from error
377 1
        if content_type is None:
378 1
            result = "The request body is empty."
379 1
            raise BadRequest(result)
380 1
        if metadata is None:
381 1
            if content_type != "application/json":
382 1
                result = (
383
                    "The content type must be application/json "
384
                    f"(received {content_type})."
385
                )
386
            else:
387
                result = "Metadata is empty."
388 1
            raise UnsupportedMediaType(result)
389
390 1
        try:
391 1
            evc = self.circuits[circuit_id]
392 1
        except KeyError as error:
393 1
            raise NotFound(f"circuit_id {circuit_id} not found.") from error
394
395 1
        evc.extend_metadata(metadata)
396 1
        evc.sync()
397 1
        return jsonify("Operation successful"), 201
398
399 1
    @rest("v2/evc/<circuit_id>/metadata/<key>", methods=["DELETE"])
400 1
    def delete_metadata(self, circuit_id, key):
401
        """Delete metadata from an EVC."""
402 1
        try:
403 1
            evc = self.circuits[circuit_id]
404 1
        except KeyError as error:
405 1
            raise NotFound(f"circuit_id {circuit_id} not found.") from error
406
407 1
        evc.remove_metadata(key)
408 1
        evc.sync()
409 1
        return jsonify("Operation successful"), 200
410
411 1
    @rest("/v2/evc/<circuit_id>/redeploy", methods=["PATCH"])
412 1
    def redeploy(self, circuit_id):
413
        """Endpoint to force the redeployment of an EVC."""
414 1
        log.debug("redeploy /v2/evc/%s/redeploy", circuit_id)
415 1
        try:
416 1
            evc = self.circuits[circuit_id]
417 1
        except KeyError:
418 1
            result = f"circuit_id {circuit_id} not found"
419 1
            raise NotFound(result) from NotFound
420 1
        if evc.is_enabled():
421 1
            with evc.lock:
422 1
                evc.remove_current_flows()
423 1
                evc.deploy()
424 1
            result = {"response": f"Circuit {circuit_id} redeploy received."}
425 1
            status = 202
426
        else:
427 1
            result = {"response": f"Circuit {circuit_id} is disabled."}
428 1
            status = 409
429
430 1
        return jsonify(result), status
431
432 1
    @rest("/v2/evc/schedule", methods=["GET"])
433 1
    def list_schedules(self):
434
        """Endpoint to return all schedules stored for all circuits.
435
436
        Return a JSON with the following template:
437
        [{"schedule_id": <schedule_id>,
438
         "circuit_id": <circuit_id>,
439
         "schedule": <schedule object>}]
440
        """
441 1
        log.debug("list_schedules /v2/evc/schedule")
442 1
        circuits = self.mongo_controller.get_circuits()['circuits'].values()
443 1
        if not circuits:
444 1
            result = {}
445 1
            status = 200
446 1
            return jsonify(result), status
447
448 1
        result = []
449 1
        status = 200
450 1
        for circuit in circuits:
451 1
            circuit_scheduler = circuit.get("circuit_scheduler")
452 1
            if circuit_scheduler:
453 1
                for scheduler in circuit_scheduler:
454 1
                    value = {
455
                        "schedule_id": scheduler.get("id"),
456
                        "circuit_id": circuit.get("id"),
457
                        "schedule": scheduler,
458
                    }
459 1
                    result.append(value)
460
461 1
        log.debug("list_schedules result %s %s", result, status)
462 1
        return jsonify(result), status
463
464 1
    @rest("/v2/evc/schedule/", methods=["POST"])
465 1
    def create_schedule(self):
466
        """
467
        Create a new schedule for a given circuit.
468
469
        This service do no check if there are conflicts with another schedule.
470
        Payload example:
471
            {
472
              "circuit_id":"aa:bb:cc",
473
              "schedule": {
474
                "date": "2019-08-07T14:52:10.967Z",
475
                "interval": "string",
476
                "frequency": "1 * * * *",
477
                "action": "create"
478
              }
479
            }
480
        """
481 1
        log.debug("create_schedule /v2/evc/schedule/")
482
483 1
        json_data = self._json_from_request("create_schedule")
484 1
        try:
485 1
            circuit_id = json_data["circuit_id"]
486 1
        except TypeError:
487 1
            result = "The payload should have a dictionary."
488 1
            log.debug("create_schedule result %s %s", result, 400)
489 1
            raise BadRequest(result) from BadRequest
490 1
        except KeyError:
491 1
            result = "Missing circuit_id."
492 1
            log.debug("create_schedule result %s %s", result, 400)
493 1
            raise BadRequest(result) from BadRequest
494
495 1
        try:
496 1
            schedule_data = json_data["schedule"]
497 1
        except KeyError:
498 1
            result = "Missing schedule data."
499 1
            log.debug("create_schedule result %s %s", result, 400)
500 1
            raise BadRequest(result) from BadRequest
501
502
        # Get EVC from circuits buffer
503 1
        circuits = self._get_circuits_buffer()
504
505
        # get the circuit
506 1
        evc = circuits.get(circuit_id)
507
508
        # get the circuit
509 1
        if not evc:
510 1
            result = f"circuit_id {circuit_id} not found"
511 1
            log.debug("create_schedule result %s %s", result, 404)
512 1
            raise NotFound(result) from NotFound
513
        # Can not modify circuits deleted and archived
514 1
        if evc.archived:
515 1
            result = f"Circuit {circuit_id} is archived. Update is forbidden."
516 1
            log.debug("create_schedule result %s %s", result, 403)
517 1
            raise Forbidden(result) from Forbidden
518
519
        # new schedule from dict
520 1
        new_schedule = CircuitSchedule.from_dict(schedule_data)
521
522
        # If there is no schedule, create the list
523 1
        if not evc.circuit_scheduler:
524 1
            evc.circuit_scheduler = []
525
526
        # Add the new schedule
527 1
        evc.circuit_scheduler.append(new_schedule)
528
529
        # Add schedule job
530 1
        self.sched.add_circuit_job(evc, new_schedule)
531
532
        # save circuit to mongodb
533 1
        evc.sync()
534
535 1
        result = new_schedule.as_dict()
536 1
        status = 201
537
538 1
        log.debug("create_schedule result %s %s", result, status)
539 1
        return jsonify(result), status
540
541 1
    @rest("/v2/evc/schedule/<schedule_id>", methods=["PATCH"])
542 1
    def update_schedule(self, schedule_id):
543
        """Update a schedule.
544
545
        Change all attributes from the given schedule from a EVC circuit.
546
        The schedule ID is preserved as default.
547
        Payload example:
548
            {
549
              "date": "2019-08-07T14:52:10.967Z",
550
              "interval": "string",
551
              "frequency": "1 * * *",
552
              "action": "create"
553
            }
554
        """
555 1
        log.debug("update_schedule /v2/evc/schedule/%s", schedule_id)
556
557
        # Try to find a circuit schedule
558 1
        evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
559
560
        # Can not modify circuits deleted and archived
561 1
        if not found_schedule:
562 1
            result = f"schedule_id {schedule_id} not found"
563 1
            log.debug("update_schedule result %s %s", result, 404)
564 1
            raise NotFound(result) from NotFound
565 1
        if evc.archived:
566 1
            result = f"Circuit {evc.id} is archived. Update is forbidden."
567 1
            log.debug("update_schedule result %s %s", result, 403)
568 1
            raise Forbidden(result) from Forbidden
569
570 1
        data = self._json_from_request("update_schedule")
571
572 1
        new_schedule = CircuitSchedule.from_dict(data)
573 1
        new_schedule.id = found_schedule.id
574
        # Remove the old schedule
575 1
        evc.circuit_scheduler.remove(found_schedule)
576
        # Append the modified schedule
577 1
        evc.circuit_scheduler.append(new_schedule)
578
579
        # Cancel all schedule jobs
580 1
        self.sched.cancel_job(found_schedule.id)
581
        # Add the new circuit schedule
582 1
        self.sched.add_circuit_job(evc, new_schedule)
583
        # Save EVC to mongodb
584 1
        evc.sync()
585
586 1
        result = new_schedule.as_dict()
587 1
        status = 200
588
589 1
        log.debug("update_schedule result %s %s", result, status)
590 1
        return jsonify(result), status
591
592 1
    @rest("/v2/evc/schedule/<schedule_id>", methods=["DELETE"])
593 1
    def delete_schedule(self, schedule_id):
594
        """Remove a circuit schedule.
595
596
        Remove the Schedule from EVC.
597
        Remove the Schedule from cron job.
598
        Save the EVC to the Storehouse.
599
        """
600 1
        log.debug("delete_schedule /v2/evc/schedule/%s", schedule_id)
601 1
        evc, found_schedule = self._find_evc_by_schedule_id(schedule_id)
602
603
        # Can not modify circuits deleted and archived
604 1
        if not found_schedule:
605 1
            result = f"schedule_id {schedule_id} not found"
606 1
            log.debug("delete_schedule result %s %s", result, 404)
607 1
            raise NotFound(result)
608
609 1
        if evc.archived:
610 1
            result = f"Circuit {evc.id} is archived. Update is forbidden."
611 1
            log.debug("delete_schedule result %s %s", result, 403)
612 1
            raise Forbidden(result)
613
614
        # Remove the old schedule
615 1
        evc.circuit_scheduler.remove(found_schedule)
616
617
        # Cancel all schedule jobs
618 1
        self.sched.cancel_job(found_schedule.id)
619
        # Save EVC to mongodb
620 1
        evc.sync()
621
622 1
        result = "Schedule removed"
623 1
        status = 200
624
625 1
        log.debug("delete_schedule result %s %s", result, status)
626 1
        return jsonify(result), status
627
628 1
    def _is_duplicated_evc(self, evc):
629
        """Verify if the circuit given is duplicated with the stored evcs.
630
631
        Args:
632
            evc (EVC): circuit to be analysed.
633
634
        Returns:
635
            boolean: True if the circuit is duplicated, otherwise False.
636
637
        """
638 1
        for circuit in tuple(self.circuits.values()):
639 1
            if not circuit.archived and circuit.shares_uni(evc):
640 1
                return True
641 1
        return False
642
643 1
    @listen_to("kytos/topology.link_up")
644 1
    def on_link_up(self, event):
645
        """Change circuit when link is up or end_maintenance."""
646
        self.handle_link_up(event)
647
648 1
    def handle_link_up(self, event):
649
        """Change circuit when link is up or end_maintenance."""
650 1
        log.info("Event handle_link_up %s", event.content["link"])
651 1
        for evc in self.get_evcs_by_svc_level():
652 1
            if evc.is_enabled() and not evc.archived:
653 1
                with evc.lock:
654 1
                    evc.handle_link_up(event.content["link"])
655
656 1
    @listen_to("kytos/topology.link_down")
657 1
    def on_link_down(self, event):
658
        """Change circuit when link is down or under_mantenance."""
659
        self.handle_link_down(event)
660
661 1
    def handle_link_down(self, event):
662
        """Change circuit when link is down or under_mantenance."""
663 1
        link = event.content["link"]
664 1
        log.info("Event handle_link_down %s", link)
665 1
        switch_flows = {}
666 1
        evcs_with_failover = []
667 1
        evcs_normal = []
668 1
        check_failover = []
669 1
        for evc in self.get_evcs_by_svc_level():
670 1
            if evc.is_affected_by_link(link):
671
                # if there is no failover path, handles link down the
672
                # tradditional way
673 1
                if (
674
                    not getattr(evc, 'failover_path', None) or
675
                    evc.is_failover_path_affected_by_link(link)
676
                ):
677 1
                    evcs_normal.append(evc)
678 1
                    continue
679 1
                for dpid, flows in evc.get_failover_flows().items():
680 1
                    switch_flows.setdefault(dpid, [])
681 1
                    switch_flows[dpid].extend(flows)
682 1
                evcs_with_failover.append(evc)
683
            else:
684 1
                check_failover.append(evc)
685
686 1
        offset = 0
687 1
        while switch_flows:
688 1
            offset = (offset + settings.BATCH_SIZE) or None
689 1
            switches = list(switch_flows.keys())
690 1
            for dpid in switches:
691 1
                emit_event(
692
                    self.controller,
693
                    context="kytos.flow_manager",
694
                    _name="flows.install",
695
                    dpid=dpid,
696
                    flow_dict={"flows": switch_flows[dpid][:offset]},
697
                )
698 1
                if offset is None or offset >= len(switch_flows[dpid]):
699 1
                    del switch_flows[dpid]
700 1
                    continue
701 1
                switch_flows[dpid] = switch_flows[dpid][offset:]
702 1
            time.sleep(settings.BATCH_INTERVAL)
703
704 1
        for evc in evcs_with_failover:
705 1
            with evc.lock:
706 1
                old_path = evc.current_path
707 1
                evc.current_path = evc.failover_path
708 1
                evc.failover_path = old_path
709 1
                evc.sync()
710 1
            emit_event(self.controller, "redeployed_link_down", evc_id=evc.id)
711 1
            log.info(
712
                f"{evc} redeployed with failover due to link down {link.id}"
713
            )
714
715 1
        for evc in evcs_normal:
716 1
            emit_event(
717
                self.controller,
718
                "evc_affected_by_link_down",
719
                evc_id=evc.id,
720
                link_id=link.id,
721
            )
722
723
        # After handling the hot path, check if new failover paths are needed.
724
        # Note that EVCs affected by link down will generate a KytosEvent for
725
        # deployed|redeployed, which will trigger the failover path setup.
726
        # Thus, we just need to further check the check_failover list
727 1
        for evc in check_failover:
728 1
            if evc.is_failover_path_affected_by_link(link):
729 1
                evc.setup_failover_path()
730
731 1
    @listen_to("kytos/mef_eline.evc_affected_by_link_down")
732 1
    def on_evc_affected_by_link_down(self, event):
733
        """Change circuit when link is down or under_mantenance."""
734
        self.handle_evc_affected_by_link_down(event)
735
736 1
    def handle_evc_affected_by_link_down(self, event):
737
        """Change circuit when link is down or under_mantenance."""
738 1
        evc = self.circuits.get(event.content["evc_id"])
739 1
        link_id = event.content['link_id']
740 1
        if not evc:
741 1
            return
742 1
        with evc.lock:
743 1
            result = evc.handle_link_down()
744 1
        event_name = "error_redeploy_link_down"
745 1
        if result:
746 1
            log.info(f"{evc} redeployed due to link down {link_id}")
747 1
            event_name = "redeployed_link_down"
748 1
        emit_event(self.controller, event_name, evc_id=evc.id)
749
750 1
    @listen_to("kytos/mef_eline.(redeployed_link_(up|down)|deployed)")
751 1
    def on_evc_deployed(self, event):
752
        """Handle EVC deployed|redeployed_link_down."""
753
        self.handle_evc_deployed(event)
754
755 1
    def handle_evc_deployed(self, event):
756
        """Setup failover path on evc deployed."""
757 1
        evc = self.circuits.get(event.content["evc_id"])
758 1
        if not evc:
759 1
            return
760 1
        with evc.lock:
761 1
            evc.setup_failover_path()
762
763 1
    @listen_to("kytos/topology.topology_loaded")
764 1
    def on_topology_loaded(self, event):  # pylint: disable=unused-argument
765
        """Load EVCs once the topology is available."""
766
        self.load_all_evcs()
767
768 1
    def load_all_evcs(self):
769
        """Try to load all EVCs on startup."""
770 1
        circuits = self.mongo_controller.get_circuits()['circuits'].items()
771 1
        for circuit_id, circuit in circuits:
772 1
            if circuit_id not in self.circuits:
773 1
                self._load_evc(circuit)
774
775 1
    def _load_evc(self, circuit_dict):
776
        """Load one EVC from mongodb to memory."""
777 1
        try:
778 1
            evc = self._evc_from_dict(circuit_dict)
779 1
        except ValueError as exception:
780 1
            log.error(
781
                f"Could not load EVC: dict={circuit_dict} error={exception}"
782
            )
783 1
            return None
784
785 1
        if evc.archived:
786 1
            return None
787 1
        evc.deactivate()
788 1
        evc.sync()
789 1
        self.circuits.setdefault(evc.id, evc)
790 1
        self.sched.add(evc)
791 1
        return evc
792
793 1
    @listen_to("kytos/flow_manager.flow.error")
794 1
    def on_flow_mod_error(self, event):
795
        """Handle flow mod errors related to an EVC."""
796
        self.handle_flow_mod_error(event)
797
798 1
    def handle_flow_mod_error(self, event):
799
        """Handle flow mod errors related to an EVC."""
800 1
        flow = event.content["flow"]
801 1
        command = event.content.get("error_command")
802 1
        if command != "add":
803
            return
804 1
        evc = self.circuits.get(EVC.get_id_from_cookie(flow.cookie))
805 1
        if evc:
806 1
            evc.remove_current_flows()
807
808 1
    def _evc_dict_with_instances(self, evc_dict):
809
        """Convert some dict values to instance of EVC classes.
810
811
        This method will convert: [UNI, Link]
812
        """
813 1
        data = evc_dict.copy()  # Do not modify the original dict
814 1
        for attribute, value in data.items():
815
            # Get multiple attributes.
816
            # Ex: uni_a, uni_z
817 1
            if "uni" in attribute:
818 1
                try:
819 1
                    data[attribute] = self._uni_from_dict(value)
820 1
                except ValueError as exception:
821 1
                    result = "Error creating UNI: Invalid value"
822 1
                    raise ValueError(result) from exception
823
824 1
            if attribute == "circuit_scheduler":
825 1
                data[attribute] = []
826 1
                for schedule in value:
827 1
                    data[attribute].append(CircuitSchedule.from_dict(schedule))
828
829
            # Get multiple attributes.
830
            # Ex: primary_links,
831
            #     backup_links,
832
            #     current_links_cache,
833
            #     primary_links_cache,
834
            #     backup_links_cache
835 1
            if "links" in attribute:
836 1
                data[attribute] = [
837
                    self._link_from_dict(link) for link in value
838
                ]
839
840
            # Ex: current_path,
841
            #     primary_path,
842
            #     backup_path
843 1
            if "path" in attribute and attribute != "dynamic_backup_path":
844 1
                data[attribute] = Path(
845
                    [self._link_from_dict(link) for link in value]
846
                )
847
848 1
        return data
849
850 1
    def _evc_from_dict(self, evc_dict):
851 1
        data = self._evc_dict_with_instances(evc_dict)
852 1
        return EVC(self.controller, **data)
853
854 1
    def _uni_from_dict(self, uni_dict):
855
        """Return a UNI object from python dict."""
856 1
        if uni_dict is None:
857 1
            return False
858
859 1
        interface_id = uni_dict.get("interface_id")
860 1
        interface = self.controller.get_interface_by_id(interface_id)
861 1
        if interface is None:
862 1
            result = (
863
                "Error creating UNI:"
864
                + f"Could not instantiate interface {interface_id}"
865
            )
866 1
            raise ValueError(result) from ValueError
867
868 1
        tag_dict = uni_dict.get("tag", None)
869 1
        if tag_dict:
870 1
            tag = TAG.from_dict(tag_dict)
871
        else:
872 1
            tag = None
873 1
        uni = UNI(interface, tag)
874
875 1
        return uni
876
877 1
    def _link_from_dict(self, link_dict):
878
        """Return a Link object from python dict."""
879 1
        id_a = link_dict.get("endpoint_a").get("id")
880 1
        id_b = link_dict.get("endpoint_b").get("id")
881
882 1
        endpoint_a = self.controller.get_interface_by_id(id_a)
883 1
        endpoint_b = self.controller.get_interface_by_id(id_b)
884 1
        if not endpoint_a:
885 1
            error_msg = f"Could not get interface endpoint_a id {id_a}"
886 1
            raise ValueError(error_msg)
887 1
        if not endpoint_b:
888
            error_msg = f"Could not get interface endpoint_b id {id_b}"
889
            raise ValueError(error_msg)
890
891 1
        link = Link(endpoint_a, endpoint_b)
892 1
        if "metadata" in link_dict:
893 1
            link.extend_metadata(link_dict.get("metadata"))
894
895 1
        s_vlan = link.get_metadata("s_vlan")
896 1
        if s_vlan:
897 1
            tag = TAG.from_dict(s_vlan)
898 1
            if tag is False:
899
                error_msg = f"Could not instantiate tag from dict {s_vlan}"
900
                raise ValueError(error_msg)
901 1
            link.update_metadata("s_vlan", tag)
902 1
        return link
903
904 1
    def _find_evc_by_schedule_id(self, schedule_id):
905
        """
906
        Find an EVC and CircuitSchedule based on schedule_id.
907
908
        :param schedule_id: Schedule ID
909
        :return: EVC and Schedule
910
        """
911 1
        circuits = self._get_circuits_buffer()
912 1
        found_schedule = None
913 1
        evc = None
914
915
        # pylint: disable=unused-variable
916 1
        for c_id, circuit in circuits.items():
917 1
            for schedule in circuit.circuit_scheduler:
918 1
                if schedule.id == schedule_id:
919 1
                    found_schedule = schedule
920 1
                    evc = circuit
921 1
                    break
922 1
            if found_schedule:
923 1
                break
924 1
        return evc, found_schedule
925
926 1
    def _get_circuits_buffer(self):
927
        """
928
        Return the circuit buffer.
929
930
        If the buffer is empty, try to load data from mongodb.
931
        """
932 1
        if not self.circuits:
933
            # Load circuits from mongodb to buffer
934 1
            circuits = self.mongo_controller.get_circuits()['circuits']
935 1
            for c_id, circuit in circuits.items():
936 1
                evc = self._evc_from_dict(circuit)
937 1
                self.circuits[c_id] = evc
938 1
        return self.circuits
939
940 1
    @staticmethod
941 1
    def _json_from_request(caller):
942
        """Return a json from request.
943
944
        If it was not possible to get a json from the request, log, for debug,
945
        who was the caller and the error that ocurred, and raise an
946
        Exception.
947
        """
948 1
        try:
949 1
            json_data = request.get_json()
950 1
        except ValueError as exception:
951
            log.error(exception)
952
            log.debug(f"{caller} result {exception} 400")
953
            raise BadRequest(str(exception)) from BadRequest
954 1
        except BadRequest:
955 1
            result = "The request is not a valid JSON."
956 1
            log.debug(f"{caller} result {result} 400")
957 1
            raise BadRequest(result) from BadRequest
958 1
        if json_data is None:
959 1
            result = "Content-Type must be application/json"
960 1
            log.debug(f"{caller} result {result} 415")
961 1
            raise UnsupportedMediaType(result)
962
        return json_data
963