Passed
Pull Request — master (#320)
by Vinicius
07:35 queued 03:38
created

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

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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