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

build.models.evc.EVCBase.archive()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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