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

EVCDeploy._prepare_direct_uni_flows()   D

Complexity

Conditions 12

Size

Total Lines 48
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 33
nop 1
dl 0
loc 48
rs 4.8
c 0
b 0
f 0
ccs 24
cts 24
cp 1
crap 12

How to fix   Complexity   

Complexity

Complex classes like build.models.evc.EVCDeploy._prepare_direct_uni_flows() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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