Test Failed
Pull Request — master (#396)
by
unknown
03:43
created

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

Complexity

Conditions 2

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 2

Importance

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