Passed
Pull Request — master (#280)
by
unknown
06:57
created

build.models.evc.EVCBase.is_recent_updated()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.2963

Importance

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