Passed
Pull Request — master (#258)
by
unknown
03:31
created

EVCDeploy._prepare_direct_uni_flows()   D

Complexity

Conditions 12

Size

Total Lines 50
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 35
nop 1
dl 0
loc 50
ccs 26
cts 26
cp 1
crap 12
rs 4.8
c 0
b 0
f 0

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