Passed
Push — master ( f0eb4d...f1cfb0 )
by Vinicius
09:02 queued 06:59
created

build.models.evc.EVCBase.as_dict()   B

Complexity

Conditions 4

Size

Total Lines 49
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 32
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 37
dl 0
loc 49
ccs 32
cts 32
cp 1
rs 8.9919
c 0
b 0
f 0
cc 4
nop 1
crap 4
1
"""Classes used in the main application."""  # pylint: disable=too-many-lines
2 1
from collections import OrderedDict
3 1
from datetime import datetime
4 1
from threading import Lock
5 1
from uuid import uuid4
6
7 1
import requests
8 1
from glom import glom
9
10 1
from kytos.core import log
11 1
from kytos.core.common import EntityStatus, GenericEntity
12 1
from kytos.core.exceptions import KytosNoTagAvailableError
13 1
from kytos.core.helpers import get_time, now
14 1
from kytos.core.interface import UNI
15 1
from napps.kytos.mef_eline import controllers, settings
16 1
from napps.kytos.mef_eline.exceptions import FlowModException, InvalidPath
17 1
from napps.kytos.mef_eline.utils import (compare_endpoint_trace, emit_event,
18
                                         notify_link_available_tags)
19
20 1
from .path import DynamicPathManager, Path
21
22
23 1
class EVCBase(GenericEntity):
24
    """Class to represent a circuit."""
25
26 1
    read_only_attributes = [
27
        "creation_time",
28
        "active",
29
        "current_path",
30
        "failover_path",
31
        "_id",
32
        "archived",
33
    ]
34 1
    attributes_requiring_redeploy = [
35
        "primary_path",
36
        "backup_path",
37
        "dynamic_backup_path",
38
        "queue_id",
39
        "sb_priority",
40
    ]
41 1
    required_attributes = ["name", "uni_a", "uni_z"]
42
43 1
    def __init__(self, controller, **kwargs):
44
        """Create an EVC instance with the provided parameters.
45
46
        Args:
47
            id(str): EVC identifier. Whether it's None an ID will be genereted.
48
                     Only the first 14 bytes passed will be used.
49
            name: represents an EVC name.(Required)
50
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
51
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
52
            start_date(datetime|str): Date when the EVC was registred.
53
                                      Default is now().
54
            end_date(datetime|str): Final date that the EVC will be fineshed.
55
                                    Default is None.
56
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
57
            primary_links(list): Primary links used by evc. Default is []
58
            backup_links(list): Backups links used by evc. Default is []
59
            current_path(list): Circuit being used at the moment if this is an
60
                                active circuit. Default is [].
61
            failover_path(list): Path being used to provide EVC protection via
62
                                failover during link failures. Default is [].
63
            primary_path(list): primary circuit offered to user IF one or more
64
                                links were provided. Default is [].
65
            backup_path(list): backup circuit offered to the user IF one or
66
                               more links were provided. Default is [].
67
            dynamic_backup_path(bool): Enable computer backup path dynamically.
68
                                       Dafault is False.
69
            creation_time(datetime|str): datetime when the circuit should be
70
                                         activated. default is now().
71
            enabled(Boolean): attribute to indicate the administrative state;
72
                              default is False.
73
            active(Boolean): attribute to indicate the operational state;
74
                             default is False.
75
            archived(Boolean): indicate the EVC has been deleted and is
76
                               archived; default is False.
77
            owner(str): The EVC owner. Default is None.
78
            sb_priority(int): Service level provided in the request.
79
                              Default is None.
80
            service_level(int): Service level provided. The higher the better.
81
                                Default is 0.
82
83
        Raises:
84
            ValueError: raised when object attributes are invalid.
85
86
        """
87 1
        self._validate(**kwargs)
88 1
        super().__init__()
89
90
        # required attributes
91 1
        self._id = kwargs.get("id", uuid4().hex)[:14]
92 1
        self.uni_a = kwargs.get("uni_a")
93 1
        self.uni_z = kwargs.get("uni_z")
94 1
        self.name = kwargs.get("name")
95
96
        # optional attributes
97 1
        self.start_date = get_time(kwargs.get("start_date")) or now()
98 1
        self.end_date = get_time(kwargs.get("end_date")) or None
99 1
        self.queue_id = kwargs.get("queue_id", None)
100
101 1
        self.bandwidth = kwargs.get("bandwidth", 0)
102 1
        self.primary_links = Path(kwargs.get("primary_links", []))
103 1
        self.backup_links = Path(kwargs.get("backup_links", []))
104 1
        self.current_path = Path(kwargs.get("current_path", []))
105 1
        self.failover_path = Path(kwargs.get("failover_path", []))
106 1
        self.primary_path = Path(kwargs.get("primary_path", []))
107 1
        self.backup_path = Path(kwargs.get("backup_path", []))
108 1
        self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False)
109 1
        self.creation_time = get_time(kwargs.get("creation_time")) or now()
110 1
        self.owner = kwargs.get("owner", None)
111 1
        self.sb_priority = kwargs.get("sb_priority", None) or kwargs.get(
112
            "priority", None
113
        )
114 1
        self.service_level = kwargs.get("service_level", 0)
115 1
        self.circuit_scheduler = kwargs.get("circuit_scheduler", [])
116
117 1
        self.current_links_cache = set()
118 1
        self.primary_links_cache = set()
119 1
        self.backup_links_cache = set()
120
121 1
        self.lock = Lock()
122
123 1
        self.archived = kwargs.get("archived", False)
124
125 1
        self.metadata = kwargs.get("metadata", {})
126
127 1
        self._controller = controller
128 1
        self._mongo_controller = controllers.ELineController()
129
130 1
        if kwargs.get("active", False):
131 1
            self.activate()
132
        else:
133 1
            self.deactivate()
134
135 1
        if kwargs.get("enabled", False):
136 1
            self.enable()
137
        else:
138 1
            self.disable()
139
140
        # datetime of user request for a EVC (or datetime when object was
141
        # created)
142 1
        self.request_time = kwargs.get("request_time", now())
143
        # dict with the user original request (input)
144 1
        self._requested = kwargs
145
146 1
    def sync(self):
147
        """Sync this EVC in the MongoDB."""
148 1
        self._mongo_controller.upsert_evc(self.as_dict())
149
150 1
    def update(self, **kwargs):
151
        """Update evc attributes.
152
153
        This method will raises an error trying to change the following
154
        attributes: [name, uni_a and uni_z]
155
156
        Returns:
157
            the values for enable and a redeploy attribute, if exists and None
158
            otherwise
159
        Raises:
160
            ValueError: message with error detail.
161
162
        """
163 1
        enable, redeploy = (None, None)
164 1
        uni_a = kwargs.get("uni_a") or self.uni_a
165 1
        uni_z = kwargs.get("uni_z") or self.uni_z
166 1
        for attribute, value in kwargs.items():
167 1
            if attribute in self.read_only_attributes:
168 1
                raise ValueError(f"{attribute} can't be updated.")
169 1
            if not hasattr(self, attribute):
170 1
                raise ValueError(f'The attribute "{attribute}" is invalid.')
171 1
            if attribute in ("primary_path", "backup_path"):
172 1
                try:
173 1
                    value.is_valid(
174
                        uni_a.interface.switch, uni_z.interface.switch
175
                    )
176 1
                except InvalidPath as exception:
177 1
                    raise ValueError(  # pylint: disable=raise-missing-from
178
                        f"{attribute} is not a " f"valid path: {exception}"
179
                    )
180 1
        for attribute, value in kwargs.items():
181 1
            if attribute in ("enable", "enabled"):
182 1
                if value:
183 1
                    self.enable()
184
                else:
185 1
                    self.disable()
186 1
                enable = value
187
            else:
188 1
                setattr(self, attribute, value)
189 1
                if attribute in self.attributes_requiring_redeploy:
190 1
                    redeploy = value
191 1
        self.sync()
192 1
        return enable, redeploy
193
194 1
    def __repr__(self):
195
        """Repr method."""
196 1
        return f"EVC({self._id}, {self.name})"
197
198 1
    def _validate(self, **kwargs):
199
        """Do Basic validations.
200
201
        Verify required attributes: name, uni_a, uni_z
202
        Verify if the attributes uni_a and uni_z are valid.
203
204
        Raises:
205
            ValueError: message with error detail.
206
207
        """
208 1
        for attribute in self.required_attributes:
209
210 1
            if attribute not in kwargs:
211 1
                raise ValueError(f"{attribute} is required.")
212
213 1
            if "uni" in attribute:
214 1
                uni = kwargs.get(attribute)
215 1
                if not isinstance(uni, UNI):
216
                    raise ValueError(f"{attribute} is an invalid UNI.")
217
218 1
                if not uni.is_valid():
219 1
                    tag = uni.user_tag.value
220 1
                    message = f"VLAN tag {tag} is not available in {attribute}"
221 1
                    raise ValueError(message)
222
223 1
    def __eq__(self, other):
224
        """Override the default implementation."""
225 1
        if not isinstance(other, EVC):
226
            return False
227
228 1
        attrs_to_compare = ["name", "uni_a", "uni_z", "owner", "bandwidth"]
229 1
        for attribute in attrs_to_compare:
230 1
            if getattr(other, attribute) != getattr(self, attribute):
231 1
                return False
232 1
        return True
233
234 1
    def shares_uni(self, other):
235
        """Check if two EVCs share an UNI."""
236 1
        if other.uni_a in (self.uni_a, self.uni_z) or other.uni_z in (
237
            self.uni_a,
238
            self.uni_z,
239
        ):
240 1
            return True
241
        return False
242
243 1
    def as_dict(self):
244
        """Return a dictionary representing an EVC object."""
245 1
        evc_dict = {
246
            "id": self.id,
247
            "name": self.name,
248
            "uni_a": self.uni_a.as_dict(),
249
            "uni_z": self.uni_z.as_dict(),
250
        }
251
252 1
        time_fmt = "%Y-%m-%dT%H:%M:%S"
253
254 1
        evc_dict["start_date"] = self.start_date
255 1
        if isinstance(self.start_date, datetime):
256 1
            evc_dict["start_date"] = self.start_date.strftime(time_fmt)
257
258 1
        evc_dict["end_date"] = self.end_date
259 1
        if isinstance(self.end_date, datetime):
260 1
            evc_dict["end_date"] = self.end_date.strftime(time_fmt)
261
262 1
        evc_dict["queue_id"] = self.queue_id
263 1
        evc_dict["bandwidth"] = self.bandwidth
264 1
        evc_dict["primary_links"] = self.primary_links.as_dict()
265 1
        evc_dict["backup_links"] = self.backup_links.as_dict()
266 1
        evc_dict["current_path"] = self.current_path.as_dict()
267 1
        evc_dict["failover_path"] = self.failover_path.as_dict()
268 1
        evc_dict["primary_path"] = self.primary_path.as_dict()
269 1
        evc_dict["backup_path"] = self.backup_path.as_dict()
270 1
        evc_dict["dynamic_backup_path"] = self.dynamic_backup_path
271 1
        evc_dict["metadata"] = self.metadata
272
273 1
        evc_dict["request_time"] = self.request_time
274 1
        if isinstance(self.request_time, datetime):
275 1
            evc_dict["request_time"] = self.request_time.strftime(time_fmt)
276
277 1
        time = self.creation_time.strftime(time_fmt)
278 1
        evc_dict["creation_time"] = time
279
280 1
        evc_dict["owner"] = self.owner
281 1
        evc_dict["circuit_scheduler"] = [
282
            sc.as_dict() for sc in self.circuit_scheduler
283
        ]
284
285 1
        evc_dict["active"] = self.is_active()
286 1
        evc_dict["enabled"] = self.is_enabled()
287 1
        evc_dict["archived"] = self.archived
288 1
        evc_dict["sb_priority"] = self.sb_priority
289 1
        evc_dict["service_level"] = self.service_level
290
291 1
        return evc_dict
292
293 1
    @property
294 1
    def id(self):  # pylint: disable=invalid-name
295
        """Return this EVC's ID."""
296 1
        return self._id
297
298 1
    def archive(self):
299
        """Archive this EVC on deletion."""
300 1
        self.archived = True
301
302
303
# pylint: disable=fixme, too-many-public-methods
304 1
class EVCDeploy(EVCBase):
305
    """Class to handle the deploy procedures."""
306
307 1
    def create(self):
308
        """Create a EVC."""
309
310 1
    def discover_new_paths(self):
311
        """Discover new paths to satisfy this circuit and deploy it."""
312
        return DynamicPathManager.get_best_paths(self)
313
314 1
    def get_failover_path_candidates(self):
315
        """Get failover paths to satisfy this EVC."""
316
        # in the future we can return primary/backup paths as well
317
        # we just have to properly handle link_up and failover paths
318
        # if (
319
        #     self.is_using_primary_path() and
320
        #     self.backup_path.status is EntityStatus.UP
321
        # ):
322
        #     yield self.backup_path
323 1
        return DynamicPathManager.get_disjoint_paths(self, self.current_path)
324
325 1
    def change_path(self):
326
        """Change EVC path."""
327
328 1
    def reprovision(self):
329
        """Force the EVC (re-)provisioning."""
330
331 1
    def is_affected_by_link(self, link):
332
        """Return True if this EVC has the given link on its current path."""
333 1
        return link in self.current_path
334
335 1
    def link_affected_by_interface(self, interface):
336
        """Return True if this EVC has the given link on its current path."""
337
        return self.current_path.link_affected_by_interface(interface)
338
339 1
    def is_backup_path_affected_by_link(self, link):
340
        """Return True if the backup path of this EVC uses the given link."""
341 1
        return link in self.backup_path
342
343
    # pylint: disable=invalid-name
344 1
    def is_primary_path_affected_by_link(self, link):
345
        """Return True if the primary path of this EVC uses the given link."""
346 1
        return link in self.primary_path
347
348 1
    def is_failover_path_affected_by_link(self, link):
349
        """Return True if this EVC has the given link on its failover path."""
350 1
        return link in self.failover_path
351
352 1
    def is_eligible_for_failover_path(self):
353
        """Verify if this EVC is eligible for failover path (EP029)"""
354
        # In the future this function can be augmented to consider
355
        # primary/backup, primary/dynamic, and other path combinations
356 1
        return (
357
            self.dynamic_backup_path and
358
            not self.primary_path and not self.backup_path
359
        )
360
361 1
    def is_using_primary_path(self):
362
        """Verify if the current deployed path is self.primary_path."""
363 1
        return self.primary_path and (self.current_path == self.primary_path)
364
365 1
    def is_using_backup_path(self):
366
        """Verify if the current deployed path is self.backup_path."""
367 1
        return self.backup_path and (self.current_path == self.backup_path)
368
369 1
    def is_using_dynamic_path(self):
370
        """Verify if the current deployed path is a dynamic path."""
371 1
        if (
372
            self.current_path
373
            and not self.is_using_primary_path()
374
            and not self.is_using_backup_path()
375
            and self.current_path.status == EntityStatus.UP
376
        ):
377
            return True
378 1
        return False
379
380 1
    def deploy_to_backup_path(self):
381
        """Deploy the backup path into the datapaths of this circuit.
382
383
        If the backup_path attribute is valid and up, this method will try to
384
        deploy this backup_path.
385
386
        If everything fails and dynamic_backup_path is True, then tries to
387
        deploy a dynamic path.
388
        """
389
        # TODO: Remove flows from current (cookies)
390 1
        if self.is_using_backup_path():
391
            # TODO: Log to say that cannot move backup to backup
392
            return True
393
394 1
        success = False
395 1
        if self.backup_path.status is EntityStatus.UP:
396 1
            success = self.deploy_to_path(self.backup_path)
397
398 1
        if success:
399 1
            return True
400
401 1
        if (
402
            self.dynamic_backup_path
403
            or self.uni_a.interface.switch == self.uni_z.interface.switch
404
        ):
405 1
            return self.deploy_to_path()
406
407
        return False
408
409 1
    def deploy_to_primary_path(self):
410
        """Deploy the primary path into the datapaths of this circuit.
411
412
        If the primary_path attribute is valid and up, this method will try to
413
        deploy this primary_path.
414
        """
415
        # TODO: Remove flows from current (cookies)
416 1
        if self.is_using_primary_path():
417
            # TODO: Log to say that cannot move primary to primary
418
            return True
419
420 1
        if self.primary_path.status is EntityStatus.UP:
421 1
            return self.deploy_to_path(self.primary_path)
422 1
        return False
423
424 1
    def deploy(self):
425
        """Deploy EVC to best path.
426
427
        Best path can be the primary path, if available. If not, the backup
428
        path, and, if it is also not available, a dynamic path.
429
        """
430 1
        if self.archived:
431 1
            return False
432 1
        self.enable()
433 1
        success = self.deploy_to_primary_path()
434 1
        if not success:
435 1
            success = self.deploy_to_backup_path()
436
437 1
        if success:
438 1
            emit_event(self._controller, "deployed", evc_id=self.id)
439 1
        return success
440
441 1
    @staticmethod
442 1
    def get_path_status(path):
443
        """Check for the current status of a path.
444
445
        If any link in this path is down, the path is considered down.
446
        """
447 1
        if not path:
448 1
            return EntityStatus.DISABLED
449
450 1
        for link in path:
451 1
            if link.status is not EntityStatus.UP:
452 1
                return link.status
453 1
        return EntityStatus.UP
454
455
    #    def discover_new_path(self):
456
    #        # TODO: discover a new path to satisfy this circuit and deploy
457
458 1
    def remove(self):
459
        """Remove EVC path and disable it."""
460 1
        self.remove_current_flows()
461 1
        self.remove_path_flows(self.failover_path)
462 1
        self.disable()
463 1
        self.sync()
464 1
        emit_event(self._controller, "undeployed", evc_id=self.id)
465
466 1
    def remove_current_flows(self, current_path=None, force=True):
467
        """Remove all flows from current path."""
468 1
        switches = set()
469
470 1
        switches.add(self.uni_a.interface.switch)
471 1
        switches.add(self.uni_z.interface.switch)
472 1
        if not current_path:
473 1
            current_path = self.current_path
474 1
        for link in current_path:
475 1
            switches.add(link.endpoint_a.switch)
476 1
            switches.add(link.endpoint_b.switch)
477
478 1
        match = {
479
            "cookie": self.get_cookie(),
480
            "cookie_mask": 18446744073709551615,
481
        }
482
483 1
        for switch in switches:
484 1
            try:
485 1
                self._send_flow_mods(switch.id, [match], 'delete', force=force)
486 1
            except FlowModException as err:
487 1
                log.error(
488
                    f"Error removing flows from switch {switch.id} for"
489
                    f"EVC {self}: {err}"
490
                )
491
492 1
        current_path.make_vlans_available()
493 1
        for link in current_path:
494 1
            notify_link_available_tags(self._controller, link)
495 1
        self.current_path = Path([])
496 1
        self.deactivate()
497 1
        self.sync()
498
499 1
    def remove_path_flows(self, path=None, force=True):
500
        """Remove all flows from path."""
501 1
        if not path:
502 1
            return
503
504 1
        dpid_flows_match = {}
505 1
        for dpid, flows in self._prepare_nni_flows(path).items():
506 1
            dpid_flows_match.setdefault(dpid, [])
507 1
            for flow in flows:
508 1
                dpid_flows_match[dpid].append({
509
                    "cookie": flow["cookie"],
510
                    "match": flow["match"],
511
                    "cookie_mask": 18446744073709551615
512
                })
513 1
        for dpid, flows in self._prepare_uni_flows(path, skip_in=True).items():
514 1
            dpid_flows_match.setdefault(dpid, [])
515 1
            for flow in flows:
516 1
                dpid_flows_match[dpid].append({
517
                    "cookie": flow["cookie"],
518
                    "match": flow["match"],
519
                    "cookie_mask": int(0xffffffffffffffff)
520
                })
521
522 1
        for dpid, flows in dpid_flows_match.items():
523 1
            try:
524 1
                self._send_flow_mods(dpid, flows, 'delete', force=force)
525 1
            except FlowModException as err:
526 1
                log.error(
527
                    "Error removing failover flows: "
528
                    f"dpid={dpid} evc={self} error={err}"
529
                )
530
531 1
        path.make_vlans_available()
532 1
        for link in path:
533 1
            notify_link_available_tags(self._controller, link)
534
535 1
    @staticmethod
536 1
    def links_zipped(path=None):
537
        """Return an iterator which yields pairs of links in order."""
538 1
        if not path:
539
            return []
540 1
        return zip(path[:-1], path[1:])
541
542 1
    def should_deploy(self, path=None):
543
        """Verify if the circuit should be deployed."""
544 1
        if not path:
545 1
            log.debug("Path is empty.")
546 1
            return False
547
548 1
        if not self.is_enabled():
549 1
            log.debug(f"{self} is disabled.")
550 1
            return False
551
552 1
        if not self.is_active():
553 1
            log.debug(f"{self} will be deployed.")
554 1
            return True
555
556 1
        return False
557
558 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
559
        """Install the flows for this circuit.
560
561
        Procedures to deploy:
562
563
        0. Remove current flows installed
564
        1. Decide if will deploy "path" or discover a new path
565
        2. Choose vlan
566
        3. Install NNI flows
567
        4. Install UNI flows
568
        5. Activate
569
        6. Update current_path
570
        7. Update links caches(primary, current, backup)
571
572
        """
573 1
        self.remove_current_flows()
574 1
        use_path = path
575 1
        if self.should_deploy(use_path):
576 1
            try:
577 1
                use_path.choose_vlans()
578 1
                for link in use_path:
579 1
                    notify_link_available_tags(self._controller, link)
580 1
            except KytosNoTagAvailableError:
581 1
                use_path = None
582
        else:
583 1
            for use_path in self.discover_new_paths():
584 1
                if use_path is None:
585
                    continue
586 1
                try:
587 1
                    use_path.choose_vlans()
588 1
                    for link in use_path:
589 1
                        notify_link_available_tags(self._controller, link)
590 1
                    break
591 1
                except KytosNoTagAvailableError:
592 1
                    pass
593
            else:
594 1
                use_path = None
595
596 1
        try:
597 1
            if use_path:
598 1
                self._install_nni_flows(use_path)
599 1
                self._install_uni_flows(use_path)
600 1
            elif self.uni_a.interface.switch == self.uni_z.interface.switch:
601 1
                use_path = Path()
602 1
                self._install_direct_uni_flows()
603
            else:
604 1
                log.warn(
605
                    f"{self} was not deployed. " "No available path was found."
606
                )
607 1
                return False
608 1
        except FlowModException as err:
609 1
            log.error(
610
                f"Error deploying EVC {self} when calling flow_manager: {err}"
611
            )
612 1
            self.remove_current_flows(use_path)
613 1
            return False
614 1
        self.activate()
615 1
        self.current_path = use_path
616 1
        self.sync()
617 1
        log.info(f"{self} was deployed.")
618 1
        return True
619
620 1
    def setup_failover_path(self):
621
        """Install flows for the failover path of this EVC.
622
623
        Procedures to deploy:
624
625
        0. Remove flows currently installed for failover_path (if any)
626
        1. Discover a disjoint path from current_path
627
        2. Choose vlans
628
        3. Install NNI flows
629
        4. Install UNI egress flows
630
        5. Update failover_path
631
        """
632
        # Intra-switch EVCs have no failover_path
633 1
        if self.uni_a.interface.switch == self.uni_z.interface.switch:
634 1
            return False
635
636
        # For not only setup failover path for totally dynamic EVCs
637 1
        if not self.is_eligible_for_failover_path():
638 1
            return False
639
640 1
        reason = ""
641 1
        self.remove_path_flows(self.failover_path)
642 1
        for use_path in self.get_failover_path_candidates():
643 1
            if not use_path:
644 1
                continue
645 1
            try:
646 1
                use_path.choose_vlans()
647 1
                for link in use_path:
648 1
                    notify_link_available_tags(self._controller, link)
649 1
                break
650 1
            except KytosNoTagAvailableError:
651 1
                pass
652
        else:
653 1
            use_path = Path([])
654 1
            reason = "No available path was found"
655
656 1
        try:
657 1
            if use_path:
658 1
                self._install_nni_flows(use_path)
659 1
                self._install_uni_flows(use_path, skip_in=True)
660 1
        except FlowModException as err:
661 1
            reason = "Error deploying failover path"
662 1
            log.error(
663
                f"{reason} for {self}. FlowManager error: {err}"
664
            )
665 1
            self.remove_path_flows(use_path)
666 1
            use_path = Path([])
667
668 1
        self.failover_path = use_path
669 1
        self.sync()
670
671 1
        if not use_path:
672 1
            log.warn(
673
                f"Failover path for {self} was not deployed: {reason}"
674
            )
675 1
            return False
676 1
        log.info(f"Failover path for {self} was deployed.")
677 1
        return True
678
679 1
    def get_failover_flows(self):
680
        """Return the flows needed to make the failover path active, i.e. the
681
        flows for ingress forwarding.
682
683
        Return:
684
            dict: A dict of flows indexed by the switch_id will be returned, or
685
                an empty dict if no failover_path is available.
686
        """
687 1
        if not self.failover_path:
688 1
            return {}
689 1
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
690
691 1
    def _prepare_direct_uni_flows(self):
692
        """Prepare flows connecting two UNIs for intra-switch EVC."""
693 1
        vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
694 1
        vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
695
696 1
        flow_mod_az = self._prepare_flow_mod(
697
            self.uni_a.interface, self.uni_z.interface, self.queue_id
698
        )
699 1
        flow_mod_za = self._prepare_flow_mod(
700
            self.uni_z.interface, self.uni_a.interface, self.queue_id
701
        )
702
703 1
        if vlan_a and vlan_z:
704 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
705 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
706 1
            flow_mod_az["actions"].insert(
707
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
708
            )
709 1
            flow_mod_za["actions"].insert(
710
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
711
            )
712 1
        elif vlan_a:
713 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
714 1
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
715 1
            flow_mod_za["actions"].insert(
716
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
717
            )
718 1
        elif vlan_z:
719 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
720 1
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
721 1
            flow_mod_az["actions"].insert(
722
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
723
            )
724 1
        return (
725
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
726
        )
727
728 1
    def _install_direct_uni_flows(self):
729
        """Install flows connecting two UNIs.
730
731
        This case happens when the circuit is between UNIs in the
732
        same switch.
733
        """
734 1
        (dpid, flows) = self._prepare_direct_uni_flows()
735 1
        self._send_flow_mods(dpid, flows)
736
737 1
    def _prepare_nni_flows(self, path=None):
738
        """Prepare NNI flows."""
739 1
        nni_flows = OrderedDict()
740 1
        for incoming, outcoming in self.links_zipped(path):
741 1
            in_vlan = incoming.get_metadata("s_vlan").value
742 1
            out_vlan = outcoming.get_metadata("s_vlan").value
743
744 1
            flows = []
745
            # Flow for one direction
746 1
            flows.append(
747
                self._prepare_nni_flow(
748
                    incoming.endpoint_b,
749
                    outcoming.endpoint_a,
750
                    in_vlan,
751
                    out_vlan,
752
                    queue_id=self.queue_id,
753
                )
754
            )
755
756
            # Flow for the other direction
757 1
            flows.append(
758
                self._prepare_nni_flow(
759
                    outcoming.endpoint_a,
760
                    incoming.endpoint_b,
761
                    out_vlan,
762
                    in_vlan,
763
                    queue_id=self.queue_id,
764
                )
765
            )
766 1
            nni_flows[incoming.endpoint_b.switch.id] = flows
767 1
        return nni_flows
768
769 1
    def _install_nni_flows(self, path=None):
770
        """Install NNI flows."""
771 1
        for dpid, flows in self._prepare_nni_flows(path).items():
772 1
            self._send_flow_mods(dpid, flows)
773
774 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
775
        """Prepare flows to install UNIs."""
776 1
        uni_flows = {}
777 1
        if not path:
778 1
            log.info("install uni flows without path.")
779 1
            return uni_flows
780
781
        # Determine VLANs
782 1
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
783 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
784
785 1
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
786 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
787
788
        # Flows for the first UNI
789 1
        flows_a = []
790
791
        # Flow for one direction, pushing the service tag
792 1
        if not skip_in:
793 1
            push_flow = self._prepare_push_flow(
794
                self.uni_a.interface,
795
                path[0].endpoint_a,
796
                in_vlan_a,
797
                out_vlan_a,
798
                in_vlan_z,
799
                queue_id=self.queue_id,
800
            )
801 1
            flows_a.append(push_flow)
802
803
        # Flow for the other direction, popping the service tag
804 1
        if not skip_out:
805 1
            pop_flow = self._prepare_pop_flow(
806
                path[0].endpoint_a,
807
                self.uni_a.interface,
808
                out_vlan_a,
809
                queue_id=self.queue_id,
810
            )
811 1
            flows_a.append(pop_flow)
812
813 1
        uni_flows[self.uni_a.interface.switch.id] = flows_a
814
815
        # Flows for the second UNI
816 1
        flows_z = []
817
818
        # Flow for one direction, pushing the service tag
819 1
        if not skip_in:
820 1
            push_flow = self._prepare_push_flow(
821
                self.uni_z.interface,
822
                path[-1].endpoint_b,
823
                in_vlan_z,
824
                out_vlan_z,
825
                in_vlan_a,
826
                queue_id=self.queue_id,
827
            )
828 1
            flows_z.append(push_flow)
829
830
        # Flow for the other direction, popping the service tag
831 1
        if not skip_out:
832 1
            pop_flow = self._prepare_pop_flow(
833
                path[-1].endpoint_b,
834
                self.uni_z.interface,
835
                out_vlan_z,
836
                queue_id=self.queue_id,
837
            )
838 1
            flows_z.append(pop_flow)
839
840 1
        uni_flows[self.uni_z.interface.switch.id] = flows_z
841
842 1
        return uni_flows
843
844 1
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
845
        """Install UNI flows."""
846 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
847
848 1
        for (dpid, flows) in uni_flows.items():
849 1
            self._send_flow_mods(dpid, flows)
850
851 1
    @staticmethod
852 1
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
853
        """Send a flow_mod list to a specific switch.
854
855
        Args:
856
            dpid(str): The target of flows (i.e. Switch.id).
857
            flow_mods(dict): Python dictionary with flow_mods.
858
            command(str): By default is 'flows'. To remove a flow is 'remove'.
859
            force(bool): True to send via consistency check in case of errors
860
861
        """
862
863 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
864
865 1
        data = {"flows": flow_mods, "force": force}
866 1
        response = requests.post(endpoint, json=data)
867 1
        if response.status_code >= 400:
868 1
            raise FlowModException(str(response.text))
869
870 1
    def get_cookie(self):
871
        """Return the cookie integer from evc id."""
872 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
873
874 1
    @staticmethod
875 1
    def get_id_from_cookie(cookie):
876
        """Return the evc id given a cookie value."""
877 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
878 1
        return f"{evc_id:x}".zfill(14)
879
880 1
    def _prepare_flow_mod(self, in_interface, out_interface, queue_id=None):
881
        """Prepare a common flow mod."""
882 1
        default_actions = [
883
            {"action_type": "output", "port": out_interface.port_number}
884
        ]
885 1
        if queue_id:
886
            default_actions.append(
887
                {"action_type": "set_queue", "queue_id": queue_id}
888
            )
889
890 1
        flow_mod = {
891
            "match": {"in_port": in_interface.port_number},
892
            "cookie": self.get_cookie(),
893
            "actions": default_actions,
894
        }
895 1
        if self.sb_priority:
896
            flow_mod["priority"] = self.sb_priority
897
898 1
        return flow_mod
899
900 1
    def _prepare_nni_flow(self, *args, queue_id=None):
901
        """Create NNI flows."""
902 1
        in_interface, out_interface, in_vlan, out_vlan = args
903 1
        flow_mod = self._prepare_flow_mod(
904
            in_interface, out_interface, queue_id
905
        )
906 1
        flow_mod["match"]["dl_vlan"] = in_vlan
907
908 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
909 1
        flow_mod["actions"].insert(0, new_action)
910
911 1
        return flow_mod
912
913 1
    def _prepare_push_flow(self, *args, queue_id=None):
914
        """Prepare push flow.
915
916
        Arguments:
917
            in_interface(str): Interface input.
918
            out_interface(str): Interface output.
919
            in_vlan(str): Vlan input.
920
            out_vlan(str): Vlan output.
921
            new_c_vlan(str): New client vlan.
922
923
        Return:
924
            dict: An python dictionary representing a FlowMod
925
926
        """
927
        # assign all arguments
928 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
929
930 1
        flow_mod = self._prepare_flow_mod(
931
            in_interface, out_interface, queue_id
932
        )
933
934
        # the service tag must be always pushed
935 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
936 1
        flow_mod["actions"].insert(0, new_action)
937
938 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
939 1
        flow_mod["actions"].insert(0, new_action)
940
941 1
        if in_vlan:
942
            # if in_vlan is set, it must be included in the match
943 1
            flow_mod["match"]["dl_vlan"] = in_vlan
944 1
        if new_c_vlan:
945
            # new_in_vlan is set, so an action to set it is necessary
946 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
947 1
            flow_mod["actions"].insert(0, new_action)
948 1
            if not in_vlan:
949
                # new_in_vlan is set, but in_vlan is not, so there was no
950
                # vlan set; then it is set now
951 1
                new_action = {"action_type": "push_vlan", "tag_type": "c"}
952 1
                flow_mod["actions"].insert(0, new_action)
953 1
        elif in_vlan:
954
            # in_vlan is set, but new_in_vlan is not, so the existing vlan
955
            # must be removed
956 1
            new_action = {"action_type": "pop_vlan"}
957 1
            flow_mod["actions"].insert(0, new_action)
958 1
        return flow_mod
959
960 1
    def _prepare_pop_flow(
961
        self, in_interface, out_interface, out_vlan, queue_id=None
962
    ):
963
        # pylint: disable=too-many-arguments
964
        """Prepare pop flow."""
965 1
        flow_mod = self._prepare_flow_mod(
966
            in_interface, out_interface, queue_id
967
        )
968 1
        flow_mod["match"]["dl_vlan"] = out_vlan
969 1
        new_action = {"action_type": "pop_vlan"}
970 1
        flow_mod["actions"].insert(0, new_action)
971 1
        return flow_mod
972
973 1
    @staticmethod
974 1
    def run_sdntrace(uni):
975
        """Run SDN trace on control plane starting from EVC UNIs."""
976 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/trace"
977 1
        data_uni = {
978
            "trace": {
979
                "switch": {
980
                    "dpid": uni.interface.switch.dpid,
981
                    "in_port": uni.interface.port_number,
982
                }
983
            }
984
        }
985 1
        if uni.user_tag:
986 1
            data_uni["trace"]["eth"] = {
987
                "dl_type": 0x8100,
988
                "dl_vlan": uni.user_tag.value,
989
            }
990 1
        response = requests.put(endpoint, json=data_uni)
991 1
        if response.status_code >= 400:
992 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
993 1
            return []
994 1
        return response.json().get('result', [])
995
996 1
    def check_traces(self):
997
        """Check if current_path is deployed comparing with SDN traces."""
998 1
        trace_a = self.run_sdntrace(self.uni_a)
999 1
        if len(trace_a) != len(self.current_path) + 1:
1000 1
            log.warn(f"Invalid trace from uni_a: {trace_a}")
1001 1
            return False
1002 1
        trace_z = self.run_sdntrace(self.uni_z)
1003 1
        if len(trace_z) != len(self.current_path) + 1:
1004 1
            log.warn(f"Invalid trace from uni_z: {trace_z}")
1005 1
            return False
1006
1007 1
        for link, trace1, trace2 in zip(self.current_path,
1008
                                        trace_a[1:],
1009
                                        trace_z[:0:-1]):
1010 1
            if compare_endpoint_trace(
1011
               link.endpoint_a,
1012
               glom(link.metadata, 's_vlan.value'), trace2) is False:
1013 1
                log.warn(f"Invalid trace from uni_a: {trace_a}")
1014 1
                return False
1015 1
            if compare_endpoint_trace(
1016
               link.endpoint_b,
1017
               glom(link.metadata, 's_vlan.value'), trace1) is False:
1018 1
                log.warn(f"Invalid trace from uni_z: {trace_z}")
1019 1
                return False
1020
1021 1
        return True
1022
1023
1024 1
class LinkProtection(EVCDeploy):
1025
    """Class to handle link protection."""
1026
1027 1
    def is_affected_by_link(self, link=None):
1028
        """Verify if the current path is affected by link down event."""
1029
        return self.current_path.is_affected_by_link(link)
1030
1031 1
    def is_using_primary_path(self):
1032
        """Verify if the current deployed path is self.primary_path."""
1033 1
        return self.current_path == self.primary_path
1034
1035 1
    def is_using_backup_path(self):
1036
        """Verify if the current deployed path is self.backup_path."""
1037 1
        return self.current_path == self.backup_path
1038
1039 1
    def is_using_dynamic_path(self):
1040
        """Verify if the current deployed path is dynamic."""
1041 1
        if (
1042
            self.current_path
1043
            and not self.is_using_primary_path()
1044
            and not self.is_using_backup_path()
1045
            and self.current_path.status is EntityStatus.UP
1046
        ):
1047
            return True
1048 1
        return False
1049
1050 1
    def deploy_to(self, path_name=None, path=None):
1051
        """Create a deploy to path."""
1052 1
        if self.current_path == path:
1053 1
            log.debug(f"{path_name} is equal to current_path.")
1054 1
            return True
1055
1056 1
        if path.status is EntityStatus.UP:
1057 1
            return self.deploy_to_path(path)
1058
1059 1
        return False
1060
1061 1
    def handle_link_up(self, link):
1062
        """Handle circuit when link down.
1063
1064
        Args:
1065
            link(Link): Link affected by link.down event.
1066
1067
        """
1068 1
        if self.is_using_primary_path():
1069 1
            return True
1070
1071 1
        success = False
1072 1
        if self.primary_path.is_affected_by_link(link):
1073 1
            success = self.deploy_to_primary_path()
1074
1075 1
        if success:
1076 1
            return True
1077
1078
        # We tried to deploy(primary_path) without success.
1079
        # And in this case is up by some how. Nothing to do.
1080 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1081 1
            return True
1082
1083
        # In this case, probably the circuit is not being used and
1084
        # we can move to backup
1085 1
        if self.backup_path.is_affected_by_link(link):
1086 1
            success = self.deploy_to_backup_path()
1087
1088
        # In this case, the circuit is not being used and we should
1089
        # try a dynamic path
1090 1
        if not success and self.dynamic_backup_path:
1091 1
            success = self.deploy_to_path()
1092
1093 1
        if success:
1094 1
            emit_event(self._controller, "redeployed_link_up", evc_id=self.id)
1095 1
            return True
1096
1097 1
        return True
1098
1099 1
    def handle_link_down(self):
1100
        """Handle circuit when link down.
1101
1102
        Returns:
1103
            bool: True if the re-deploy was successly otherwise False.
1104
1105
        """
1106 1
        success = False
1107 1
        if self.is_using_primary_path():
1108 1
            success = self.deploy_to_backup_path()
1109 1
        elif self.is_using_backup_path():
1110 1
            success = self.deploy_to_primary_path()
1111
1112 1
        if not success and self.dynamic_backup_path:
1113 1
            success = self.deploy_to_path()
1114
1115 1
        if success:
1116 1
            log.debug(f"{self} deployed after link down.")
1117
        else:
1118 1
            self.deactivate()
1119 1
            self.current_path = Path([])
1120 1
            self.sync()
1121 1
            log.debug(f"Failed to re-deploy {self} after link down.")
1122
1123 1
        return success
1124
1125
1126 1
class EVC(LinkProtection):
1127
    """Class that represents a E-Line Virtual Connection."""
1128