Passed
Pull Request — master (#375)
by Italo Valcy
04:18
created

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

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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