Passed
Pull Request — master (#352)
by Vinicius
03:45
created

EVCDeploy._prepare_direct_uni_flows()   D

Complexity

Conditions 12

Size

Total Lines 48
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 24
CRAP Score 12

Importance

Changes 0
Metric Value
cc 12
eloc 33
nop 1
dl 0
loc 48
rs 4.8
c 0
b 0
f 0
ccs 24
cts 24
cp 1
crap 12

How to fix   Complexity   

Complexity

Complex classes like build.models.evc.EVCDeploy._prepare_direct_uni_flows() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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