Test Failed
Pull Request — master (#407)
by Vinicius
15:31 queued 13:18
created

build.models.evc.EVCDeploy.get_endpoint_by_id()   A

Complexity

Conditions 2

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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