Passed
Pull Request — master (#254)
by
unknown
03:30
created

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

Complexity

Conditions 6

Size

Total Lines 32
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 21
CRAP Score 6

Importance

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