Passed
Pull Request — master (#226)
by
unknown
03:15
created

build.models.evc.EVCDeploy.run_bulk_sdntraces()   B

Complexity

Conditions 5

Size

Total Lines 29
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 5.0406

Importance

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