Passed
Pull Request — master (#371)
by
unknown
03:29
created

build.models.evc.EVCDeploy.remove_failover_flows()   C

Complexity

Conditions 9

Size

Total Lines 44
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 9.0468

Importance

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