Passed
Push — master ( fa6907...6c74fb )
by Vinicius
02:48 queued 15s
created

LinkProtection.is_affected_by_link()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

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