Passed
Pull Request — master (#280)
by
unknown
03:21
created

build.models.evc   F

Complexity

Total Complexity 232

Size/Duplication

Total Lines 1341
Duplicated Lines 0 %

Test Coverage

Coverage 94.85%

Importance

Changes 0
Metric Value
wmc 232
eloc 824
dl 0
loc 1341
ccs 626
cts 660
cp 0.9485
rs 1.7759
c 0
b 0
f 0

66 Methods

Rating   Name   Duplication   Size   Complexity  
A EVCDeploy.link_affected_by_interface() 0 3 1
A EVCDeploy.is_backup_path_affected_by_link() 0 3 1
A EVCDeploy.is_using_backup_path() 0 3 1
A EVCBase.sync() 0 4 1
A EVCDeploy.is_failover_path_affected_by_link() 0 3 1
A EVCBase.id() 0 4 1
A EVCDeploy.is_primary_path_affected_by_link() 0 3 1
C EVCBase._validate_has_primary_or_dynamic() 0 28 10
A EVCBase.set_flow_removed_at() 0 3 1
B EVCDeploy.deploy_to_backup_path() 0 25 6
A EVCDeploy.reprovision() 0 2 1
A EVCDeploy.is_using_dynamic_path() 0 10 5
C EVCBase.update() 0 49 10
A EVCDeploy.get_failover_path_candidates() 0 10 1
A EVCDeploy.create() 0 2 1
A EVCBase.is_intra_switch() 0 3 1
B EVCBase._validate() 0 24 6
A EVCBase.__repr__() 0 3 1
A EVCDeploy.is_eligible_for_failover_path() 0 7 1
A EVCBase.has_recent_removed_flow() 0 6 2
B EVCBase.as_dict() 0 53 4
A EVCBase.__eq__() 0 10 4
A EVCBase.archive() 0 3 1
B EVCBase.__init__() 0 107 3
A EVCBase.shares_uni() 0 8 3
A EVCDeploy.is_affected_by_link() 0 3 1
A EVCBase.is_recent_updated() 0 4 1
A EVCDeploy.is_using_primary_path() 0 3 1
A EVCDeploy.discover_new_paths() 0 4 1
A EVCDeploy.change_path() 0 2 1
C EVCDeploy._prepare_uni_flows() 0 69 8
A EVCDeploy._prepare_nni_flow() 0 12 1
D EVCDeploy.deploy_to_path() 0 61 12
A EVCDeploy.run_sdntrace() 0 22 3
A EVCDeploy._install_uni_flows() 0 6 2
A EVCDeploy.get_id_from_cookie() 0 5 1
B EVCDeploy._prepare_push_flow() 0 46 5
A EVCDeploy.links_zipped() 0 6 2
B EVCDeploy.remove_current_flows() 0 32 6
A EVCDeploy.get_failover_flows() 0 11 2
A EVCDeploy._send_flow_mods() 0 18 2
B EVCDeploy._prepare_direct_uni_flows() 0 39 7
C EVCDeploy.remove_failover_flows() 0 47 10
A EVCDeploy._prepare_nni_flows() 0 31 2
A EVCDeploy.should_deploy() 0 15 4
A EVCDeploy.get_cookie() 0 3 1
C EVCDeploy.remove_path_flows() 0 35 9
A EVCDeploy._prepare_pop_flow() 0 12 1
C EVCDeploy.setup_failover_path() 0 58 11
A EVCDeploy._install_direct_uni_flows() 0 8 1
B EVCDeploy.run_bulk_sdntraces() 0 29 5
A EVCDeploy._install_nni_flows() 0 4 2
A EVCDeploy._prepare_flow_mod() 0 24 4
A EVCDeploy.deploy_to_primary_path() 0 14 3
A LinkProtection.is_using_dynamic_path() 0 10 5
A EVCDeploy.remove() 0 8 1
A LinkProtection.is_affected_by_link() 0 3 1
A EVCDeploy.get_path_status() 0 13 4
C EVCDeploy.check_trace() 0 38 9
A LinkProtection.is_using_primary_path() 0 3 1
C EVCDeploy.check_list_traces() 0 36 9
A LinkProtection.is_using_backup_path() 0 3 1
C LinkProtection.handle_link_up() 0 41 11
A EVCDeploy.deploy() 0 17 4
A LinkProtection.deploy_to() 0 10 3
B LinkProtection.handle_link_down() 0 25 6

How to fix   Complexity   

Complexity

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