Passed
Push — master ( 3e1f49...f82675 )
by Vinicius
07:14 queued 04:25
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 2
CRAP Score 1

Importance

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