Passed
Pull Request — master (#241)
by
unknown
03:21
created

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

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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