Passed
Pull Request — master (#258)
by
unknown
03:54
created

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

Complexity

Conditions 6

Size

Total Lines 69
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 6

Importance

Changes 0
Metric Value
cc 6
eloc 46
nop 4
dl 0
loc 69
ccs 26
cts 26
cp 1
crap 6
rs 7.8339
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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