Passed
Pull Request — master (#337)
by Rogerio
03:35
created

build.models.evc.LinkProtection.handle_link_up()   C

Complexity

Conditions 11

Size

Total Lines 41
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 11.0151

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 41
ccs 19
cts 20
cp 0.95
rs 5.4
c 0
b 0
f 0
cc 11
nop 2
crap 11.0151

How to fix   Complexity   

Complexity

Complex classes like build.models.evc.LinkProtection.handle_link_up() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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