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

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

Complexity

Conditions 1

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

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