Passed
Pull Request — master (#224)
by
unknown
03:13
created

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

Complexity

Conditions 4

Size

Total Lines 25
Code Lines 20

Duplication

Lines 25
Ratio 100 %

Code Coverage

Tests 2
CRAP Score 14.0742

Importance

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