Passed
Pull Request — master (#371)
by
unknown
07:16
created

build.models.evc.EVCBase._use_uni_vlan()   A

Complexity

Conditions 4

Size

Total Lines 13
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 11
nop 2
dl 0
loc 13
ccs 10
cts 10
cp 1
crap 4
rs 9.85
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
            result = uni.interface.use_tags(
430
                self._controller, tag, tag_type
431
            )
432 1
            if not result:
433 1
                intf = uni.interface.id
434 1
                raise ValueError(f"Tag {tag} is not available in {intf}")
435
436 1
    def make_uni_vlan_available(self, uni: UNI):
437
        """Make available tag from UNI"""
438 1
        if uni.user_tag is None:
439 1
            return
440 1
        tag = uni.user_tag.value
441 1
        tag_type = uni.user_tag.tag_type
442 1
        if isinstance(tag, int):
443 1
            result = uni.interface.make_tags_available(
444
                self._controller, tag, tag_type
445
            )
446 1
            if not result:
447 1
                intf = uni.interface.id
448 1
                log.warning(f"Tag {tag} was already available in {intf}")
449
450 1
    def remove_uni_tags(self):
451
        """Remove both UNI usage of a tag"""
452 1
        self.make_uni_vlan_available(self.uni_a)
453 1
        self.make_uni_vlan_available(self.uni_z)
454
455
456
# pylint: disable=fixme, too-many-public-methods
457 1
class EVCDeploy(EVCBase):
458
    """Class to handle the deploy procedures."""
459
460 1
    def create(self):
461
        """Create a EVC."""
462
463 1
    def discover_new_paths(self):
464
        """Discover new paths to satisfy this circuit and deploy it."""
465
        return DynamicPathManager.get_best_paths(self,
466
                                                 **self.primary_constraints)
467
468 1
    def get_failover_path_candidates(self):
469
        """Get failover paths to satisfy this EVC."""
470
        # in the future we can return primary/backup paths as well
471
        # we just have to properly handle link_up and failover paths
472
        # if (
473
        #     self.is_using_primary_path() and
474
        #     self.backup_path.status is EntityStatus.UP
475
        # ):
476
        #     yield self.backup_path
477 1
        return DynamicPathManager.get_disjoint_paths(self, self.current_path)
478
479 1
    def change_path(self):
480
        """Change EVC path."""
481
482 1
    def reprovision(self):
483
        """Force the EVC (re-)provisioning."""
484
485 1
    def is_affected_by_link(self, link):
486
        """Return True if this EVC has the given link on its current path."""
487 1
        return link in self.current_path
488
489 1
    def link_affected_by_interface(self, interface):
490
        """Return True if this EVC has the given link on its current path."""
491
        return self.current_path.link_affected_by_interface(interface)
492
493 1
    def is_backup_path_affected_by_link(self, link):
494
        """Return True if the backup path of this EVC uses the given link."""
495 1
        return link in self.backup_path
496
497
    # pylint: disable=invalid-name
498 1
    def is_primary_path_affected_by_link(self, link):
499
        """Return True if the primary path of this EVC uses the given link."""
500 1
        return link in self.primary_path
501
502 1
    def is_failover_path_affected_by_link(self, link):
503
        """Return True if this EVC has the given link on its failover path."""
504 1
        return link in self.failover_path
505
506 1
    def is_eligible_for_failover_path(self):
507
        """Verify if this EVC is eligible for failover path (EP029)"""
508
        # In the future this function can be augmented to consider
509
        # primary/backup, primary/dynamic, and other path combinations
510 1
        return (
511
            self.dynamic_backup_path and
512
            not self.primary_path and not self.backup_path
513
        )
514
515 1
    def is_using_primary_path(self):
516
        """Verify if the current deployed path is self.primary_path."""
517 1
        return self.primary_path and (self.current_path == self.primary_path)
518
519 1
    def is_using_backup_path(self):
520
        """Verify if the current deployed path is self.backup_path."""
521 1
        return self.backup_path and (self.current_path == self.backup_path)
522
523 1
    def is_using_dynamic_path(self):
524
        """Verify if the current deployed path is a dynamic path."""
525 1
        if (
526
            self.current_path
527
            and not self.is_using_primary_path()
528
            and not self.is_using_backup_path()
529
            and self.current_path.status == EntityStatus.UP
530
        ):
531
            return True
532 1
        return False
533
534 1
    def deploy_to_backup_path(self):
535
        """Deploy the backup path into the datapaths of this circuit.
536
537
        If the backup_path attribute is valid and up, this method will try to
538
        deploy this backup_path.
539
540
        If everything fails and dynamic_backup_path is True, then tries to
541
        deploy a dynamic path.
542
        """
543
        # TODO: Remove flows from current (cookies)
544 1
        if self.is_using_backup_path():
545
            # TODO: Log to say that cannot move backup to backup
546
            return True
547
548 1
        success = False
549 1
        if self.backup_path.status is EntityStatus.UP:
550 1
            success = self.deploy_to_path(self.backup_path)
551
552 1
        if success:
553 1
            return True
554
555 1
        if self.dynamic_backup_path or self.is_intra_switch():
556 1
            return self.deploy_to_path()
557
558
        return False
559
560 1
    def deploy_to_primary_path(self):
561
        """Deploy the primary path into the datapaths of this circuit.
562
563
        If the primary_path attribute is valid and up, this method will try to
564
        deploy this primary_path.
565
        """
566
        # TODO: Remove flows from current (cookies)
567 1
        if self.is_using_primary_path():
568
            # TODO: Log to say that cannot move primary to primary
569
            return True
570
571 1
        if self.primary_path.status is EntityStatus.UP:
572 1
            return self.deploy_to_path(self.primary_path)
573 1
        return False
574
575 1
    def deploy(self):
576
        """Deploy EVC to best path.
577
578
        Best path can be the primary path, if available. If not, the backup
579
        path, and, if it is also not available, a dynamic path.
580
        """
581 1
        if self.archived:
582 1
            return False
583 1
        self.enable()
584 1
        success = self.deploy_to_primary_path()
585 1
        if not success:
586 1
            success = self.deploy_to_backup_path()
587
588 1
        if success:
589 1
            emit_event(self._controller, "deployed",
590
                       content=map_evc_event_content(self))
591 1
        return success
592
593 1
    @staticmethod
594 1
    def get_path_status(path):
595
        """Check for the current status of a path.
596
597
        If any link in this path is down, the path is considered down.
598
        """
599 1
        if not path:
600 1
            return EntityStatus.DISABLED
601
602 1
        for link in path:
603 1
            if link.status is not EntityStatus.UP:
604 1
                return link.status
605 1
        return EntityStatus.UP
606
607
    #    def discover_new_path(self):
608
    #        # TODO: discover a new path to satisfy this circuit and deploy
609
610 1
    def remove(self):
611
        """Remove EVC path and disable it."""
612 1
        self.remove_current_flows()
613 1
        self.remove_failover_flows()
614 1
        self.disable()
615 1
        self.sync()
616 1
        emit_event(self._controller, "undeployed",
617
                   content=map_evc_event_content(self))
618
619 1
    def remove_failover_flows(self, exclude_uni_switches=True,
620
                              force=True, sync=True) -> None:
621
        """Remove failover_flows.
622
623
        By default, it'll exclude UNI switches, if mef_eline has already
624
        called remove_current_flows before then this minimizes the number
625
        of FlowMods and IO.
626
        """
627 1
        if not self.failover_path:
628 1
            return
629 1
        switches, cookie, excluded = OrderedDict(), self.get_cookie(), set()
630 1
        links = set()
631 1
        if exclude_uni_switches:
632 1
            excluded.add(self.uni_a.interface.switch.id)
633 1
            excluded.add(self.uni_z.interface.switch.id)
634 1
        for link in self.failover_path:
635 1
            if link.endpoint_a.switch.id not in excluded:
636 1
                switches[link.endpoint_a.switch.id] = link.endpoint_a.switch
637 1
                links.add(link)
638 1
            if link.endpoint_b.switch.id not in excluded:
639 1
                switches[link.endpoint_b.switch.id] = link.endpoint_b.switch
640 1
                links.add(link)
641 1
        for switch in switches.values():
642 1
            try:
643 1
                self._send_flow_mods(
644
                    switch.id,
645
                    [
646
                        {
647
                            "cookie": cookie,
648
                            "cookie_mask": int(0xffffffffffffffff),
649
                        }
650
                    ],
651
                    "delete",
652
                    force=force,
653
                )
654
            except FlowModException as err:
655
                log.error(
656
                    f"Error removing flows from switch {switch.id} for"
657
                    f"EVC {self}: {err}"
658
                )
659 1
        self.failover_path.make_vlans_available(self._controller)
660 1
        self.failover_path = Path([])
661 1
        if sync:
662 1
            self.sync()
663
664 1
    def remove_current_flows(self, current_path=None, force=True):
665
        """Remove all flows from current path."""
666 1
        switches = set()
667
668 1
        switches.add(self.uni_a.interface.switch)
669 1
        switches.add(self.uni_z.interface.switch)
670 1
        if not current_path:
671 1
            current_path = self.current_path
672 1
        for link in current_path:
673 1
            switches.add(link.endpoint_a.switch)
674 1
            switches.add(link.endpoint_b.switch)
675
676 1
        match = {
677
            "cookie": self.get_cookie(),
678
            "cookie_mask": int(0xffffffffffffffff)
679
        }
680
681 1
        for switch in switches:
682 1
            try:
683 1
                self._send_flow_mods(switch.id, [match], 'delete', force=force)
684 1
            except FlowModException as err:
685 1
                log.error(
686
                    f"Error removing flows from switch {switch.id} for"
687
                    f"EVC {self}: {err}"
688
                )
689
690 1
        current_path.make_vlans_available(self._controller)
691 1
        self.current_path = Path([])
692 1
        self.deactivate()
693 1
        self.sync()
694
695 1
    def remove_path_flows(self, path=None, force=True):
696
        """Remove all flows from path."""
697 1
        if not path:
698 1
            return
699
700 1
        dpid_flows_match = {}
701 1
        for dpid, flows in self._prepare_nni_flows(path).items():
702 1
            dpid_flows_match.setdefault(dpid, [])
703 1
            for flow in flows:
704 1
                dpid_flows_match[dpid].append({
705
                    "cookie": flow["cookie"],
706
                    "match": flow["match"],
707
                    "cookie_mask": int(0xffffffffffffffff)
708
                })
709 1
        for dpid, flows in self._prepare_uni_flows(path, skip_in=True).items():
710 1
            dpid_flows_match.setdefault(dpid, [])
711 1
            for flow in flows:
712 1
                dpid_flows_match[dpid].append({
713
                    "cookie": flow["cookie"],
714
                    "match": flow["match"],
715
                    "cookie_mask": int(0xffffffffffffffff)
716
                })
717
718 1
        for dpid, flows in dpid_flows_match.items():
719 1
            try:
720 1
                self._send_flow_mods(dpid, flows, 'delete', force=force)
721 1
            except FlowModException as err:
722 1
                log.error(
723
                    "Error removing failover flows: "
724
                    f"dpid={dpid} evc={self} error={err}"
725
                )
726
727 1
        path.make_vlans_available(self._controller)
728
729 1
    @staticmethod
730 1
    def links_zipped(path=None):
731
        """Return an iterator which yields pairs of links in order."""
732 1
        if not path:
733
            return []
734 1
        return zip(path[:-1], path[1:])
735
736 1
    def should_deploy(self, path=None):
737
        """Verify if the circuit should be deployed."""
738 1
        if not path:
739 1
            log.debug("Path is empty.")
740 1
            return False
741
742 1
        if not self.is_enabled():
743 1
            log.debug(f"{self} is disabled.")
744 1
            return False
745
746 1
        if not self.is_active():
747 1
            log.debug(f"{self} will be deployed.")
748 1
            return True
749
750 1
        return False
751
752 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
753
        """Install the flows for this circuit.
754
755
        Procedures to deploy:
756
757
        0. Remove current flows installed
758
        1. Decide if will deploy "path" or discover a new path
759
        2. Choose vlan
760
        3. Install NNI flows
761
        4. Install UNI flows
762
        5. Activate
763
        6. Update current_path
764
        7. Update links caches(primary, current, backup)
765
766
        """
767 1
        self.remove_current_flows()
768 1
        use_path = path
769 1
        if self.should_deploy(use_path):
770 1
            try:
771 1
                use_path.choose_vlans(self._controller)
772 1
            except KytosNoTagAvailableError:
773 1
                use_path = None
774
        else:
775 1
            for use_path in self.discover_new_paths():
776 1
                if use_path is None:
777
                    continue
778 1
                try:
779 1
                    use_path.choose_vlans(self._controller)
780 1
                    break
781 1
                except KytosNoTagAvailableError:
782 1
                    pass
783
            else:
784 1
                use_path = None
785
786 1
        try:
787 1
            if use_path:
788 1
                self._install_nni_flows(use_path)
789 1
                self._install_uni_flows(use_path)
790 1
            elif self.is_intra_switch():
791 1
                use_path = Path()
792 1
                self._install_direct_uni_flows()
793
            else:
794 1
                log.warning(
795
                    f"{self} was not deployed. No available path was found."
796
                )
797 1
                return False
798 1
        except FlowModException as err:
799 1
            log.error(
800
                f"Error deploying EVC {self} when calling flow_manager: {err}"
801
            )
802 1
            self.remove_current_flows(use_path)
803 1
            return False
804 1
        self.activate()
805 1
        self.current_path = use_path
806 1
        self.sync()
807 1
        log.info(f"{self} was deployed.")
808 1
        return True
809
810 1
    def setup_failover_path(self):
811
        """Install flows for the failover path of this EVC.
812
813
        Procedures to deploy:
814
815
        0. Remove flows currently installed for failover_path (if any)
816
        1. Discover a disjoint path from current_path
817
        2. Choose vlans
818
        3. Install NNI flows
819
        4. Install UNI egress flows
820
        5. Update failover_path
821
        """
822
        # Intra-switch EVCs have no failover_path
823 1
        if self.is_intra_switch():
824 1
            return False
825
826
        # For not only setup failover path for totally dynamic EVCs
827 1
        if not self.is_eligible_for_failover_path():
828 1
            return False
829
830 1
        reason = ""
831 1
        self.remove_path_flows(self.failover_path)
832 1
        for use_path in self.get_failover_path_candidates():
833 1
            if not use_path:
834 1
                continue
835 1
            try:
836 1
                use_path.choose_vlans(self._controller)
837 1
                break
838 1
            except KytosNoTagAvailableError:
839 1
                pass
840
        else:
841 1
            use_path = Path([])
842 1
            reason = "No available path was found"
843
844 1
        try:
845 1
            if use_path:
846 1
                self._install_nni_flows(use_path)
847 1
                self._install_uni_flows(use_path, skip_in=True)
848 1
        except FlowModException as err:
849 1
            reason = "Error deploying failover path"
850 1
            log.error(
851
                f"{reason} for {self}. FlowManager error: {err}"
852
            )
853 1
            self.remove_path_flows(use_path)
854 1
            use_path = Path([])
855
856 1
        self.failover_path = use_path
857 1
        self.sync()
858
859 1
        if not use_path:
860 1
            log.warning(
861
                f"Failover path for {self} was not deployed: {reason}"
862
            )
863 1
            return False
864 1
        log.info(f"Failover path for {self} was deployed.")
865 1
        return True
866
867 1
    def get_failover_flows(self):
868
        """Return the flows needed to make the failover path active, i.e. the
869
        flows for ingress forwarding.
870
871
        Return:
872
            dict: A dict of flows indexed by the switch_id will be returned, or
873
                an empty dict if no failover_path is available.
874
        """
875 1
        if not self.failover_path:
876 1
            return {}
877 1
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
878
879 1
    def _prepare_direct_uni_flows(self):
880
        """Prepare flows connecting two UNIs for intra-switch EVC."""
881 1
        vlan_a = self._get_value_from_uni_tag(self.uni_a)
882 1
        vlan_z = self._get_value_from_uni_tag(self.uni_z)
883
884 1
        flow_mod_az = self._prepare_flow_mod(
885
            self.uni_a.interface, self.uni_z.interface,
886
            self.queue_id, vlan_a
887
        )
888 1
        flow_mod_za = self._prepare_flow_mod(
889
            self.uni_z.interface, self.uni_a.interface,
890
            self.queue_id, vlan_z
891
        )
892
893 1
        if vlan_a is not None:
894 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
895
896 1
        if vlan_z is not None:
897 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
898
899 1
        if vlan_z not in self.special_cases:
900 1
            flow_mod_az["actions"].insert(
901
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
902
            )
903 1
            if not vlan_a:
904 1
                flow_mod_az["actions"].insert(
905
                    0, {"action_type": "push_vlan", "tag_type": "c"}
906
                )
907
908 1
        if vlan_a not in self.special_cases:
909 1
            flow_mod_za["actions"].insert(
910
                    0, {"action_type": "set_vlan", "vlan_id": vlan_a}
911
                )
912 1
            if not vlan_z:
913 1
                flow_mod_za["actions"].insert(
914
                    0, {"action_type": "push_vlan", "tag_type": "c"}
915
                )
916 1
            if vlan_z == 0:
917 1
                flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
918
919 1
        elif vlan_a == "4096/4096" and vlan_z == 0:
920 1
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
921
922 1
        elif vlan_a == 0 and vlan_z:
923 1
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
924
925 1
        return (
926
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
927
        )
928
929 1
    def _install_direct_uni_flows(self):
930
        """Install flows connecting two UNIs.
931
932
        This case happens when the circuit is between UNIs in the
933
        same switch.
934
        """
935 1
        (dpid, flows) = self._prepare_direct_uni_flows()
936 1
        self._send_flow_mods(dpid, flows)
937
938 1
    def _prepare_nni_flows(self, path=None):
939
        """Prepare NNI flows."""
940 1
        nni_flows = OrderedDict()
941 1
        previous = self.uni_a.interface.switch.dpid
942 1
        for incoming, outcoming in self.links_zipped(path):
943 1
            in_vlan = incoming.get_metadata("s_vlan").value
944 1
            out_vlan = outcoming.get_metadata("s_vlan").value
945 1
            in_endpoint = self.get_endpoint_by_id(incoming, previous, ne)
946 1
            out_endpoint = self.get_endpoint_by_id(
947
                outcoming, in_endpoint.switch.id, eq
948
            )
949
950 1
            flows = []
951
            # Flow for one direction
952 1
            flows.append(
953
                self._prepare_nni_flow(
954
                    in_endpoint,
955
                    out_endpoint,
956
                    in_vlan,
957
                    out_vlan,
958
                    queue_id=self.queue_id,
959
                )
960
            )
961
962
            # Flow for the other direction
963 1
            flows.append(
964
                self._prepare_nni_flow(
965
                    out_endpoint,
966
                    in_endpoint,
967
                    out_vlan,
968
                    in_vlan,
969
                    queue_id=self.queue_id,
970
                )
971
            )
972 1
            previous = in_endpoint.switch.id
973 1
            nni_flows[in_endpoint.switch.id] = flows
974 1
        return nni_flows
975
976 1
    def _install_nni_flows(self, path=None):
977
        """Install NNI flows."""
978 1
        for dpid, flows in self._prepare_nni_flows(path).items():
979 1
            self._send_flow_mods(dpid, flows)
980
981 1
    @staticmethod
982 1
    def _get_value_from_uni_tag(uni):
983
        """Returns the value from tag. In case of any and untagged
984
        it should return 4096/4096 and 0 respectively"""
985 1
        special = {"any": "4096/4096", "untagged": 0}
986
987 1
        if uni.user_tag:
988 1
            value = uni.user_tag.value
989 1
            return special.get(value, value)
990
        return None
991
992 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
993
        """Prepare flows to install UNIs."""
994 1
        uni_flows = {}
995 1
        if not path:
996 1
            log.info("install uni flows without path.")
997 1
            return uni_flows
998
999
        # Determine VLANs
1000 1
        in_vlan_a = self._get_value_from_uni_tag(self.uni_a)
1001 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
1002
1003 1
        in_vlan_z = self._get_value_from_uni_tag(self.uni_z)
1004 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
1005
1006
        # Get endpoints from path
1007 1
        endpoint_a = self.get_endpoint_by_id(
1008
            path[0], self.uni_a.interface.switch.id, eq
1009
        )
1010 1
        endpoint_z = self.get_endpoint_by_id(
1011
            path[-1], self.uni_z.interface.switch.id, eq
1012
        )
1013
1014
        # Flows for the first UNI
1015 1
        flows_a = []
1016
1017
        # Flow for one direction, pushing the service tag
1018 1
        if not skip_in:
1019 1
            push_flow = self._prepare_push_flow(
1020
                self.uni_a.interface,
1021
                endpoint_a,
1022
                in_vlan_a,
1023
                out_vlan_a,
1024
                in_vlan_z,
1025
                queue_id=self.queue_id,
1026
            )
1027 1
            flows_a.append(push_flow)
1028
1029
        # Flow for the other direction, popping the service tag
1030 1
        if not skip_out:
1031 1
            pop_flow = self._prepare_pop_flow(
1032
                endpoint_a,
1033
                self.uni_a.interface,
1034
                out_vlan_a,
1035
                queue_id=self.queue_id,
1036
            )
1037 1
            flows_a.append(pop_flow)
1038
1039 1
        uni_flows[self.uni_a.interface.switch.id] = flows_a
1040
1041
        # Flows for the second UNI
1042 1
        flows_z = []
1043
1044
        # Flow for one direction, pushing the service tag
1045 1
        if not skip_in:
1046 1
            push_flow = self._prepare_push_flow(
1047
                self.uni_z.interface,
1048
                endpoint_z,
1049
                in_vlan_z,
1050
                out_vlan_z,
1051
                in_vlan_a,
1052
                queue_id=self.queue_id,
1053
            )
1054 1
            flows_z.append(push_flow)
1055
1056
        # Flow for the other direction, popping the service tag
1057 1
        if not skip_out:
1058 1
            pop_flow = self._prepare_pop_flow(
1059
                endpoint_z,
1060
                self.uni_z.interface,
1061
                out_vlan_z,
1062
                queue_id=self.queue_id,
1063
            )
1064 1
            flows_z.append(pop_flow)
1065
1066 1
        uni_flows[self.uni_z.interface.switch.id] = flows_z
1067
1068 1
        return uni_flows
1069
1070 1
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
1071
        """Install UNI flows."""
1072 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
1073
1074 1
        for (dpid, flows) in uni_flows.items():
1075 1
            self._send_flow_mods(dpid, flows)
1076
1077 1
    @staticmethod
1078 1
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
1079
        """Send a flow_mod list to a specific switch.
1080
1081
        Args:
1082
            dpid(str): The target of flows (i.e. Switch.id).
1083
            flow_mods(dict): Python dictionary with flow_mods.
1084
            command(str): By default is 'flows'. To remove a flow is 'remove'.
1085
            force(bool): True to send via consistency check in case of errors
1086
1087
        """
1088
1089 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
1090
1091 1
        data = {"flows": flow_mods, "force": force}
1092 1
        response = requests.post(endpoint, json=data)
1093 1
        if response.status_code >= 400:
1094 1
            raise FlowModException(str(response.text))
1095
1096 1
    def get_cookie(self):
1097
        """Return the cookie integer from evc id."""
1098 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
1099
1100 1
    @staticmethod
1101 1
    def get_id_from_cookie(cookie):
1102
        """Return the evc id given a cookie value."""
1103 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
1104 1
        return f"{evc_id:x}".zfill(14)
1105
1106 1
    def set_flow_table_group_id(self, flow_mod: dict, vlan) -> dict:
1107
        """Set table_group and table_id"""
1108 1
        table_group = "epl" if vlan is None else "evpl"
1109 1
        flow_mod["table_group"] = table_group
1110 1
        flow_mod["table_id"] = self.table_group[table_group]
1111 1
        return flow_mod
1112
1113 1
    @staticmethod
1114 1
    def get_priority(vlan):
1115
        """Return priority value depending on vlan value"""
1116 1
        if vlan not in {None, "4096/4096", 0}:
1117 1
            return settings.EVPL_SB_PRIORITY
1118 1
        if vlan == 0:
1119 1
            return settings.UNTAGGED_SB_PRIORITY
1120 1
        if vlan == "4096/4096":
1121 1
            return settings.ANY_SB_PRIORITY
1122 1
        return settings.EPL_SB_PRIORITY
1123
1124 1
    def _prepare_flow_mod(self, in_interface, out_interface,
1125
                          queue_id=None, vlan=True):
1126
        """Prepare a common flow mod."""
1127 1
        default_actions = [
1128
            {"action_type": "output", "port": out_interface.port_number}
1129
        ]
1130 1
        queue_id = settings.QUEUE_ID if queue_id == -1 else queue_id
1131 1
        if queue_id is not None:
1132
            default_actions.append(
1133
                {"action_type": "set_queue", "queue_id": queue_id}
1134
            )
1135
1136 1
        flow_mod = {
1137
            "match": {"in_port": in_interface.port_number},
1138
            "cookie": self.get_cookie(),
1139
            "actions": default_actions,
1140
            "owner": "mef_eline",
1141
        }
1142
1143 1
        self.set_flow_table_group_id(flow_mod, vlan)
1144 1
        if self.sb_priority:
1145
            flow_mod["priority"] = self.sb_priority
1146
        else:
1147 1
            flow_mod["priority"] = self.get_priority(vlan)
1148 1
        return flow_mod
1149
1150 1
    def _prepare_nni_flow(self, *args, queue_id=None):
1151
        """Create NNI flows."""
1152 1
        in_interface, out_interface, in_vlan, out_vlan = args
1153 1
        flow_mod = self._prepare_flow_mod(
1154
            in_interface, out_interface, queue_id
1155
        )
1156 1
        flow_mod["match"]["dl_vlan"] = in_vlan
1157 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1158 1
        flow_mod["actions"].insert(0, new_action)
1159
1160 1
        return flow_mod
1161
1162 1
    def _prepare_push_flow(self, *args, queue_id=None):
1163
        """Prepare push flow.
1164
1165
        Arguments:
1166
            in_interface(str): Interface input.
1167
            out_interface(str): Interface output.
1168
            in_vlan(str): Vlan input.
1169
            out_vlan(str): Vlan output.
1170
            new_c_vlan(str): New client vlan.
1171
1172
        Return:
1173
            dict: An python dictionary representing a FlowMod
1174
1175
        """
1176
        # assign all arguments
1177 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
1178 1
        flow_mod = self._prepare_flow_mod(
1179
            in_interface, out_interface, queue_id, in_vlan
1180
        )
1181
        # the service tag must be always pushed
1182 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1183 1
        flow_mod["actions"].insert(0, new_action)
1184
1185 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
1186 1
        flow_mod["actions"].insert(0, new_action)
1187
1188 1
        if in_vlan is not None:
1189
            # if in_vlan is set, it must be included in the match
1190 1
            flow_mod["match"]["dl_vlan"] = in_vlan
1191
1192 1
        if new_c_vlan not in self.special_cases:
1193
            # new_in_vlan is an integer but zero, action to set is required
1194 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
1195 1
            flow_mod["actions"].insert(0, new_action)
1196
1197 1
        if in_vlan not in self.special_cases and new_c_vlan == 0:
1198
            # # new_in_vlan is an integer but zero and new_c_vlan does not
1199
            # a pop action is required
1200 1
            new_action = {"action_type": "pop_vlan"}
1201 1
            flow_mod["actions"].insert(0, new_action)
1202
1203 1
        elif in_vlan == "4096/4096" and new_c_vlan == 0:
1204
            # if in_vlan match with any tags and new_c_vlan does not
1205
            # a pop action is required
1206 1
            new_action = {"action_type": "pop_vlan"}
1207 1
            flow_mod["actions"].insert(0, new_action)
1208
1209 1
        elif not in_vlan and new_c_vlan not in self.special_cases:
1210
            # new_in_vlan is an integer but zero and in_vlan is not set
1211
            # then it is set now
1212 1
            new_action = {"action_type": "push_vlan", "tag_type": "c"}
1213 1
            flow_mod["actions"].insert(0, new_action)
1214
1215 1
        return flow_mod
1216
1217 1
    def _prepare_pop_flow(
1218
        self, in_interface, out_interface, out_vlan, queue_id=None
1219
    ):
1220
        # pylint: disable=too-many-arguments
1221
        """Prepare pop flow."""
1222 1
        flow_mod = self._prepare_flow_mod(
1223
            in_interface, out_interface, queue_id
1224
        )
1225 1
        flow_mod["match"]["dl_vlan"] = out_vlan
1226 1
        new_action = {"action_type": "pop_vlan"}
1227 1
        flow_mod["actions"].insert(0, new_action)
1228 1
        return flow_mod
1229
1230 1
    @staticmethod
1231 1
    def run_bulk_sdntraces(uni_list):
1232
        """Run SDN traces on control plane starting from EVC UNIs."""
1233 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/traces"
1234 1
        data = []
1235 1
        for uni in uni_list:
1236 1
            data_uni = {
1237
                "trace": {
1238
                            "switch": {
1239
                                "dpid": uni.interface.switch.dpid,
1240
                                "in_port": uni.interface.port_number,
1241
                            }
1242
                        }
1243
                }
1244 1
            if uni.user_tag:
1245 1
                uni_dl_vlan = map_dl_vlan(uni.user_tag.value)
1246 1
                if uni_dl_vlan:
1247 1
                    data_uni["trace"]["eth"] = {
1248
                                            "dl_type": 0x8100,
1249
                                            "dl_vlan": uni_dl_vlan,
1250
                                            }
1251 1
            data.append(data_uni)
1252 1
        try:
1253 1
            response = requests.put(endpoint, json=data, timeout=30)
1254
        except Timeout as exception:
1255
            log.error(f"Request has timed out: {exception}")
1256
            return {"result": []}
1257 1
        if response.status_code >= 400:
1258 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1259 1
            return {"result": []}
1260 1
        return response.json()
1261
1262
    # pylint: disable=too-many-return-statements
1263 1
    @staticmethod
1264 1
    def check_trace(circuit, trace_a, trace_z):
1265
        """Auxiliar function to check an individual trace"""
1266 1
        if (
1267
            len(trace_a) != len(circuit.current_path) + 1
1268
            or not compare_uni_out_trace(circuit.uni_z, trace_a[-1])
1269
        ):
1270 1
            log.warning(f"Invalid trace from uni_a: {trace_a}")
1271 1
            return False
1272 1
        if (
1273
            len(trace_z) != len(circuit.current_path) + 1
1274
            or not compare_uni_out_trace(circuit.uni_a, trace_z[-1])
1275
        ):
1276 1
            log.warning(f"Invalid trace from uni_z: {trace_z}")
1277 1
            return False
1278
1279 1
        for link, trace1, trace2 in zip(circuit.current_path,
1280
                                        trace_a[1:],
1281
                                        trace_z[:0:-1]):
1282 1
            metadata_vlan = None
1283 1
            if link.metadata:
1284 1
                metadata_vlan = glom(link.metadata, 's_vlan.value')
1285 1
            if compare_endpoint_trace(
1286
                                        link.endpoint_a,
1287
                                        metadata_vlan,
1288
                                        trace2
1289
                                    ) is False:
1290 1
                log.warning(f"Invalid trace from uni_a: {trace_a}")
1291 1
                return False
1292 1
            if compare_endpoint_trace(
1293
                                        link.endpoint_b,
1294
                                        metadata_vlan,
1295
                                        trace1
1296
                                    ) is False:
1297 1
                log.warning(f"Invalid trace from uni_z: {trace_z}")
1298 1
                return False
1299
1300 1
        return True
1301
1302 1
    @staticmethod
1303 1
    def check_list_traces(list_circuits):
1304
        """Check if current_path is deployed comparing with SDN traces."""
1305 1
        if not list_circuits:
1306
            return {}
1307 1
        uni_list = []
1308 1
        for circuit in list_circuits:
1309 1
            uni_list.append(circuit.uni_a)
1310 1
            uni_list.append(circuit.uni_z)
1311
1312 1
        traces = EVCDeploy.run_bulk_sdntraces(uni_list)
1313 1
        traces = traces["result"]
1314 1
        circuits_checked = {}
1315 1
        if not traces:
1316
            return circuits_checked
1317
1318 1
        try:
1319 1
            for i, circuit in enumerate(list_circuits):
1320 1
                trace_a = traces[2*i]
1321 1
                trace_z = traces[2*i+1]
1322 1
                circuits_checked[circuit.id] = EVCDeploy.check_trace(
1323
                        circuit, trace_a, trace_z
1324
                    )
1325
        except IndexError as err:
1326
            log.error(
1327
                f"Bulk sdntraces returned fewer items than expected."
1328
                f"Error = {err}"
1329
            )
1330
1331 1
        return circuits_checked
1332
1333 1
    @staticmethod
1334 1
    def get_endpoint_by_id(
1335
        link: Link,
1336
        id_: str,
1337
        operator: Union[eq, ne]
1338
    ) -> Interface:
1339
        """Return endpoint from link
1340
        either equal(eq) or not equal(ne) to id"""
1341 1
        if operator(link.endpoint_a.switch.id, id_):
1342 1
            return link.endpoint_a
1343 1
        return link.endpoint_b
1344
1345
1346 1
class LinkProtection(EVCDeploy):
1347
    """Class to handle link protection."""
1348
1349 1
    def is_affected_by_link(self, link=None):
1350
        """Verify if the current path is affected by link down event."""
1351
        return self.current_path.is_affected_by_link(link)
1352
1353 1
    def is_using_primary_path(self):
1354
        """Verify if the current deployed path is self.primary_path."""
1355 1
        return self.current_path == self.primary_path
1356
1357 1
    def is_using_backup_path(self):
1358
        """Verify if the current deployed path is self.backup_path."""
1359 1
        return self.current_path == self.backup_path
1360
1361 1
    def is_using_dynamic_path(self):
1362
        """Verify if the current deployed path is dynamic."""
1363 1
        if (
1364
            self.current_path
1365
            and not self.is_using_primary_path()
1366
            and not self.is_using_backup_path()
1367
            and self.current_path.status is EntityStatus.UP
1368
        ):
1369
            return True
1370 1
        return False
1371
1372 1
    def deploy_to(self, path_name=None, path=None):
1373
        """Create a deploy to path."""
1374 1
        if self.current_path == path:
1375 1
            log.debug(f"{path_name} is equal to current_path.")
1376 1
            return True
1377
1378 1
        if path.status is EntityStatus.UP:
1379 1
            return self.deploy_to_path(path)
1380
1381 1
        return False
1382
1383 1
    def handle_link_up(self, link):
1384
        """Handle circuit when link up.
1385
1386
        Args:
1387
            link(Link): Link affected by link.up event.
1388
1389
        """
1390 1
        if self.is_intra_switch():
1391
            return True
1392
1393 1
        if self.is_using_primary_path():
1394 1
            return True
1395
1396 1
        success = False
1397 1
        if self.primary_path.is_affected_by_link(link):
1398 1
            success = self.deploy_to_primary_path()
1399
1400 1
        if success:
1401 1
            return True
1402
1403
        # We tried to deploy(primary_path) without success.
1404
        # And in this case is up by some how. Nothing to do.
1405 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1406 1
            return True
1407
1408
        # In this case, probably the circuit is not being used and
1409
        # we can move to backup
1410 1
        if self.backup_path.is_affected_by_link(link):
1411 1
            success = self.deploy_to_backup_path()
1412
1413
        # In this case, the circuit is not being used and we should
1414
        # try a dynamic path
1415 1
        if not success and self.dynamic_backup_path:
1416 1
            success = self.deploy_to_path()
1417
1418 1
        if success:
1419 1
            emit_event(self._controller, "redeployed_link_up",
1420
                       content=map_evc_event_content(self))
1421 1
            return True
1422
1423 1
        return True
1424
1425 1
    def handle_link_down(self):
1426
        """Handle circuit when link down.
1427
1428
        Returns:
1429
            bool: True if the re-deploy was successly otherwise False.
1430
1431
        """
1432 1
        success = False
1433 1
        if self.is_using_primary_path():
1434 1
            success = self.deploy_to_backup_path()
1435 1
        elif self.is_using_backup_path():
1436 1
            success = self.deploy_to_primary_path()
1437
1438 1
        if not success and self.dynamic_backup_path:
1439 1
            success = self.deploy_to_path()
1440
1441 1
        if success:
1442 1
            log.debug(f"{self} deployed after link down.")
1443
        else:
1444 1
            self.deactivate()
1445 1
            self.current_path = Path([])
1446 1
            self.sync()
1447 1
            log.debug(f"Failed to re-deploy {self} after link down.")
1448
1449 1
        return success
1450
1451 1
    @staticmethod
1452 1
    def get_interface_from_switch(uni: UNI, switches: dict) -> Interface:
1453
        """Get interface from switch by uni"""
1454 1
        switch = switches[uni.interface.switch.dpid]
1455 1
        interface = switch.interfaces[uni.interface.port_number]
1456 1
        return interface
1457
1458 1
    def handle_topology_update(self, switches: dict):
1459
        """Handle changes in the topology"""
1460
        # All intra-switch EVCs do not have current_path.
1461
        # In case of inter-switch EVC and not current_path,
1462
        # link_down should take care of deactivation.
1463 1
        if not self.is_intra_switch and not self.current_path:
1464
            return
1465 1
        try:
1466 1
            interface_a = self.get_interface_from_switch(self.uni_a, switches)
1467 1
        except KeyError:
1468 1
            id_ = self.uni_a.interface.id
1469 1
            log.warning(f"The interface {id_} was not found")
1470 1
            return
1471
1472 1
        try:
1473 1
            interface_z = self.get_interface_from_switch(self.uni_z, switches)
1474
        except KeyError:
1475
            id_ = self.uni_z.interface.id
1476
            log.warning(f"The interface {id_} was not found")
1477
            return
1478
1479 1
        active, interfaces = self.is_uni_interface_active(
1480
            interface_a, interface_z
1481
        )
1482 1
        if self.is_active() != active:
1483 1
            if active:
1484 1
                self.activate()
1485 1
                log.info(f"Activating EVC {self.id}. Interfaces: "
1486
                         f"{interfaces}.")
1487
            else:
1488 1
                self.deactivate()
1489 1
                log.info(f"Deactivating EVC {self.id}. Interfaces: "
1490
                         f"{interfaces}.")
1491 1
            self.sync()
1492
1493 1
    def are_unis_active(self, switches: dict) -> bool:
1494
        """Determine whether this EVC should be active"""
1495 1
        interface_a = self.get_interface_from_switch(self.uni_a, switches)
1496 1
        interface_z = self.get_interface_from_switch(self.uni_z, switches)
1497 1
        active, _ = self.is_uni_interface_active(interface_a, interface_z)
1498 1
        return active
1499
1500 1
    @staticmethod
1501 1
    def is_uni_interface_active(
1502
        interface_a: Interface,
1503
        interface_z: Interface
1504
    ) -> tuple[bool, dict]:
1505
        """Determine whether a UNI should be active"""
1506 1
        active = True
1507 1
        interfaces = {}
1508 1
        interface_a_dict = {
1509
            "status": interface_a.status.value,
1510
            "status_reason": interface_a.status_reason
1511
        }
1512 1
        interface_z_dict = {
1513
            "status": interface_z.status.value,
1514
            "status_reason": interface_z.status_reason
1515
        }
1516 1
        if (interface_a.status != EntityStatus.UP
1517
                or interface_a.status_reason != set()):
1518 1
            active = False
1519 1
            interfaces[interface_a.id] = interface_a_dict
1520 1
        if (interface_z.status != EntityStatus.UP
1521
                or interface_z.status_reason != set()):
1522 1
            active = False
1523 1
            interfaces[interface_z.id] = interface_z_dict
1524 1
        if active:
1525 1
            interfaces[interface_a.id] = interface_a_dict
1526 1
            interfaces[interface_z.id] = interface_z_dict
1527 1
        return active, interfaces
1528
1529
1530 1
class EVC(LinkProtection):
1531
    """Class that represents a E-Line Virtual Connection."""
1532