Passed
Pull Request — master (#375)
by Italo Valcy
04:00
created

build.models.evc.EVCDeploy.run_bulk_sdntraces()   B

Complexity

Conditions 6

Size

Total Lines 31
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6.1215

Importance

Changes 0
Metric Value
cc 6
eloc 26
nop 1
dl 0
loc 31
ccs 17
cts 20
cp 0.85
crap 6.1215
rs 8.3226
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 1
        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
654 1
        try:
655 1
            nni_flows = self._prepare_nni_flows(path)
656
        # pylint: disable=broad-except
657
        except Exception as err:
658
            log.error(f"Fail to remove NNI failover flows for {self}: {err}")
659
            nni_flows = {}
660
661 1
        for dpid, flows in nni_flows.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
        try:
671 1
            uni_flows = self._prepare_uni_flows(path, skip_in=True)
672
        # pylint: disable=broad-except
673
        except Exception as err:
674
            log.error(f"Fail to remove UNI failover flows for {self}: {err}")
675
            uni_flows = {}
676
677 1
        for dpid, flows in uni_flows.items():
678 1
            dpid_flows_match.setdefault(dpid, [])
679 1
            for flow in flows:
680 1
                dpid_flows_match[dpid].append({
681
                    "cookie": flow["cookie"],
682
                    "match": flow["match"],
683
                    "cookie_mask": int(0xffffffffffffffff)
684
                })
685
686 1
        for dpid, flows in dpid_flows_match.items():
687 1
            try:
688 1
                self._send_flow_mods(dpid, flows, 'delete', force=force)
689 1
            except FlowModException as err:
690 1
                log.error(
691
                    "Error removing failover flows: "
692
                    f"dpid={dpid} evc={self} error={err}"
693
                )
694
695 1
        path.make_vlans_available()
696 1
        for link in path:
697 1
            notify_link_available_tags(self._controller, link)
698
699 1
    @staticmethod
700 1
    def links_zipped(path=None):
701
        """Return an iterator which yields pairs of links in order."""
702 1
        if not path:
703
            return []
704 1
        return zip(path[:-1], path[1:])
705
706 1
    def should_deploy(self, path=None):
707
        """Verify if the circuit should be deployed."""
708 1
        if not path:
709 1
            log.debug("Path is empty.")
710 1
            return False
711
712 1
        if not self.is_enabled():
713 1
            log.debug(f"{self} is disabled.")
714 1
            return False
715
716 1
        if not self.is_active():
717 1
            log.debug(f"{self} will be deployed.")
718 1
            return True
719
720 1
        return False
721
722 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
723
        """Install the flows for this circuit.
724
725
        Procedures to deploy:
726
727
        0. Remove current flows installed
728
        1. Decide if will deploy "path" or discover a new path
729
        2. Choose vlan
730
        3. Install NNI flows
731
        4. Install UNI flows
732
        5. Activate
733
        6. Update current_path
734
        7. Update links caches(primary, current, backup)
735
736
        """
737 1
        self.remove_current_flows()
738 1
        use_path = path
739 1
        if self.should_deploy(use_path):
740 1
            try:
741 1
                use_path.choose_vlans()
742 1
                for link in use_path:
743 1
                    notify_link_available_tags(self._controller, link)
744 1
            except KytosNoTagAvailableError:
745 1
                use_path = None
746
        else:
747 1
            for use_path in self.discover_new_paths():
748 1
                if use_path is None:
749
                    continue
750 1
                try:
751 1
                    use_path.choose_vlans()
752 1
                    for link in use_path:
753 1
                        notify_link_available_tags(self._controller, link)
754 1
                    break
755 1
                except KytosNoTagAvailableError:
756 1
                    pass
757
            else:
758 1
                use_path = None
759
760 1
        try:
761 1
            if use_path:
762 1
                self._install_nni_flows(use_path)
763 1
                self._install_uni_flows(use_path)
764 1
            elif self.is_intra_switch():
765 1
                use_path = Path()
766 1
                self._install_direct_uni_flows()
767
            else:
768 1
                log.warning(
769
                    f"{self} was not deployed. " "No available path was found."
770
                )
771 1
                return False
772 1
        except FlowModException as err:
773 1
            log.error(
774
                f"Error deploying EVC {self} when calling flow_manager: {err}"
775
            )
776 1
            self.remove_current_flows(use_path)
777 1
            return False
778 1
        self.activate()
779 1
        self.current_path = use_path
780 1
        self.sync()
781 1
        log.info(f"{self} was deployed.")
782 1
        return True
783
784 1
    def setup_failover_path(self):
785
        """Install flows for the failover path of this EVC.
786
787
        Procedures to deploy:
788
789
        0. Remove flows currently installed for failover_path (if any)
790
        1. Discover a disjoint path from current_path
791
        2. Choose vlans
792
        3. Install NNI flows
793
        4. Install UNI egress flows
794
        5. Update failover_path
795
        """
796
        # Intra-switch EVCs have no failover_path
797 1
        if self.is_intra_switch():
798 1
            return False
799
800
        # For not only setup failover path for totally dynamic EVCs
801 1
        if not self.is_eligible_for_failover_path():
802 1
            return False
803
804 1
        reason = ""
805 1
        self.remove_path_flows(self.failover_path)
806 1
        self.failover_path = Path([])
807 1
        for use_path in self.get_failover_path_candidates():
808 1
            if not use_path:
809 1
                continue
810 1
            try:
811 1
                use_path.choose_vlans()
812 1
                for link in use_path:
813 1
                    notify_link_available_tags(self._controller, link)
814 1
                break
815 1
            except KytosNoTagAvailableError:
816 1
                pass
817
        else:
818 1
            use_path = Path([])
819 1
            reason = "No available path was found"
820
821 1
        try:
822 1
            if use_path:
823 1
                self._install_nni_flows(use_path)
824 1
                self._install_uni_flows(use_path, skip_in=True)
825 1
        except FlowModException as err:
826 1
            reason = "Error deploying failover path"
827 1
            log.error(
828
                f"{reason} for {self}. FlowManager error: {err}"
829
            )
830 1
            self.remove_path_flows(use_path)
831 1
            use_path = Path([])
832
833 1
        self.failover_path = use_path
834 1
        self.sync()
835
836 1
        if not use_path:
837 1
            log.warning(
838
                f"Failover path for {self} was not deployed: {reason}"
839
            )
840 1
            return False
841 1
        log.info(f"Failover path for {self} was deployed.")
842 1
        return True
843
844 1
    def get_failover_flows(self):
845
        """Return the flows needed to make the failover path active, i.e. the
846
        flows for ingress forwarding.
847
848
        Return:
849
            dict: A dict of flows indexed by the switch_id will be returned, or
850
                an empty dict if no failover_path is available.
851
        """
852 1
        if not self.failover_path:
853 1
            return {}
854 1
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
855
856 1
    def _prepare_direct_uni_flows(self):
857
        """Prepare flows connecting two UNIs for intra-switch EVC."""
858 1
        vlan_a = self._get_value_from_uni_tag(self.uni_a)
859 1
        vlan_z = self._get_value_from_uni_tag(self.uni_z)
860
861 1
        flow_mod_az = self._prepare_flow_mod(
862
            self.uni_a.interface, self.uni_z.interface,
863
            self.queue_id, vlan_a
864
        )
865 1
        flow_mod_za = self._prepare_flow_mod(
866
            self.uni_z.interface, self.uni_a.interface,
867
            self.queue_id, vlan_z
868
        )
869
870 1
        if vlan_a is not None:
871 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
872
873 1
        if vlan_z is not None:
874 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
875
876 1
        if vlan_z not in self.special_cases:
877 1
            flow_mod_az["actions"].insert(
878
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
879
            )
880 1
            if not vlan_a:
881 1
                flow_mod_az["actions"].insert(
882
                    0, {"action_type": "push_vlan", "tag_type": "c"}
883
                )
884
885 1
        if vlan_a not in self.special_cases:
886 1
            flow_mod_za["actions"].insert(
887
                    0, {"action_type": "set_vlan", "vlan_id": vlan_a}
888
                )
889 1
            if not vlan_z:
890 1
                flow_mod_za["actions"].insert(
891
                    0, {"action_type": "push_vlan", "tag_type": "c"}
892
                )
893 1
            if vlan_z == 0:
894 1
                flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
895
896 1
        elif vlan_a == "4096/4096" and vlan_z == 0:
897 1
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
898
899 1
        elif vlan_a == 0 and vlan_z:
900 1
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
901
902 1
        return (
903
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
904
        )
905
906 1
    def _install_direct_uni_flows(self):
907
        """Install flows connecting two UNIs.
908
909
        This case happens when the circuit is between UNIs in the
910
        same switch.
911
        """
912 1
        (dpid, flows) = self._prepare_direct_uni_flows()
913 1
        self._send_flow_mods(dpid, flows)
914
915 1
    def _prepare_nni_flows(self, path=None):
916
        """Prepare NNI flows."""
917 1
        nni_flows = OrderedDict()
918 1
        previous = self.uni_a.interface.switch.dpid
919 1
        for incoming, outcoming in self.links_zipped(path):
920 1
            in_vlan = incoming.get_metadata("s_vlan").value
921 1
            out_vlan = outcoming.get_metadata("s_vlan").value
922 1
            in_endpoint = self.get_endpoint_by_id(incoming, previous, ne)
923 1
            out_endpoint = self.get_endpoint_by_id(
924
                outcoming, in_endpoint.switch.id, eq
925
            )
926
927 1
            flows = []
928
            # Flow for one direction
929 1
            flows.append(
930
                self._prepare_nni_flow(
931
                    in_endpoint,
932
                    out_endpoint,
933
                    in_vlan,
934
                    out_vlan,
935
                    queue_id=self.queue_id,
936
                )
937
            )
938
939
            # Flow for the other direction
940 1
            flows.append(
941
                self._prepare_nni_flow(
942
                    out_endpoint,
943
                    in_endpoint,
944
                    out_vlan,
945
                    in_vlan,
946
                    queue_id=self.queue_id,
947
                )
948
            )
949 1
            previous = in_endpoint.switch.id
950 1
            nni_flows[in_endpoint.switch.id] = flows
951 1
        return nni_flows
952
953 1
    def _install_nni_flows(self, path=None):
954
        """Install NNI flows."""
955 1
        for dpid, flows in self._prepare_nni_flows(path).items():
956 1
            self._send_flow_mods(dpid, flows)
957
958 1
    @staticmethod
959 1
    def _get_value_from_uni_tag(uni):
960
        """Returns the value from tag. In case of any and untagged
961
        it should return 4096/4096 and 0 respectively"""
962 1
        special = {"any": "4096/4096", "untagged": 0}
963
964 1
        if uni.user_tag:
965 1
            value = uni.user_tag.value
966 1
            return special.get(value, value)
967
        return None
968
969 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
970
        """Prepare flows to install UNIs."""
971 1
        uni_flows = {}
972 1
        if not path:
973 1
            log.info("install uni flows without path.")
974 1
            return uni_flows
975
976
        # Determine VLANs
977 1
        in_vlan_a = self._get_value_from_uni_tag(self.uni_a)
978 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
979
980 1
        in_vlan_z = self._get_value_from_uni_tag(self.uni_z)
981 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
982
983
        # Get endpoints from path
984 1
        endpoint_a = self.get_endpoint_by_id(
985
            path[0], self.uni_a.interface.switch.id, eq
986
        )
987 1
        endpoint_z = self.get_endpoint_by_id(
988
            path[-1], self.uni_z.interface.switch.id, eq
989
        )
990
991
        # Flows for the first UNI
992 1
        flows_a = []
993
994
        # Flow for one direction, pushing the service tag
995 1
        if not skip_in:
996 1
            push_flow = self._prepare_push_flow(
997
                self.uni_a.interface,
998
                endpoint_a,
999
                in_vlan_a,
1000
                out_vlan_a,
1001
                in_vlan_z,
1002
                queue_id=self.queue_id,
1003
            )
1004 1
            flows_a.append(push_flow)
1005
1006
        # Flow for the other direction, popping the service tag
1007 1
        if not skip_out:
1008 1
            pop_flow = self._prepare_pop_flow(
1009
                endpoint_a,
1010
                self.uni_a.interface,
1011
                out_vlan_a,
1012
                queue_id=self.queue_id,
1013
            )
1014 1
            flows_a.append(pop_flow)
1015
1016 1
        uni_flows[self.uni_a.interface.switch.id] = flows_a
1017
1018
        # Flows for the second UNI
1019 1
        flows_z = []
1020
1021
        # Flow for one direction, pushing the service tag
1022 1
        if not skip_in:
1023 1
            push_flow = self._prepare_push_flow(
1024
                self.uni_z.interface,
1025
                endpoint_z,
1026
                in_vlan_z,
1027
                out_vlan_z,
1028
                in_vlan_a,
1029
                queue_id=self.queue_id,
1030
            )
1031 1
            flows_z.append(push_flow)
1032
1033
        # Flow for the other direction, popping the service tag
1034 1
        if not skip_out:
1035 1
            pop_flow = self._prepare_pop_flow(
1036
                endpoint_z,
1037
                self.uni_z.interface,
1038
                out_vlan_z,
1039
                queue_id=self.queue_id,
1040
            )
1041 1
            flows_z.append(pop_flow)
1042
1043 1
        uni_flows[self.uni_z.interface.switch.id] = flows_z
1044
1045 1
        return uni_flows
1046
1047 1
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
1048
        """Install UNI flows."""
1049 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
1050
1051 1
        for (dpid, flows) in uni_flows.items():
1052 1
            self._send_flow_mods(dpid, flows)
1053
1054 1
    @staticmethod
1055 1
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
1056
        """Send a flow_mod list to a specific switch.
1057
1058
        Args:
1059
            dpid(str): The target of flows (i.e. Switch.id).
1060
            flow_mods(dict): Python dictionary with flow_mods.
1061
            command(str): By default is 'flows'. To remove a flow is 'remove'.
1062
            force(bool): True to send via consistency check in case of errors
1063
1064
        """
1065
1066 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
1067
1068 1
        data = {"flows": flow_mods, "force": force}
1069 1
        response = requests.post(endpoint, json=data)
1070 1
        if response.status_code >= 400:
1071 1
            raise FlowModException(str(response.text))
1072
1073 1
    def get_cookie(self):
1074
        """Return the cookie integer from evc id."""
1075 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
1076
1077 1
    @staticmethod
1078 1
    def get_id_from_cookie(cookie):
1079
        """Return the evc id given a cookie value."""
1080 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
1081 1
        return f"{evc_id:x}".zfill(14)
1082
1083 1
    def set_flow_table_group_id(self, flow_mod: dict, vlan) -> dict:
1084
        """Set table_group and table_id"""
1085 1
        table_group = "epl" if vlan is None else "evpl"
1086 1
        flow_mod["table_group"] = table_group
1087 1
        flow_mod["table_id"] = self.table_group[table_group]
1088 1
        return flow_mod
1089
1090 1
    @staticmethod
1091 1
    def get_priority(vlan):
1092
        """Return priority value depending on vlan value"""
1093 1
        if vlan not in {None, "4096/4096", 0}:
1094 1
            return settings.EVPL_SB_PRIORITY
1095 1
        if vlan == 0:
1096 1
            return settings.UNTAGGED_SB_PRIORITY
1097 1
        if vlan == "4096/4096":
1098 1
            return settings.ANY_SB_PRIORITY
1099 1
        return settings.EPL_SB_PRIORITY
1100
1101 1
    def _prepare_flow_mod(self, in_interface, out_interface,
1102
                          queue_id=None, vlan=True):
1103
        """Prepare a common flow mod."""
1104 1
        default_actions = [
1105
            {"action_type": "output", "port": out_interface.port_number}
1106
        ]
1107 1
        queue_id = settings.QUEUE_ID if queue_id == -1 else queue_id
1108 1
        if queue_id is not None:
1109
            default_actions.append(
1110
                {"action_type": "set_queue", "queue_id": queue_id}
1111
            )
1112
1113 1
        flow_mod = {
1114
            "match": {"in_port": in_interface.port_number},
1115
            "cookie": self.get_cookie(),
1116
            "actions": default_actions,
1117
            "owner": "mef_eline",
1118
        }
1119
1120 1
        self.set_flow_table_group_id(flow_mod, vlan)
1121 1
        if self.sb_priority:
1122
            flow_mod["priority"] = self.sb_priority
1123
        else:
1124 1
            flow_mod["priority"] = self.get_priority(vlan)
1125 1
        return flow_mod
1126
1127 1
    def _prepare_nni_flow(self, *args, queue_id=None):
1128
        """Create NNI flows."""
1129 1
        in_interface, out_interface, in_vlan, out_vlan = args
1130 1
        flow_mod = self._prepare_flow_mod(
1131
            in_interface, out_interface, queue_id
1132
        )
1133 1
        flow_mod["match"]["dl_vlan"] = in_vlan
1134 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1135 1
        flow_mod["actions"].insert(0, new_action)
1136
1137 1
        return flow_mod
1138
1139 1
    def _prepare_push_flow(self, *args, queue_id=None):
1140
        """Prepare push flow.
1141
1142
        Arguments:
1143
            in_interface(str): Interface input.
1144
            out_interface(str): Interface output.
1145
            in_vlan(str): Vlan input.
1146
            out_vlan(str): Vlan output.
1147
            new_c_vlan(str): New client vlan.
1148
1149
        Return:
1150
            dict: An python dictionary representing a FlowMod
1151
1152
        """
1153
        # assign all arguments
1154 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
1155 1
        flow_mod = self._prepare_flow_mod(
1156
            in_interface, out_interface, queue_id, in_vlan
1157
        )
1158
        # the service tag must be always pushed
1159 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1160 1
        flow_mod["actions"].insert(0, new_action)
1161
1162 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
1163 1
        flow_mod["actions"].insert(0, new_action)
1164
1165 1
        if in_vlan is not None:
1166
            # if in_vlan is set, it must be included in the match
1167 1
            flow_mod["match"]["dl_vlan"] = in_vlan
1168
1169 1
        if new_c_vlan not in self.special_cases:
1170
            # new_in_vlan is an integer but zero, action to set is required
1171 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
1172 1
            flow_mod["actions"].insert(0, new_action)
1173
1174 1
        if in_vlan not in self.special_cases and new_c_vlan == 0:
1175
            # # new_in_vlan is an integer but zero and new_c_vlan does not
1176
            # a pop action is required
1177 1
            new_action = {"action_type": "pop_vlan"}
1178 1
            flow_mod["actions"].insert(0, new_action)
1179
1180 1
        elif in_vlan == "4096/4096" and new_c_vlan == 0:
1181
            # if in_vlan match with any tags and new_c_vlan does not
1182
            # a pop action is required
1183 1
            new_action = {"action_type": "pop_vlan"}
1184 1
            flow_mod["actions"].insert(0, new_action)
1185
1186 1
        elif not in_vlan and new_c_vlan not in self.special_cases:
1187
            # new_in_vlan is an integer but zero and in_vlan is not set
1188
            # then it is set now
1189 1
            new_action = {"action_type": "push_vlan", "tag_type": "c"}
1190 1
            flow_mod["actions"].insert(0, new_action)
1191
1192 1
        return flow_mod
1193
1194 1
    def _prepare_pop_flow(
1195
        self, in_interface, out_interface, out_vlan, queue_id=None
1196
    ):
1197
        # pylint: disable=too-many-arguments
1198
        """Prepare pop flow."""
1199 1
        flow_mod = self._prepare_flow_mod(
1200
            in_interface, out_interface, queue_id
1201
        )
1202 1
        flow_mod["match"]["dl_vlan"] = out_vlan
1203 1
        new_action = {"action_type": "pop_vlan"}
1204 1
        flow_mod["actions"].insert(0, new_action)
1205 1
        return flow_mod
1206
1207 1
    @staticmethod
1208 1
    def run_bulk_sdntraces(uni_list):
1209
        """Run SDN traces on control plane starting from EVC UNIs."""
1210 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/traces"
1211 1
        data = []
1212 1
        for uni in uni_list:
1213 1
            data_uni = {
1214
                "trace": {
1215
                            "switch": {
1216
                                "dpid": uni.interface.switch.dpid,
1217
                                "in_port": uni.interface.port_number,
1218
                            }
1219
                        }
1220
                }
1221 1
            if uni.user_tag:
1222 1
                uni_dl_vlan = map_dl_vlan(uni.user_tag.value)
1223 1
                if uni_dl_vlan:
1224 1
                    data_uni["trace"]["eth"] = {
1225
                                            "dl_type": 0x8100,
1226
                                            "dl_vlan": uni_dl_vlan,
1227
                                            }
1228 1
            data.append(data_uni)
1229 1
        try:
1230 1
            response = requests.put(endpoint, json=data, timeout=30)
1231
        except Timeout as exception:
1232
            log.error(f"Request has timed out: {exception}")
1233
            return {"result": []}
1234 1
        if response.status_code >= 400:
1235 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1236 1
            return {"result": []}
1237 1
        return response.json()
1238
1239
    # pylint: disable=too-many-return-statements
1240 1
    @staticmethod
1241 1
    def check_trace(circuit, trace_a, trace_z):
1242
        """Auxiliar function to check an individual trace"""
1243 1
        if (
1244
            len(trace_a) != len(circuit.current_path) + 1
1245
            or not compare_uni_out_trace(circuit.uni_z, trace_a[-1])
1246
        ):
1247 1
            log.warning(f"Invalid trace from uni_a: {trace_a}")
1248 1
            return False
1249 1
        if (
1250
            len(trace_z) != len(circuit.current_path) + 1
1251
            or not compare_uni_out_trace(circuit.uni_a, trace_z[-1])
1252
        ):
1253 1
            log.warning(f"Invalid trace from uni_z: {trace_z}")
1254 1
            return False
1255
1256 1
        for link, trace1, trace2 in zip(circuit.current_path,
1257
                                        trace_a[1:],
1258
                                        trace_z[:0:-1]):
1259 1
            metadata_vlan = None
1260 1
            if link.metadata:
1261 1
                metadata_vlan = glom(link.metadata, 's_vlan.value')
1262 1
            if compare_endpoint_trace(
1263
                                        link.endpoint_a,
1264
                                        metadata_vlan,
1265
                                        trace2
1266
                                    ) is False:
1267 1
                log.warning(f"Invalid trace from uni_a: {trace_a}")
1268 1
                return False
1269 1
            if compare_endpoint_trace(
1270
                                        link.endpoint_b,
1271
                                        metadata_vlan,
1272
                                        trace1
1273
                                    ) is False:
1274 1
                log.warning(f"Invalid trace from uni_z: {trace_z}")
1275 1
                return False
1276
1277 1
        return True
1278
1279 1
    @staticmethod
1280 1
    def check_list_traces(list_circuits):
1281
        """Check if current_path is deployed comparing with SDN traces."""
1282 1
        if not list_circuits:
1283
            return {}
1284 1
        uni_list = []
1285 1
        for circuit in list_circuits:
1286 1
            uni_list.append(circuit.uni_a)
1287 1
            uni_list.append(circuit.uni_z)
1288
1289 1
        traces = EVCDeploy.run_bulk_sdntraces(uni_list)
1290 1
        traces = traces["result"]
1291 1
        circuits_checked = {}
1292 1
        if not traces:
1293
            return circuits_checked
1294
1295 1
        try:
1296 1
            for i, circuit in enumerate(list_circuits):
1297 1
                trace_a = traces[2*i]
1298 1
                trace_z = traces[2*i+1]
1299 1
                circuits_checked[circuit.id] = EVCDeploy.check_trace(
1300
                        circuit, trace_a, trace_z
1301
                    )
1302
        except IndexError as err:
1303
            log.error(
1304
                f"Bulk sdntraces returned fewer items than expected."
1305
                f"Error = {err}"
1306
            )
1307
1308 1
        return circuits_checked
1309
1310 1
    @staticmethod
1311 1
    def get_endpoint_by_id(
1312
        link: Link,
1313
        id_: str,
1314
        operator: Union[eq, ne]
1315
    ) -> Interface:
1316
        """Return endpoint from link
1317
        either equal(eq) or not equal(ne) to id"""
1318 1
        if operator(link.endpoint_a.switch.id, id_):
1319 1
            return link.endpoint_a
1320 1
        return link.endpoint_b
1321
1322
1323 1
class LinkProtection(EVCDeploy):
1324
    """Class to handle link protection."""
1325
1326 1
    def is_affected_by_link(self, link=None):
1327
        """Verify if the current path is affected by link down event."""
1328
        return self.current_path.is_affected_by_link(link)
1329
1330 1
    def is_using_primary_path(self):
1331
        """Verify if the current deployed path is self.primary_path."""
1332 1
        return self.current_path == self.primary_path
1333
1334 1
    def is_using_backup_path(self):
1335
        """Verify if the current deployed path is self.backup_path."""
1336 1
        return self.current_path == self.backup_path
1337
1338 1
    def is_using_dynamic_path(self):
1339
        """Verify if the current deployed path is dynamic."""
1340 1
        if (
1341
            self.current_path
1342
            and not self.is_using_primary_path()
1343
            and not self.is_using_backup_path()
1344
            and self.current_path.status is EntityStatus.UP
1345
        ):
1346
            return True
1347 1
        return False
1348
1349 1
    def deploy_to(self, path_name=None, path=None):
1350
        """Create a deploy to path."""
1351 1
        if self.current_path == path:
1352 1
            log.debug(f"{path_name} is equal to current_path.")
1353 1
            return True
1354
1355 1
        if path.status is EntityStatus.UP:
1356 1
            return self.deploy_to_path(path)
1357
1358 1
        return False
1359
1360 1
    def handle_link_up(self, link):
1361
        """Handle circuit when link up.
1362
1363
        Args:
1364
            link(Link): Link affected by link.up event.
1365
1366
        """
1367 1
        if self.is_intra_switch():
1368
            return True
1369
1370 1
        if self.is_using_primary_path():
1371 1
            return True
1372
1373 1
        success = False
1374 1
        if self.primary_path.is_affected_by_link(link):
1375 1
            success = self.deploy_to_primary_path()
1376
1377 1
        if success:
1378 1
            return True
1379
1380
        # We tried to deploy(primary_path) without success.
1381
        # And in this case is up by some how. Nothing to do.
1382 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1383 1
            return True
1384
1385
        # In this case, probably the circuit is not being used and
1386
        # we can move to backup
1387 1
        if self.backup_path.is_affected_by_link(link):
1388 1
            success = self.deploy_to_backup_path()
1389
1390
        # In this case, the circuit is not being used and we should
1391
        # try a dynamic path
1392 1
        if not success and self.dynamic_backup_path:
1393 1
            success = self.deploy_to_path()
1394
1395 1
        if success:
1396 1
            emit_event(self._controller, "redeployed_link_up",
1397
                       content=map_evc_event_content(self))
1398 1
            return True
1399
1400 1
        return True
1401
1402 1
    def handle_link_down(self):
1403
        """Handle circuit when link down.
1404
1405
        Returns:
1406
            bool: True if the re-deploy was successly otherwise False.
1407
1408
        """
1409 1
        success = False
1410 1
        if self.is_using_primary_path():
1411 1
            success = self.deploy_to_backup_path()
1412 1
        elif self.is_using_backup_path():
1413 1
            success = self.deploy_to_primary_path()
1414
1415 1
        if not success and self.dynamic_backup_path:
1416 1
            success = self.deploy_to_path()
1417
1418 1
        if success:
1419 1
            log.debug(f"{self} deployed after link down.")
1420
        else:
1421 1
            self.deactivate()
1422 1
            self.current_path = Path([])
1423 1
            self.sync()
1424 1
            log.debug(f"Failed to re-deploy {self} after link down.")
1425
1426 1
        return success
1427
1428 1
    @staticmethod
1429 1
    def get_interface_from_switch(uni: UNI, switches: dict) -> Interface:
1430
        """Get interface from switch by uni"""
1431 1
        switch = switches[uni.interface.switch.dpid]
1432 1
        interface = switch.interfaces[uni.interface.port_number]
1433 1
        return interface
1434
1435 1
    def handle_topology_update(self, switches: dict):
1436
        """Handle changes in the topology"""
1437
        # All intra-switch EVCs do not have current_path.
1438
        # In case of inter-switch EVC and not current_path,
1439
        # link_down should take care of deactivation.
1440 1
        if not self.is_intra_switch and not self.current_path:
1441
            return
1442 1
        try:
1443 1
            interface_a = self.get_interface_from_switch(self.uni_a, switches)
1444 1
        except KeyError:
1445 1
            id_ = self.uni_a.interface.id
1446 1
            log.warning(f"The interface {id_} was not found")
1447 1
            return
1448
1449 1
        try:
1450 1
            interface_z = self.get_interface_from_switch(self.uni_z, switches)
1451
        except KeyError:
1452
            id_ = self.uni_z.interface.id
1453
            log.warning(f"The interface {id_} was not found")
1454
            return
1455
1456 1
        active, interfaces = self.is_uni_interface_active(
1457
            interface_a, interface_z
1458
        )
1459 1
        if self.is_active() != active:
1460 1
            if active:
1461 1
                self.activate()
1462 1
                log.info(f"Activating EVC {self.id}. Interfaces: "
1463
                         f"{interfaces}.")
1464
            else:
1465 1
                self.deactivate()
1466 1
                log.info(f"Deactivating EVC {self.id}. Interfaces: "
1467
                         f"{interfaces}.")
1468 1
            self.sync()
1469
1470 1
    def are_unis_active(self, switches: dict) -> bool:
1471
        """Determine whether this EVC should be active"""
1472 1
        interface_a = self.get_interface_from_switch(self.uni_a, switches)
1473 1
        interface_z = self.get_interface_from_switch(self.uni_z, switches)
1474 1
        active, _ = self.is_uni_interface_active(interface_a, interface_z)
1475 1
        return active
1476
1477 1
    @staticmethod
1478 1
    def is_uni_interface_active(
1479
        interface_a: Interface,
1480
        interface_z: Interface
1481
    ) -> tuple[bool, dict]:
1482
        """Determine whether a UNI should be active"""
1483 1
        active = True
1484 1
        interfaces = {}
1485 1
        interface_a_dict = {
1486
            "status": interface_a.status.value,
1487
            "status_reason": interface_a.status_reason
1488
        }
1489 1
        interface_z_dict = {
1490
            "status": interface_z.status.value,
1491
            "status_reason": interface_z.status_reason
1492
        }
1493 1
        if (interface_a.status != EntityStatus.UP
1494
                or interface_a.status_reason != set()):
1495 1
            active = False
1496 1
            interfaces[interface_a.id] = interface_a_dict
1497 1
        if (interface_z.status != EntityStatus.UP
1498
                or interface_z.status_reason != set()):
1499 1
            active = False
1500 1
            interfaces[interface_z.id] = interface_z_dict
1501 1
        if active:
1502 1
            interfaces[interface_a.id] = interface_a_dict
1503 1
            interfaces[interface_z.id] = interface_z_dict
1504 1
        return active, interfaces
1505
1506
1507 1
class EVC(LinkProtection):
1508
    """Class that represents a E-Line Virtual Connection."""
1509