Passed
Push — master ( 728489...ff5136 )
by Vinicius
05:39 queued 03:04
created

build.models.evc.EVCDeploy.is_using_backup_path()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
ccs 2
cts 2
cp 1
crap 1
1
"""Classes used in the main application."""  # pylint: disable=too-many-lines
2 1
from collections import OrderedDict
3 1
from datetime import datetime
4 1
from operator import eq, ne
5 1
from threading import Lock
6 1
from typing import Union
7 1
from uuid import uuid4
8
9 1
import requests
10 1
from glom import glom
11 1
from requests.exceptions import Timeout
12
13 1
from kytos.core import log
14 1
from kytos.core.common import EntityStatus, GenericEntity
15 1
from kytos.core.exceptions import KytosNoTagAvailableError
16 1
from kytos.core.helpers import get_time, now
17 1
from kytos.core.interface import UNI, Interface
18 1
from kytos.core.link import Link
19 1
from napps.kytos.mef_eline import controllers, settings
20 1
from napps.kytos.mef_eline.exceptions import FlowModException, InvalidPath
21 1
from napps.kytos.mef_eline.utils import (check_disabled_component,
22
                                         compare_endpoint_trace,
23
                                         compare_uni_out_trace, emit_event,
24
                                         map_dl_vlan, map_evc_event_content,
25
                                         notify_link_available_tags)
26
27 1
from .path import DynamicPathManager, Path
28
29
30 1
class EVCBase(GenericEntity):
31
    """Class to represent a circuit."""
32
33 1
    read_only_attributes = [
34
        "creation_time",
35
        "active",
36
        "current_path",
37
        "failover_path",
38
        "_id",
39
        "archived",
40
    ]
41 1
    attributes_requiring_redeploy = [
42
        "primary_path",
43
        "backup_path",
44
        "dynamic_backup_path",
45
        "queue_id",
46
        "sb_priority",
47
        "primary_constraints",
48
        "secondary_constraints",
49
        "uni_a",
50
        "uni_z",
51
    ]
52 1
    required_attributes = ["name", "uni_a", "uni_z"]
53
54 1
    def __init__(self, controller, **kwargs):
55
        """Create an EVC instance with the provided parameters.
56
57
        Args:
58
            id(str): EVC identifier. Whether it's None an ID will be genereted.
59
                     Only the first 14 bytes passed will be used.
60
            name: represents an EVC name.(Required)
61
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
62
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
63
            start_date(datetime|str): Date when the EVC was registred.
64
                                      Default is now().
65
            end_date(datetime|str): Final date that the EVC will be fineshed.
66
                                    Default is None.
67
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
68
            primary_links(list): Primary links used by evc. Default is []
69
            backup_links(list): Backups links used by evc. Default is []
70
            current_path(list): Circuit being used at the moment if this is an
71
                                active circuit. Default is [].
72
            failover_path(list): Path being used to provide EVC protection via
73
                                failover during link failures. Default is [].
74
            primary_path(list): primary circuit offered to user IF one or more
75
                                links were provided. Default is [].
76
            backup_path(list): backup circuit offered to the user IF one or
77
                               more links were provided. Default is [].
78
            dynamic_backup_path(bool): Enable computer backup path dynamically.
79
                                       Dafault is False.
80
            creation_time(datetime|str): datetime when the circuit should be
81
                                         activated. default is now().
82
            enabled(Boolean): attribute to indicate the administrative state;
83
                              default is False.
84
            active(Boolean): attribute to indicate the operational state;
85
                             default is False.
86
            archived(Boolean): indicate the EVC has been deleted and is
87
                               archived; default is False.
88
            owner(str): The EVC owner. Default is None.
89
            sb_priority(int): Service level provided in the request.
90
                              Default is None.
91
            service_level(int): Service level provided. The higher the better.
92
                                Default is 0.
93
94
        Raises:
95
            ValueError: raised when object attributes are invalid.
96
97
        """
98 1
        self._validate(**kwargs)
99 1
        super().__init__()
100
101
        # required attributes
102 1
        self._id = kwargs.get("id", uuid4().hex)[:14]
103 1
        self.uni_a = kwargs.get("uni_a")
104 1
        self.uni_z = kwargs.get("uni_z")
105 1
        self.name = kwargs.get("name")
106
107
        # optional attributes
108 1
        self.start_date = get_time(kwargs.get("start_date")) or now()
109 1
        self.end_date = get_time(kwargs.get("end_date")) or None
110 1
        self.queue_id = kwargs.get("queue_id", None)
111
112 1
        self.bandwidth = kwargs.get("bandwidth", 0)
113 1
        self.primary_links = Path(kwargs.get("primary_links", []))
114 1
        self.backup_links = Path(kwargs.get("backup_links", []))
115 1
        self.current_path = Path(kwargs.get("current_path", []))
116 1
        self.failover_path = Path(kwargs.get("failover_path", []))
117 1
        self.primary_path = Path(kwargs.get("primary_path", []))
118 1
        self.backup_path = Path(kwargs.get("backup_path", []))
119 1
        self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False)
120 1
        self.primary_constraints = kwargs.get("primary_constraints", {})
121 1
        self.secondary_constraints = kwargs.get("secondary_constraints", {})
122 1
        self.creation_time = get_time(kwargs.get("creation_time")) or now()
123 1
        self.owner = kwargs.get("owner", None)
124 1
        self.sb_priority = kwargs.get("sb_priority", None) or kwargs.get(
125
            "priority", None
126
        )
127 1
        self.service_level = kwargs.get("service_level", 0)
128 1
        self.circuit_scheduler = kwargs.get("circuit_scheduler", [])
129 1
        self.flow_removed_at = get_time(kwargs.get("flow_removed_at")) or None
130 1
        self.updated_at = get_time(kwargs.get("updated_at")) or now()
131 1
        self.execution_rounds = kwargs.get("execution_rounds", 0)
132
133 1
        self.current_links_cache = set()
134 1
        self.primary_links_cache = set()
135 1
        self.backup_links_cache = set()
136
137 1
        self.lock = Lock()
138
139 1
        self.archived = kwargs.get("archived", False)
140
141 1
        self.metadata = kwargs.get("metadata", {})
142
143 1
        self._controller = controller
144 1
        self._mongo_controller = controllers.ELineController()
145
146 1
        if kwargs.get("active", False):
147 1
            self.activate()
148
        else:
149 1
            self.deactivate()
150
151 1
        if kwargs.get("enabled", False):
152 1
            self.enable()
153
        else:
154 1
            self.disable()
155
156
        # datetime of user request for a EVC (or datetime when object was
157
        # created)
158 1
        self.request_time = kwargs.get("request_time", now())
159
        # dict with the user original request (input)
160 1
        self._requested = kwargs
161
162
        # Special cases: No tag, any, untagged
163 1
        self.special_cases = {None, "4096/4096", 0}
164 1
        self.table_group = kwargs.get("table_group")
165
166 1
    def sync(self):
167
        """Sync this EVC in the MongoDB."""
168 1
        self.updated_at = now()
169 1
        self._mongo_controller.upsert_evc(self.as_dict())
170
171 1
    def update(self, **kwargs):
172
        """Update evc attributes.
173
174
        This method will raises an error trying to change the following
175
        attributes: [creation_time, active, current_path, failover_path,
176
        _id, archived]
177
        [name, uni_a and uni_z]
178
179
        Returns:
180
            the values for enable and a redeploy attribute, if exists and None
181
            otherwise
182
        Raises:
183
            ValueError: message with error detail.
184
185
        """
186 1
        enable, redeploy = (None, None)
187 1
        uni_a = kwargs.get("uni_a") or self.uni_a
188 1
        uni_z = kwargs.get("uni_z") or self.uni_z
189 1
        check_disabled_component(uni_a, uni_z)
190 1
        self._validate_has_primary_or_dynamic(
191
            primary_path=kwargs.get("primary_path"),
192
            dynamic_backup_path=kwargs.get("dynamic_backup_path"),
193
            uni_a=uni_a,
194
            uni_z=uni_z,
195
        )
196 1
        for attribute, value in kwargs.items():
197 1
            if attribute in self.read_only_attributes:
198 1
                raise ValueError(f"{attribute} can't be updated.")
199 1
            if not hasattr(self, attribute):
200 1
                raise ValueError(f'The attribute "{attribute}" is invalid.')
201 1
            if attribute in ("primary_path", "backup_path"):
202 1
                try:
203 1
                    value.is_valid(
204
                        uni_a.interface.switch, uni_z.interface.switch
205
                    )
206 1
                except InvalidPath as exception:
207 1
                    raise ValueError(  # pylint: disable=raise-missing-from
208
                        f"{attribute} is not a " f"valid path: {exception}"
209
                    )
210 1
        for attribute, value in kwargs.items():
211 1
            if attribute in ("enable", "enabled"):
212 1
                if value:
213 1
                    self.enable()
214
                else:
215 1
                    self.disable()
216 1
                enable = value
217
            else:
218 1
                setattr(self, attribute, value)
219 1
                if attribute in self.attributes_requiring_redeploy:
220 1
                    redeploy = value
221 1
        self.sync()
222 1
        return enable, redeploy
223
224 1
    def set_flow_removed_at(self):
225
        """Update flow_removed_at attribute."""
226
        self.flow_removed_at = now()
227
228 1
    def has_recent_removed_flow(self, setting=settings):
229
        """Check if any flow has been removed from the evc"""
230
        if self.flow_removed_at is None:
231
            return False
232
        res_seconds = (now() - self.flow_removed_at).seconds
233
        return res_seconds < setting.TIME_RECENT_DELETED_FLOWS
234
235 1
    def is_recent_updated(self, setting=settings):
236
        """Check if the evc has been updated recently"""
237
        res_seconds = (now() - self.updated_at).seconds
238
        return res_seconds < setting.TIME_RECENT_UPDATED
239
240 1
    def __repr__(self):
241
        """Repr method."""
242 1
        return f"EVC({self._id}, {self.name})"
243
244 1
    def _validate(self, **kwargs):
245
        """Do Basic validations.
246
247
        Verify required attributes: name, uni_a, uni_z
248
        Verify if the attributes uni_a and uni_z are valid.
249
250
        Raises:
251
            ValueError: message with error detail.
252
253
        """
254 1
        for attribute in self.required_attributes:
255
256 1
            if attribute not in kwargs:
257 1
                raise ValueError(f"{attribute} is required.")
258
259 1
            if "uni" in attribute:
260 1
                uni = kwargs.get(attribute)
261 1
                if not isinstance(uni, UNI):
262
                    raise ValueError(f"{attribute} is an invalid UNI.")
263
264 1
                if not uni.is_valid():
265 1
                    try:
266 1
                        tag = uni.user_tag.value
267
                    except AttributeError:
268
                        tag = None
269 1
                    message = f"VLAN tag {tag} is not available in {attribute}"
270 1
                    raise ValueError(message)
271
272 1
    def _validate_has_primary_or_dynamic(
273
        self,
274
        primary_path=None,
275
        dynamic_backup_path=None,
276
        uni_a=None,
277
        uni_z=None,
278
    ) -> None:
279
        """Validate that it must have a primary path or allow dynamic paths."""
280 1
        primary_path = (
281
            primary_path
282
            if primary_path is not None
283
            else self.primary_path
284
        )
285 1
        dynamic_backup_path = (
286
            dynamic_backup_path
287
            if dynamic_backup_path is not None
288
            else self.dynamic_backup_path
289
        )
290 1
        uni_a = uni_a if uni_a is not None else self.uni_a
291 1
        uni_z = uni_z if uni_z is not None else self.uni_z
292 1
        if (
293
            not primary_path
294
            and not dynamic_backup_path
295
            and uni_a and uni_z
296
            and uni_a.interface.switch != uni_z.interface.switch
297
        ):
298 1
            msg = "The EVC must have a primary path or allow dynamic paths."
299 1
            raise ValueError(msg)
300
301 1
    def __eq__(self, other):
302
        """Override the default implementation."""
303 1
        if not isinstance(other, EVC):
304
            return False
305
306 1
        attrs_to_compare = ["name", "uni_a", "uni_z", "owner", "bandwidth"]
307 1
        for attribute in attrs_to_compare:
308 1
            if getattr(other, attribute) != getattr(self, attribute):
309 1
                return False
310 1
        return True
311
312 1
    def is_intra_switch(self):
313
        """Check if the UNIs are in the same switch."""
314 1
        return self.uni_a.interface.switch == self.uni_z.interface.switch
315
316 1
    def shares_uni(self, other):
317
        """Check if two EVCs share an UNI."""
318 1
        if other.uni_a in (self.uni_a, self.uni_z) or other.uni_z in (
319
            self.uni_a,
320
            self.uni_z,
321
        ):
322 1
            return True
323
        return False
324
325 1
    def as_dict(self):
326
        """Return a dictionary representing an EVC object."""
327 1
        evc_dict = {
328
            "id": self.id,
329
            "name": self.name,
330
            "uni_a": self.uni_a.as_dict(),
331
            "uni_z": self.uni_z.as_dict(),
332
        }
333
334 1
        time_fmt = "%Y-%m-%dT%H:%M:%S"
335
336 1
        evc_dict["start_date"] = self.start_date
337 1
        if isinstance(self.start_date, datetime):
338 1
            evc_dict["start_date"] = self.start_date.strftime(time_fmt)
339
340 1
        evc_dict["end_date"] = self.end_date
341 1
        if isinstance(self.end_date, datetime):
342 1
            evc_dict["end_date"] = self.end_date.strftime(time_fmt)
343
344 1
        evc_dict["queue_id"] = self.queue_id
345 1
        evc_dict["bandwidth"] = self.bandwidth
346 1
        evc_dict["primary_links"] = self.primary_links.as_dict()
347 1
        evc_dict["backup_links"] = self.backup_links.as_dict()
348 1
        evc_dict["current_path"] = self.current_path.as_dict()
349 1
        evc_dict["failover_path"] = self.failover_path.as_dict()
350 1
        evc_dict["primary_path"] = self.primary_path.as_dict()
351 1
        evc_dict["backup_path"] = self.backup_path.as_dict()
352 1
        evc_dict["dynamic_backup_path"] = self.dynamic_backup_path
353 1
        evc_dict["metadata"] = self.metadata
354
355 1
        evc_dict["request_time"] = self.request_time
356 1
        if isinstance(self.request_time, datetime):
357 1
            evc_dict["request_time"] = self.request_time.strftime(time_fmt)
358
359 1
        time = self.creation_time.strftime(time_fmt)
360 1
        evc_dict["creation_time"] = time
361
362 1
        evc_dict["owner"] = self.owner
363 1
        evc_dict["circuit_scheduler"] = [
364
            sc.as_dict() for sc in self.circuit_scheduler
365
        ]
366
367 1
        evc_dict["active"] = self.is_active()
368 1
        evc_dict["enabled"] = self.is_enabled()
369 1
        evc_dict["archived"] = self.archived
370 1
        evc_dict["sb_priority"] = self.sb_priority
371 1
        evc_dict["service_level"] = self.service_level
372 1
        evc_dict["primary_constraints"] = self.primary_constraints
373 1
        evc_dict["secondary_constraints"] = self.secondary_constraints
374 1
        evc_dict["flow_removed_at"] = self.flow_removed_at
375 1
        evc_dict["updated_at"] = self.updated_at
376
377 1
        return evc_dict
378
379 1
    @property
380 1
    def id(self):  # pylint: disable=invalid-name
381
        """Return this EVC's ID."""
382 1
        return self._id
383
384 1
    def archive(self):
385
        """Archive this EVC on deletion."""
386 1
        self.archived = True
387
388
389
# pylint: disable=fixme, too-many-public-methods
390 1
class EVCDeploy(EVCBase):
391
    """Class to handle the deploy procedures."""
392
393 1
    def create(self):
394
        """Create a EVC."""
395
396 1
    def discover_new_paths(self):
397
        """Discover new paths to satisfy this circuit and deploy it."""
398
        return DynamicPathManager.get_best_paths(self,
399
                                                 **self.primary_constraints)
400
401 1
    def get_failover_path_candidates(self):
402
        """Get failover paths to satisfy this EVC."""
403
        # in the future we can return primary/backup paths as well
404
        # we just have to properly handle link_up and failover paths
405
        # if (
406
        #     self.is_using_primary_path() and
407
        #     self.backup_path.status is EntityStatus.UP
408
        # ):
409
        #     yield self.backup_path
410 1
        return DynamicPathManager.get_disjoint_paths(self, self.current_path)
411
412 1
    def change_path(self):
413
        """Change EVC path."""
414
415 1
    def reprovision(self):
416
        """Force the EVC (re-)provisioning."""
417
418 1
    def is_affected_by_link(self, link):
419
        """Return True if this EVC has the given link on its current path."""
420 1
        return link in self.current_path
421
422 1
    def link_affected_by_interface(self, interface):
423
        """Return True if this EVC has the given link on its current path."""
424
        return self.current_path.link_affected_by_interface(interface)
425
426 1
    def is_backup_path_affected_by_link(self, link):
427
        """Return True if the backup path of this EVC uses the given link."""
428 1
        return link in self.backup_path
429
430
    # pylint: disable=invalid-name
431 1
    def is_primary_path_affected_by_link(self, link):
432
        """Return True if the primary path of this EVC uses the given link."""
433 1
        return link in self.primary_path
434
435 1
    def is_failover_path_affected_by_link(self, link):
436
        """Return True if this EVC has the given link on its failover path."""
437 1
        return link in self.failover_path
438
439 1
    def is_eligible_for_failover_path(self):
440
        """Verify if this EVC is eligible for failover path (EP029)"""
441
        # In the future this function can be augmented to consider
442
        # primary/backup, primary/dynamic, and other path combinations
443 1
        return (
444
            self.dynamic_backup_path and
445
            not self.primary_path and not self.backup_path
446
        )
447
448 1
    def is_using_primary_path(self):
449
        """Verify if the current deployed path is self.primary_path."""
450 1
        return self.primary_path and (self.current_path == self.primary_path)
451
452 1
    def is_using_backup_path(self):
453
        """Verify if the current deployed path is self.backup_path."""
454 1
        return self.backup_path and (self.current_path == self.backup_path)
455
456 1
    def is_using_dynamic_path(self):
457
        """Verify if the current deployed path is a dynamic path."""
458 1
        if (
459
            self.current_path
460
            and not self.is_using_primary_path()
461
            and not self.is_using_backup_path()
462
            and self.current_path.status == EntityStatus.UP
463
        ):
464
            return True
465 1
        return False
466
467 1
    def deploy_to_backup_path(self):
468
        """Deploy the backup path into the datapaths of this circuit.
469
470
        If the backup_path attribute is valid and up, this method will try to
471
        deploy this backup_path.
472
473
        If everything fails and dynamic_backup_path is True, then tries to
474
        deploy a dynamic path.
475
        """
476
        # TODO: Remove flows from current (cookies)
477 1
        if self.is_using_backup_path():
478
            # TODO: Log to say that cannot move backup to backup
479
            return True
480
481 1
        success = False
482 1
        if self.backup_path.status is EntityStatus.UP:
483 1
            success = self.deploy_to_path(self.backup_path)
484
485 1
        if success:
486 1
            return True
487
488 1
        if self.dynamic_backup_path or self.is_intra_switch():
489 1
            return self.deploy_to_path()
490
491
        return False
492
493 1
    def deploy_to_primary_path(self):
494
        """Deploy the primary path into the datapaths of this circuit.
495
496
        If the primary_path attribute is valid and up, this method will try to
497
        deploy this primary_path.
498
        """
499
        # TODO: Remove flows from current (cookies)
500 1
        if self.is_using_primary_path():
501
            # TODO: Log to say that cannot move primary to primary
502
            return True
503
504 1
        if self.primary_path.status is EntityStatus.UP:
505 1
            return self.deploy_to_path(self.primary_path)
506 1
        return False
507
508 1
    def deploy(self):
509
        """Deploy EVC to best path.
510
511
        Best path can be the primary path, if available. If not, the backup
512
        path, and, if it is also not available, a dynamic path.
513
        """
514 1
        if self.archived:
515 1
            return False
516 1
        self.enable()
517 1
        success = self.deploy_to_primary_path()
518 1
        if not success:
519 1
            success = self.deploy_to_backup_path()
520
521 1
        if success:
522 1
            emit_event(self._controller, "deployed",
523
                       content=map_evc_event_content(self))
524 1
        return success
525
526 1
    @staticmethod
527 1
    def get_path_status(path):
528
        """Check for the current status of a path.
529
530
        If any link in this path is down, the path is considered down.
531
        """
532 1
        if not path:
533 1
            return EntityStatus.DISABLED
534
535 1
        for link in path:
536 1
            if link.status is not EntityStatus.UP:
537 1
                return link.status
538 1
        return EntityStatus.UP
539
540
    #    def discover_new_path(self):
541
    #        # TODO: discover a new path to satisfy this circuit and deploy
542
543 1
    def remove(self):
544
        """Remove EVC path and disable it."""
545 1
        self.remove_current_flows()
546 1
        self.remove_failover_flows()
547 1
        self.disable()
548 1
        self.sync()
549 1
        emit_event(self._controller, "undeployed",
550
                   content=map_evc_event_content(self))
551
552 1
    def remove_failover_flows(self, exclude_uni_switches=True,
553
                              force=True, sync=True) -> None:
554
        """Remove failover_flows.
555
556
        By default, it'll exclude UNI switches, if mef_eline has already
557
        called remove_current_flows before then this minimizes the number
558
        of FlowMods and IO.
559
        """
560 1
        if not self.failover_path:
561 1
            return
562 1
        switches, cookie, excluded = OrderedDict(), self.get_cookie(), set()
563 1
        links = set()
564 1
        if exclude_uni_switches:
565 1
            excluded.add(self.uni_a.interface.switch.id)
566 1
            excluded.add(self.uni_z.interface.switch.id)
567 1
        for link in self.failover_path:
568 1
            if link.endpoint_a.switch.id not in excluded:
569 1
                switches[link.endpoint_a.switch.id] = link.endpoint_a.switch
570 1
                links.add(link)
571 1
            if link.endpoint_b.switch.id not in excluded:
572 1
                switches[link.endpoint_b.switch.id] = link.endpoint_b.switch
573 1
                links.add(link)
574 1
        for switch in switches.values():
575 1
            try:
576 1
                self._send_flow_mods(
577
                    switch.id,
578
                    [
579
                        {
580
                            "cookie": cookie,
581
                            "cookie_mask": int(0xffffffffffffffff),
582
                        }
583
                    ],
584
                    "delete",
585
                    force=force,
586
                )
587
            except FlowModException as err:
588
                log.error(
589
                    f"Error removing flows from switch {switch.id} for"
590
                    f"EVC {self}: {err}"
591
                )
592 1
        for link in links:
593 1
            link.make_tag_available(link.get_metadata("s_vlan"))
594 1
            link.remove_metadata("s_vlan")
595 1
            notify_link_available_tags(self._controller, link)
596 1
        self.failover_path = Path([])
597 1
        if sync:
598 1
            self.sync()
599
600 1
    def remove_current_flows(self, current_path=None, force=True):
601
        """Remove all flows from current path."""
602 1
        switches = set()
603
604 1
        switches.add(self.uni_a.interface.switch)
605 1
        switches.add(self.uni_z.interface.switch)
606 1
        if not current_path:
607 1
            current_path = self.current_path
608 1
        for link in current_path:
609 1
            switches.add(link.endpoint_a.switch)
610 1
            switches.add(link.endpoint_b.switch)
611
612 1
        match = {
613
            "cookie": self.get_cookie(),
614
            "cookie_mask": int(0xffffffffffffffff)
615
        }
616
617 1
        for switch in switches:
618 1
            try:
619 1
                self._send_flow_mods(switch.id, [match], 'delete', force=force)
620 1
            except FlowModException as err:
621 1
                log.error(
622
                    f"Error removing flows from switch {switch.id} for"
623
                    f"EVC {self}: {err}"
624
                )
625
626 1
        current_path.make_vlans_available()
627 1
        for link in current_path:
628 1
            notify_link_available_tags(self._controller, link)
629 1
        self.current_path = Path([])
630 1
        self.deactivate()
631 1
        self.sync()
632
633 1
    def remove_path_flows(self, path=None, force=True):
634
        """Remove all flows from path."""
635 1
        if not path:
636 1
            return
637
638 1
        dpid_flows_match = {}
639 1
        for dpid, flows in self._prepare_nni_flows(path).items():
640 1
            dpid_flows_match.setdefault(dpid, [])
641 1
            for flow in flows:
642 1
                dpid_flows_match[dpid].append({
643
                    "cookie": flow["cookie"],
644
                    "match": flow["match"],
645
                    "cookie_mask": int(0xffffffffffffffff)
646
                })
647 1
        for dpid, flows in self._prepare_uni_flows(path, skip_in=True).items():
648 1
            dpid_flows_match.setdefault(dpid, [])
649 1
            for flow in flows:
650 1
                dpid_flows_match[dpid].append({
651
                    "cookie": flow["cookie"],
652
                    "match": flow["match"],
653
                    "cookie_mask": int(0xffffffffffffffff)
654
                })
655
656 1
        for dpid, flows in dpid_flows_match.items():
657 1
            try:
658 1
                self._send_flow_mods(dpid, flows, 'delete', force=force)
659 1
            except FlowModException as err:
660 1
                log.error(
661
                    "Error removing failover flows: "
662
                    f"dpid={dpid} evc={self} error={err}"
663
                )
664
665 1
        path.make_vlans_available()
666 1
        for link in path:
667 1
            notify_link_available_tags(self._controller, link)
668
669 1
    @staticmethod
670 1
    def links_zipped(path=None):
671
        """Return an iterator which yields pairs of links in order."""
672 1
        if not path:
673
            return []
674 1
        return zip(path[:-1], path[1:])
675
676 1
    def should_deploy(self, path=None):
677
        """Verify if the circuit should be deployed."""
678 1
        if not path:
679 1
            log.debug("Path is empty.")
680 1
            return False
681
682 1
        if not self.is_enabled():
683 1
            log.debug(f"{self} is disabled.")
684 1
            return False
685
686 1
        if not self.is_active():
687 1
            log.debug(f"{self} will be deployed.")
688 1
            return True
689
690 1
        return False
691
692 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
693
        """Install the flows for this circuit.
694
695
        Procedures to deploy:
696
697
        0. Remove current flows installed
698
        1. Decide if will deploy "path" or discover a new path
699
        2. Choose vlan
700
        3. Install NNI flows
701
        4. Install UNI flows
702
        5. Activate
703
        6. Update current_path
704
        7. Update links caches(primary, current, backup)
705
706
        """
707 1
        self.remove_current_flows()
708 1
        use_path = path
709 1
        if self.should_deploy(use_path):
710 1
            try:
711 1
                use_path.choose_vlans()
712 1
                for link in use_path:
713 1
                    notify_link_available_tags(self._controller, link)
714 1
            except KytosNoTagAvailableError:
715 1
                use_path = None
716
        else:
717 1
            for use_path in self.discover_new_paths():
718 1
                if use_path is None:
719
                    continue
720 1
                try:
721 1
                    use_path.choose_vlans()
722 1
                    for link in use_path:
723 1
                        notify_link_available_tags(self._controller, link)
724 1
                    break
725 1
                except KytosNoTagAvailableError:
726 1
                    pass
727
            else:
728 1
                use_path = None
729
730 1
        try:
731 1
            if use_path:
732 1
                self._install_nni_flows(use_path)
733 1
                self._install_uni_flows(use_path)
734 1
            elif self.is_intra_switch():
735 1
                use_path = Path()
736 1
                self._install_direct_uni_flows()
737
            else:
738 1
                log.warning(
739
                    f"{self} was not deployed. " "No available path was found."
740
                )
741 1
                return False
742 1
        except FlowModException as err:
743 1
            log.error(
744
                f"Error deploying EVC {self} when calling flow_manager: {err}"
745
            )
746 1
            self.remove_current_flows(use_path)
747 1
            return False
748 1
        self.activate()
749 1
        self.current_path = use_path
750 1
        self.sync()
751 1
        log.info(f"{self} was deployed.")
752 1
        return True
753
754 1
    def setup_failover_path(self):
755
        """Install flows for the failover path of this EVC.
756
757
        Procedures to deploy:
758
759
        0. Remove flows currently installed for failover_path (if any)
760
        1. Discover a disjoint path from current_path
761
        2. Choose vlans
762
        3. Install NNI flows
763
        4. Install UNI egress flows
764
        5. Update failover_path
765
        """
766
        # Intra-switch EVCs have no failover_path
767 1
        if self.is_intra_switch():
768 1
            return False
769
770
        # For not only setup failover path for totally dynamic EVCs
771 1
        if not self.is_eligible_for_failover_path():
772 1
            return False
773
774 1
        reason = ""
775 1
        self.remove_path_flows(self.failover_path)
776 1
        for use_path in self.get_failover_path_candidates():
777 1
            if not use_path:
778 1
                continue
779 1
            try:
780 1
                use_path.choose_vlans()
781 1
                for link in use_path:
782 1
                    notify_link_available_tags(self._controller, link)
783 1
                break
784 1
            except KytosNoTagAvailableError:
785 1
                pass
786
        else:
787 1
            use_path = Path([])
788 1
            reason = "No available path was found"
789
790 1
        try:
791 1
            if use_path:
792 1
                self._install_nni_flows(use_path)
793 1
                self._install_uni_flows(use_path, skip_in=True)
794 1
        except FlowModException as err:
795 1
            reason = "Error deploying failover path"
796 1
            log.error(
797
                f"{reason} for {self}. FlowManager error: {err}"
798
            )
799 1
            self.remove_path_flows(use_path)
800 1
            use_path = Path([])
801
802 1
        self.failover_path = use_path
803 1
        self.sync()
804
805 1
        if not use_path:
806 1
            log.warning(
807
                f"Failover path for {self} was not deployed: {reason}"
808
            )
809 1
            return False
810 1
        log.info(f"Failover path for {self} was deployed.")
811 1
        return True
812
813 1
    def get_failover_flows(self):
814
        """Return the flows needed to make the failover path active, i.e. the
815
        flows for ingress forwarding.
816
817
        Return:
818
            dict: A dict of flows indexed by the switch_id will be returned, or
819
                an empty dict if no failover_path is available.
820
        """
821 1
        if not self.failover_path:
822 1
            return {}
823 1
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
824
825 1
    def _prepare_direct_uni_flows(self):
826
        """Prepare flows connecting two UNIs for intra-switch EVC."""
827 1
        vlan_a = self._get_value_from_uni_tag(self.uni_a)
828 1
        vlan_z = self._get_value_from_uni_tag(self.uni_z)
829
830 1
        flow_mod_az = self._prepare_flow_mod(
831
            self.uni_a.interface, self.uni_z.interface,
832
            self.queue_id, vlan_a
833
        )
834 1
        flow_mod_za = self._prepare_flow_mod(
835
            self.uni_z.interface, self.uni_a.interface,
836
            self.queue_id, vlan_z
837
        )
838
839 1
        if vlan_a is not None:
840 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
841
842 1
        if vlan_z is not None:
843 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
844
845 1
        if vlan_z not in self.special_cases:
846 1
            flow_mod_az["actions"].insert(
847
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
848
            )
849 1
            if not vlan_a:
850 1
                flow_mod_az["actions"].insert(
851
                    0, {"action_type": "push_vlan", "tag_type": "c"}
852
                )
853
854 1
        if vlan_a not in self.special_cases:
855 1
            flow_mod_za["actions"].insert(
856
                    0, {"action_type": "set_vlan", "vlan_id": vlan_a}
857
                )
858 1
            if not vlan_z:
859 1
                flow_mod_za["actions"].insert(
860
                    0, {"action_type": "push_vlan", "tag_type": "c"}
861
                )
862 1
            if vlan_z == 0:
863 1
                flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
864
865 1
        elif vlan_a == "4096/4096" and vlan_z == 0:
866 1
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
867
868 1
        elif vlan_a == 0 and vlan_z:
869 1
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
870
871 1
        return (
872
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
873
        )
874
875 1
    def _install_direct_uni_flows(self):
876
        """Install flows connecting two UNIs.
877
878
        This case happens when the circuit is between UNIs in the
879
        same switch.
880
        """
881 1
        (dpid, flows) = self._prepare_direct_uni_flows()
882 1
        self._send_flow_mods(dpid, flows)
883
884 1
    def _prepare_nni_flows(self, path=None):
885
        """Prepare NNI flows."""
886 1
        nni_flows = OrderedDict()
887 1
        previous = self.uni_a.interface.switch.dpid
888 1
        for incoming, outcoming in self.links_zipped(path):
889 1
            in_vlan = incoming.get_metadata("s_vlan").value
890 1
            out_vlan = outcoming.get_metadata("s_vlan").value
891 1
            in_endpoint = self.get_endpoint_by_id(incoming, previous, ne)
892 1
            out_endpoint = self.get_endpoint_by_id(
893
                outcoming, in_endpoint.switch.id, eq
894
            )
895
896 1
            flows = []
897
            # Flow for one direction
898 1
            flows.append(
899
                self._prepare_nni_flow(
900
                    in_endpoint,
901
                    out_endpoint,
902
                    in_vlan,
903
                    out_vlan,
904
                    queue_id=self.queue_id,
905
                )
906
            )
907
908
            # Flow for the other direction
909 1
            flows.append(
910
                self._prepare_nni_flow(
911
                    out_endpoint,
912
                    in_endpoint,
913
                    out_vlan,
914
                    in_vlan,
915
                    queue_id=self.queue_id,
916
                )
917
            )
918 1
            previous = in_endpoint.switch.id
919 1
            nni_flows[in_endpoint.switch.id] = flows
920 1
        return nni_flows
921
922 1
    def _install_nni_flows(self, path=None):
923
        """Install NNI flows."""
924 1
        for dpid, flows in self._prepare_nni_flows(path).items():
925 1
            self._send_flow_mods(dpid, flows)
926
927 1
    @staticmethod
928 1
    def _get_value_from_uni_tag(uni):
929
        """Returns the value from tag. In case of any and untagged
930
        it should return 4096/4096 and 0 respectively"""
931 1
        special = {"any": "4096/4096", "untagged": 0}
932
933 1
        if uni.user_tag:
934 1
            value = uni.user_tag.value
935 1
            return special.get(value, value)
936
        return None
937
938 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
939
        """Prepare flows to install UNIs."""
940 1
        uni_flows = {}
941 1
        if not path:
942 1
            log.info("install uni flows without path.")
943 1
            return uni_flows
944
945
        # Determine VLANs
946 1
        in_vlan_a = self._get_value_from_uni_tag(self.uni_a)
947 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
948
949 1
        in_vlan_z = self._get_value_from_uni_tag(self.uni_z)
950 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
951
952
        # Get endpoints from path
953 1
        endpoint_a = self.get_endpoint_by_id(
954
            path[0], self.uni_a.interface.switch.id, eq
955
        )
956 1
        endpoint_z = self.get_endpoint_by_id(
957
            path[-1], self.uni_z.interface.switch.id, eq
958
        )
959
960
        # Flows for the first UNI
961 1
        flows_a = []
962
963
        # Flow for one direction, pushing the service tag
964 1
        if not skip_in:
965 1
            push_flow = self._prepare_push_flow(
966
                self.uni_a.interface,
967
                endpoint_a,
968
                in_vlan_a,
969
                out_vlan_a,
970
                in_vlan_z,
971
                queue_id=self.queue_id,
972
            )
973 1
            flows_a.append(push_flow)
974
975
        # Flow for the other direction, popping the service tag
976 1
        if not skip_out:
977 1
            pop_flow = self._prepare_pop_flow(
978
                endpoint_a,
979
                self.uni_a.interface,
980
                out_vlan_a,
981
                queue_id=self.queue_id,
982
            )
983 1
            flows_a.append(pop_flow)
984
985 1
        uni_flows[self.uni_a.interface.switch.id] = flows_a
986
987
        # Flows for the second UNI
988 1
        flows_z = []
989
990
        # Flow for one direction, pushing the service tag
991 1
        if not skip_in:
992 1
            push_flow = self._prepare_push_flow(
993
                self.uni_z.interface,
994
                endpoint_z,
995
                in_vlan_z,
996
                out_vlan_z,
997
                in_vlan_a,
998
                queue_id=self.queue_id,
999
            )
1000 1
            flows_z.append(push_flow)
1001
1002
        # Flow for the other direction, popping the service tag
1003 1
        if not skip_out:
1004 1
            pop_flow = self._prepare_pop_flow(
1005
                endpoint_z,
1006
                self.uni_z.interface,
1007
                out_vlan_z,
1008
                queue_id=self.queue_id,
1009
            )
1010 1
            flows_z.append(pop_flow)
1011
1012 1
        uni_flows[self.uni_z.interface.switch.id] = flows_z
1013
1014 1
        return uni_flows
1015
1016 1
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
1017
        """Install UNI flows."""
1018 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
1019
1020 1
        for (dpid, flows) in uni_flows.items():
1021 1
            self._send_flow_mods(dpid, flows)
1022
1023 1
    @staticmethod
1024 1
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
1025
        """Send a flow_mod list to a specific switch.
1026
1027
        Args:
1028
            dpid(str): The target of flows (i.e. Switch.id).
1029
            flow_mods(dict): Python dictionary with flow_mods.
1030
            command(str): By default is 'flows'. To remove a flow is 'remove'.
1031
            force(bool): True to send via consistency check in case of errors
1032
1033
        """
1034
1035 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
1036
1037 1
        data = {"flows": flow_mods, "force": force}
1038 1
        response = requests.post(endpoint, json=data)
1039 1
        if response.status_code >= 400:
1040 1
            raise FlowModException(str(response.text))
1041
1042 1
    def get_cookie(self):
1043
        """Return the cookie integer from evc id."""
1044 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
1045
1046 1
    @staticmethod
1047 1
    def get_id_from_cookie(cookie):
1048
        """Return the evc id given a cookie value."""
1049 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
1050 1
        return f"{evc_id:x}".zfill(14)
1051
1052 1
    def set_flow_table_group_id(self, flow_mod: dict, vlan) -> dict:
1053
        """Set table_group and table_id"""
1054 1
        table_group = "epl" if vlan is None else "evpl"
1055 1
        flow_mod["table_group"] = table_group
1056 1
        flow_mod["table_id"] = self.table_group[table_group]
1057 1
        return flow_mod
1058
1059 1
    @staticmethod
1060 1
    def get_priority(vlan):
1061
        """Return priority value depending on vlan value"""
1062 1
        if vlan not in {None, "4096/4096", 0}:
1063 1
            return settings.EVPL_SB_PRIORITY
1064 1
        if vlan == 0:
1065 1
            return settings.UNTAGGED_SB_PRIORITY
1066 1
        if vlan == "4096/4096":
1067 1
            return settings.ANY_SB_PRIORITY
1068 1
        return settings.EPL_SB_PRIORITY
1069
1070 1
    def _prepare_flow_mod(self, in_interface, out_interface,
1071
                          queue_id=None, vlan=True):
1072
        """Prepare a common flow mod."""
1073 1
        default_actions = [
1074
            {"action_type": "output", "port": out_interface.port_number}
1075
        ]
1076 1
        if queue_id is not None:
1077
            default_actions.append(
1078
                {"action_type": "set_queue", "queue_id": queue_id}
1079
            )
1080
1081 1
        flow_mod = {
1082
            "match": {"in_port": in_interface.port_number},
1083
            "cookie": self.get_cookie(),
1084
            "actions": default_actions,
1085
            "owner": "mef_eline",
1086
        }
1087
1088 1
        self.set_flow_table_group_id(flow_mod, vlan)
1089 1
        if self.sb_priority:
1090
            flow_mod["priority"] = self.sb_priority
1091
        else:
1092 1
            flow_mod["priority"] = self.get_priority(vlan)
1093 1
        return flow_mod
1094
1095 1
    def _prepare_nni_flow(self, *args, queue_id=None):
1096
        """Create NNI flows."""
1097 1
        in_interface, out_interface, in_vlan, out_vlan = args
1098 1
        flow_mod = self._prepare_flow_mod(
1099
            in_interface, out_interface, queue_id
1100
        )
1101 1
        flow_mod["match"]["dl_vlan"] = in_vlan
1102 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1103 1
        flow_mod["actions"].insert(0, new_action)
1104
1105 1
        return flow_mod
1106
1107 1
    def _prepare_push_flow(self, *args, queue_id=None):
1108
        """Prepare push flow.
1109
1110
        Arguments:
1111
            in_interface(str): Interface input.
1112
            out_interface(str): Interface output.
1113
            in_vlan(str): Vlan input.
1114
            out_vlan(str): Vlan output.
1115
            new_c_vlan(str): New client vlan.
1116
1117
        Return:
1118
            dict: An python dictionary representing a FlowMod
1119
1120
        """
1121
        # assign all arguments
1122 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
1123 1
        flow_mod = self._prepare_flow_mod(
1124
            in_interface, out_interface, queue_id, in_vlan
1125
        )
1126
        # the service tag must be always pushed
1127 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1128 1
        flow_mod["actions"].insert(0, new_action)
1129
1130 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
1131 1
        flow_mod["actions"].insert(0, new_action)
1132
1133 1
        if in_vlan is not None:
1134
            # if in_vlan is set, it must be included in the match
1135 1
            flow_mod["match"]["dl_vlan"] = in_vlan
1136
1137 1
        if new_c_vlan not in self.special_cases:
1138
            # new_in_vlan is an integer but zero, action to set is required
1139 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
1140 1
            flow_mod["actions"].insert(0, new_action)
1141
1142 1
        if in_vlan not in self.special_cases and new_c_vlan == 0:
1143
            # # new_in_vlan is an integer but zero and new_c_vlan does not
1144
            # a pop action is required
1145 1
            new_action = {"action_type": "pop_vlan"}
1146 1
            flow_mod["actions"].insert(0, new_action)
1147
1148 1
        elif in_vlan == "4096/4096" and new_c_vlan == 0:
1149
            # if in_vlan match with any tags and new_c_vlan does not
1150
            # a pop action is required
1151 1
            new_action = {"action_type": "pop_vlan"}
1152 1
            flow_mod["actions"].insert(0, new_action)
1153
1154 1
        elif not in_vlan and new_c_vlan not in self.special_cases:
1155
            # new_in_vlan is an integer but zero and in_vlan is not set
1156
            # then it is set now
1157 1
            new_action = {"action_type": "push_vlan", "tag_type": "c"}
1158 1
            flow_mod["actions"].insert(0, new_action)
1159
1160 1
        return flow_mod
1161
1162 1
    def _prepare_pop_flow(
1163
        self, in_interface, out_interface, out_vlan, queue_id=None
1164
    ):
1165
        # pylint: disable=too-many-arguments
1166
        """Prepare pop flow."""
1167 1
        flow_mod = self._prepare_flow_mod(
1168
            in_interface, out_interface, queue_id
1169
        )
1170 1
        flow_mod["match"]["dl_vlan"] = out_vlan
1171 1
        new_action = {"action_type": "pop_vlan"}
1172 1
        flow_mod["actions"].insert(0, new_action)
1173 1
        return flow_mod
1174
1175 1
    @staticmethod
1176 1
    def run_bulk_sdntraces(uni_list):
1177
        """Run SDN traces on control plane starting from EVC UNIs."""
1178 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/traces"
1179 1
        data = []
1180 1
        for uni in uni_list:
1181 1
            data_uni = {
1182
                "trace": {
1183
                            "switch": {
1184
                                "dpid": uni.interface.switch.dpid,
1185
                                "in_port": uni.interface.port_number,
1186
                            }
1187
                        }
1188
                }
1189 1
            if uni.user_tag:
1190 1
                uni_dl_vlan = map_dl_vlan(uni.user_tag.value)
1191 1
                if uni_dl_vlan:
1192 1
                    data_uni["trace"]["eth"] = {
1193
                                            "dl_type": 0x8100,
1194
                                            "dl_vlan": uni_dl_vlan,
1195
                                            }
1196 1
            data.append(data_uni)
1197 1
        try:
1198 1
            response = requests.put(endpoint, json=data, timeout=30)
1199
        except Timeout as exception:
1200
            log.error(f"Request has timed out: {exception}")
1201
            return {"result": []}
1202 1
        if response.status_code >= 400:
1203 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1204 1
            return {"result": []}
1205 1
        return response.json()
1206
1207 1
    @staticmethod
1208 1
    def trace_invalid(trace):
1209
        """Auxiliar function to check traces"""
1210 1
        if not trace or trace[-1]['type'] != 'last':
1211 1
            return True
1212 1
        return False
1213
1214
    # pylint: disable=too-many-return-statements
1215 1
    @staticmethod
1216 1
    def check_trace(circuit, trace_a, trace_z):
1217
        """Auxiliar function to check an individual trace"""
1218 1
        if EVCDeploy.trace_invalid(trace_a):
1219 1
            log.warning(
1220
                f"Invalid trace from trace_a: {trace_a}"
1221
            )
1222 1
            return False
1223 1
        if EVCDeploy.trace_invalid(trace_z):
1224 1
            log.warning(
1225
                f"Invalid trace from trace_z: {trace_z}"
1226
            )
1227 1
            return False
1228 1
        if (
1229
            len(trace_a) != len(circuit.current_path) + 1
1230
            or not compare_uni_out_trace(circuit.uni_z, trace_a[-1])
1231
        ):
1232 1
            log.warning(f"Invalid trace from uni_a: {trace_a}")
1233 1
            return False
1234 1
        if (
1235
            len(trace_z) != len(circuit.current_path) + 1
1236
            or not compare_uni_out_trace(circuit.uni_a, trace_z[-1])
1237
        ):
1238 1
            log.warning(f"Invalid trace from uni_z: {trace_z}")
1239 1
            return False
1240
1241 1
        for link, trace1, trace2 in zip(circuit.current_path,
1242
                                        trace_a[1:],
1243
                                        trace_z[:0:-1]):
1244 1
            metadata_vlan = None
1245 1
            if link.metadata:
1246 1
                metadata_vlan = glom(link.metadata, 's_vlan.value')
1247 1
            if compare_endpoint_trace(
1248
                                        link.endpoint_a,
1249
                                        metadata_vlan,
1250
                                        trace2
1251
                                    ) is False:
1252 1
                log.warning(f"Invalid trace from uni_a: {trace_a}")
1253 1
                return False
1254 1
            if compare_endpoint_trace(
1255
                                        link.endpoint_b,
1256
                                        metadata_vlan,
1257
                                        trace1
1258
                                    ) is False:
1259 1
                log.warning(f"Invalid trace from uni_z: {trace_z}")
1260 1
                return False
1261
1262 1
        return True
1263
1264 1
    @staticmethod
1265 1
    def check_list_traces(list_circuits):
1266
        """Check if current_path is deployed comparing with SDN traces."""
1267 1
        if not list_circuits:
1268
            return {}
1269 1
        uni_list = []
1270 1
        for circuit in list_circuits:
1271 1
            uni_list.append(circuit.uni_a)
1272 1
            uni_list.append(circuit.uni_z)
1273
1274 1
        traces = EVCDeploy.run_bulk_sdntraces(uni_list)
1275 1
        traces = traces["result"]
1276 1
        circuits_checked = {}
1277 1
        if not traces:
1278
            return circuits_checked
1279
1280 1
        try:
1281 1
            for i, circuit in enumerate(list_circuits):
1282 1
                trace_a = traces[2*i]
1283 1
                trace_z = traces[2*i+1]
1284 1
                circuits_checked[circuit.id] = EVCDeploy.check_trace(
1285
                        circuit, trace_a, trace_z
1286
                    )
1287
        except IndexError as err:
1288
            log.error(
1289
                f"Bulk sdntraces returned fewer items than expected."
1290
                f"Error = {err}"
1291
            )
1292
1293 1
        return circuits_checked
1294
1295 1
    @staticmethod
1296 1
    def get_endpoint_by_id(
1297
        link: Link,
1298
        id_: str,
1299
        operator: Union[eq, ne]
1300
    ) -> Interface:
1301
        """Return endpoint from link
1302
        either equal(eq) or not equal(ne) to id"""
1303 1
        if operator(link.endpoint_a.switch.id, id_):
1304 1
            return link.endpoint_a
1305 1
        return link.endpoint_b
1306
1307
1308 1
class LinkProtection(EVCDeploy):
1309
    """Class to handle link protection."""
1310
1311 1
    def is_affected_by_link(self, link=None):
1312
        """Verify if the current path is affected by link down event."""
1313
        return self.current_path.is_affected_by_link(link)
1314
1315 1
    def is_using_primary_path(self):
1316
        """Verify if the current deployed path is self.primary_path."""
1317 1
        return self.current_path == self.primary_path
1318
1319 1
    def is_using_backup_path(self):
1320
        """Verify if the current deployed path is self.backup_path."""
1321 1
        return self.current_path == self.backup_path
1322
1323 1
    def is_using_dynamic_path(self):
1324
        """Verify if the current deployed path is dynamic."""
1325 1
        if (
1326
            self.current_path
1327
            and not self.is_using_primary_path()
1328
            and not self.is_using_backup_path()
1329
            and self.current_path.status is EntityStatus.UP
1330
        ):
1331
            return True
1332 1
        return False
1333
1334 1
    def deploy_to(self, path_name=None, path=None):
1335
        """Create a deploy to path."""
1336 1
        if self.current_path == path:
1337 1
            log.debug(f"{path_name} is equal to current_path.")
1338 1
            return True
1339
1340 1
        if path.status is EntityStatus.UP:
1341 1
            return self.deploy_to_path(path)
1342
1343 1
        return False
1344
1345 1
    def handle_link_up(self, link):
1346
        """Handle circuit when link down.
1347
1348
        Args:
1349
            link(Link): Link affected by link.down event.
1350
1351
        """
1352 1
        if self.is_intra_switch():
1353
            return True
1354
1355 1
        if self.is_using_primary_path():
1356 1
            return True
1357
1358 1
        success = False
1359 1
        if self.primary_path.is_affected_by_link(link):
1360 1
            success = self.deploy_to_primary_path()
1361
1362 1
        if success:
1363 1
            return True
1364
1365
        # We tried to deploy(primary_path) without success.
1366
        # And in this case is up by some how. Nothing to do.
1367 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1368 1
            return True
1369
1370
        # In this case, probably the circuit is not being used and
1371
        # we can move to backup
1372 1
        if self.backup_path.is_affected_by_link(link):
1373 1
            success = self.deploy_to_backup_path()
1374
1375
        # In this case, the circuit is not being used and we should
1376
        # try a dynamic path
1377 1
        if not success and self.dynamic_backup_path:
1378 1
            success = self.deploy_to_path()
1379
1380 1
        if success:
1381 1
            emit_event(self._controller, "redeployed_link_up",
1382
                       content=map_evc_event_content(self))
1383 1
            return True
1384
1385 1
        return True
1386
1387 1
    def handle_link_down(self):
1388
        """Handle circuit when link down.
1389
1390
        Returns:
1391
            bool: True if the re-deploy was successly otherwise False.
1392
1393
        """
1394 1
        success = False
1395 1
        if self.is_using_primary_path():
1396 1
            success = self.deploy_to_backup_path()
1397 1
        elif self.is_using_backup_path():
1398 1
            success = self.deploy_to_primary_path()
1399
1400 1
        if not success and self.dynamic_backup_path:
1401 1
            success = self.deploy_to_path()
1402
1403 1
        if success:
1404 1
            log.debug(f"{self} deployed after link down.")
1405
        else:
1406 1
            self.deactivate()
1407 1
            self.current_path = Path([])
1408 1
            self.sync()
1409 1
            log.debug(f"Failed to re-deploy {self} after link down.")
1410
1411 1
        return success
1412
1413
1414 1
class EVC(LinkProtection):
1415
    """Class that represents a E-Line Virtual Connection."""
1416