Passed
Pull Request — master (#327)
by Rogerio
03:26
created

EVCDeploy._prepare_direct_uni_flows()   D

Complexity

Conditions 12

Size

Total Lines 48
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 33
nop 1
dl 0
loc 48
rs 4.8
c 0
b 0
f 0
ccs 24
cts 24
cp 1
crap 12

How to fix   Complexity   

Complexity

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