Passed
Pull Request — master (#224)
by
unknown
03:21
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 14
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 20
dl 25
loc 25
rs 9.4
c 0
b 0
f 0
ccs 14
cts 14
cp 1
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
        "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
        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 remove_current_flows(self, current_path=None, force=True):
540
        """Remove all flows from current path."""
541 1
        switches = set()
542
543 1
        switches.add(self.uni_a.interface.switch)
544 1
        switches.add(self.uni_z.interface.switch)
545 1
        if not current_path:
546 1
            current_path = self.current_path
547 1
        for link in current_path:
548 1
            switches.add(link.endpoint_a.switch)
549 1
            switches.add(link.endpoint_b.switch)
550
551 1
        match = {
552
            "cookie": self.get_cookie(),
553
            "cookie_mask": int(0xffffffffffffffff)
554
        }
555
556 1
        for switch in switches:
557 1
            try:
558 1
                self._send_flow_mods(switch.id, [match], 'delete', force=force)
559 1
            except FlowModException as err:
560 1
                log.error(
561
                    f"Error removing flows from switch {switch.id} for"
562
                    f"EVC {self}: {err}"
563
                )
564
565 1
        current_path.make_vlans_available()
566 1
        for link in current_path:
567 1
            notify_link_available_tags(self._controller, link)
568 1
        self.current_path = Path([])
569 1
        self.deactivate()
570 1
        self.sync()
571
572 1
    def remove_path_flows(self, path=None, force=True):
573
        """Remove all flows from path."""
574 1
        if not path:
575 1
            return
576
577 1
        dpid_flows_match = {}
578 1
        for dpid, flows in self._prepare_nni_flows(path).items():
579 1
            dpid_flows_match.setdefault(dpid, [])
580 1
            for flow in flows:
581 1
                dpid_flows_match[dpid].append({
582
                    "cookie": flow["cookie"],
583
                    "match": flow["match"],
584
                    "cookie_mask": int(0xffffffffffffffff)
585
                })
586 1
        for dpid, flows in self._prepare_uni_flows(path, skip_in=True).items():
587 1
            dpid_flows_match.setdefault(dpid, [])
588 1
            for flow in flows:
589 1
                dpid_flows_match[dpid].append({
590
                    "cookie": flow["cookie"],
591
                    "match": flow["match"],
592
                    "cookie_mask": int(0xffffffffffffffff)
593
                })
594
595 1
        for dpid, flows in dpid_flows_match.items():
596 1
            try:
597 1
                self._send_flow_mods(dpid, flows, 'delete', force=force)
598 1
            except FlowModException as err:
599 1
                log.error(
600
                    "Error removing failover flows: "
601
                    f"dpid={dpid} evc={self} error={err}"
602
                )
603
604 1
        path.make_vlans_available()
605 1
        for link in path:
606 1
            notify_link_available_tags(self._controller, link)
607
608 1
    @staticmethod
609 1
    def links_zipped(path=None):
610
        """Return an iterator which yields pairs of links in order."""
611 1
        if not path:
612
            return []
613 1
        return zip(path[:-1], path[1:])
614
615 1
    def should_deploy(self, path=None):
616
        """Verify if the circuit should be deployed."""
617 1
        if not path:
618 1
            log.debug("Path is empty.")
619 1
            return False
620
621 1
        if not self.is_enabled():
622 1
            log.debug(f"{self} is disabled.")
623 1
            return False
624
625 1
        if not self.is_active():
626 1
            log.debug(f"{self} will be deployed.")
627 1
            return True
628
629 1
        return False
630
631 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
632
        """Install the flows for this circuit.
633
634
        Procedures to deploy:
635
636
        0. Remove current flows installed
637
        1. Decide if will deploy "path" or discover a new path
638
        2. Choose vlan
639
        3. Install NNI flows
640
        4. Install UNI flows
641
        5. Activate
642
        6. Update current_path
643
        7. Update links caches(primary, current, backup)
644
645
        """
646 1
        self.remove_current_flows()
647 1
        use_path = path
648 1
        if self.should_deploy(use_path):
649 1
            try:
650 1
                use_path.choose_vlans()
651 1
                for link in use_path:
652 1
                    notify_link_available_tags(self._controller, link)
653 1
            except KytosNoTagAvailableError:
654 1
                use_path = None
655
        else:
656 1
            for use_path in self.discover_new_paths():
657 1
                if use_path is None:
658
                    continue
659 1
                try:
660 1
                    use_path.choose_vlans()
661 1
                    for link in use_path:
662 1
                        notify_link_available_tags(self._controller, link)
663 1
                    break
664 1
                except KytosNoTagAvailableError:
665 1
                    pass
666
            else:
667 1
                use_path = None
668
669 1
        try:
670 1
            if use_path:
671 1
                self._install_nni_flows(use_path)
672 1
                self._install_uni_flows(use_path)
673 1
            elif self.uni_a.interface.switch == self.uni_z.interface.switch:
674 1
                use_path = Path()
675 1
                self._install_direct_uni_flows()
676
            else:
677 1
                log.warning(
678
                    f"{self} was not deployed. " "No available path was found."
679
                )
680 1
                return False
681 1
        except FlowModException as err:
682 1
            log.error(
683
                f"Error deploying EVC {self} when calling flow_manager: {err}"
684
            )
685 1
            self.remove_current_flows(use_path)
686 1
            return False
687 1
        self.activate()
688 1
        self.current_path = use_path
689 1
        self.sync()
690 1
        log.info(f"{self} was deployed.")
691 1
        return True
692
693 1
    def setup_failover_path(self):
694
        """Install flows for the failover path of this EVC.
695
696
        Procedures to deploy:
697
698
        0. Remove flows currently installed for failover_path (if any)
699
        1. Discover a disjoint path from current_path
700
        2. Choose vlans
701
        3. Install NNI flows
702
        4. Install UNI egress flows
703
        5. Update failover_path
704
        """
705
        # Intra-switch EVCs have no failover_path
706 1
        if self.uni_a.interface.switch == self.uni_z.interface.switch:
707 1
            return False
708
709
        # For not only setup failover path for totally dynamic EVCs
710 1
        if not self.is_eligible_for_failover_path():
711 1
            return False
712
713 1
        reason = ""
714 1
        self.remove_path_flows(self.failover_path)
715 1
        for use_path in self.get_failover_path_candidates():
716 1
            if not use_path:
717 1
                continue
718 1
            try:
719 1
                use_path.choose_vlans()
720 1
                for link in use_path:
721 1
                    notify_link_available_tags(self._controller, link)
722 1
                break
723 1
            except KytosNoTagAvailableError:
724 1
                pass
725
        else:
726 1
            use_path = Path([])
727 1
            reason = "No available path was found"
728
729 1
        try:
730 1
            if use_path:
731 1
                self._install_nni_flows(use_path)
732 1
                self._install_uni_flows(use_path, skip_in=True)
733 1
        except FlowModException as err:
734 1
            reason = "Error deploying failover path"
735 1
            log.error(
736
                f"{reason} for {self}. FlowManager error: {err}"
737
            )
738 1
            self.remove_path_flows(use_path)
739 1
            use_path = Path([])
740
741 1
        self.failover_path = use_path
742 1
        self.sync()
743
744 1
        if not use_path:
745 1
            log.warning(
746
                f"Failover path for {self} was not deployed: {reason}"
747
            )
748 1
            return False
749 1
        log.info(f"Failover path for {self} was deployed.")
750 1
        return True
751
752 1
    def get_failover_flows(self):
753
        """Return the flows needed to make the failover path active, i.e. the
754
        flows for ingress forwarding.
755
756
        Return:
757
            dict: A dict of flows indexed by the switch_id will be returned, or
758
                an empty dict if no failover_path is available.
759
        """
760 1
        if not self.failover_path:
761 1
            return {}
762 1
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
763
764 1
    def _prepare_direct_uni_flows(self):
765
        """Prepare flows connecting two UNIs for intra-switch EVC."""
766 1
        vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
767 1
        vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
768
769 1
        is_EVPL = (vlan_a is not None)
770 1
        flow_mod_az = self._prepare_flow_mod(
771
            self.uni_a.interface, self.uni_z.interface,
772
            self.queue_id, is_EVPL
773
        )
774 1
        is_EVPL = (vlan_z is not None)
775 1
        flow_mod_za = self._prepare_flow_mod(
776
            self.uni_z.interface, self.uni_a.interface,
777
            self.queue_id, is_EVPL
778
        )
779
780 1
        if vlan_a and vlan_z:
781 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
782 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
783 1
            flow_mod_az["actions"].insert(
784
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
785
            )
786 1
            flow_mod_za["actions"].insert(
787
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
788
            )
789 1
        elif vlan_a:
790 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
791 1
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
792 1
            flow_mod_za["actions"].insert(
793
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
794
            )
795 1
        elif vlan_z:
796 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
797 1
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
798 1
            flow_mod_az["actions"].insert(
799
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
800
            )
801 1
        return (
802
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
803
        )
804
805 1
    def _install_direct_uni_flows(self):
806
        """Install flows connecting two UNIs.
807
808
        This case happens when the circuit is between UNIs in the
809
        same switch.
810
        """
811 1
        (dpid, flows) = self._prepare_direct_uni_flows()
812 1
        self._send_flow_mods(dpid, flows)
813
814 1
    def _prepare_nni_flows(self, path=None):
815
        """Prepare NNI flows."""
816 1
        nni_flows = OrderedDict()
817 1
        for incoming, outcoming in self.links_zipped(path):
818 1
            in_vlan = incoming.get_metadata("s_vlan").value
819 1
            out_vlan = outcoming.get_metadata("s_vlan").value
820
821 1
            flows = []
822
            # Flow for one direction
823 1
            flows.append(
824
                self._prepare_nni_flow(
825
                    incoming.endpoint_b,
826
                    outcoming.endpoint_a,
827
                    in_vlan,
828
                    out_vlan,
829
                    queue_id=self.queue_id,
830
                )
831
            )
832
833
            # Flow for the other direction
834 1
            flows.append(
835
                self._prepare_nni_flow(
836
                    outcoming.endpoint_a,
837
                    incoming.endpoint_b,
838
                    out_vlan,
839
                    in_vlan,
840
                    queue_id=self.queue_id,
841
                )
842
            )
843 1
            nni_flows[incoming.endpoint_b.switch.id] = flows
844 1
        return nni_flows
845
846 1
    def _install_nni_flows(self, path=None):
847
        """Install NNI flows."""
848 1
        for dpid, flows in self._prepare_nni_flows(path).items():
849 1
            self._send_flow_mods(dpid, flows)
850
851 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
852
        """Prepare flows to install UNIs."""
853 1
        uni_flows = {}
854 1
        if not path:
855 1
            log.info("install uni flows without path.")
856 1
            return uni_flows
857
858
        # Determine VLANs
859 1
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
860 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
861
862 1
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
863 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
864
865
        # Flows for the first UNI
866 1
        flows_a = []
867
868
        # Flow for one direction, pushing the service tag
869 1
        if not skip_in:
870 1
            push_flow = self._prepare_push_flow(
871
                self.uni_a.interface,
872
                path[0].endpoint_a,
873
                in_vlan_a,
874
                out_vlan_a,
875
                in_vlan_z,
876
                queue_id=self.queue_id,
877
            )
878 1
            flows_a.append(push_flow)
879
880
        # Flow for the other direction, popping the service tag
881 1
        if not skip_out:
882 1
            pop_flow = self._prepare_pop_flow(
883
                path[0].endpoint_a,
884
                self.uni_a.interface,
885
                out_vlan_a,
886
                queue_id=self.queue_id,
887
            )
888 1
            flows_a.append(pop_flow)
889
890 1
        uni_flows[self.uni_a.interface.switch.id] = flows_a
891
892
        # Flows for the second UNI
893 1
        flows_z = []
894
895
        # Flow for one direction, pushing the service tag
896 1
        if not skip_in:
897 1
            push_flow = self._prepare_push_flow(
898
                self.uni_z.interface,
899
                path[-1].endpoint_b,
900
                in_vlan_z,
901
                out_vlan_z,
902
                in_vlan_a,
903
                queue_id=self.queue_id,
904
            )
905 1
            flows_z.append(push_flow)
906
907
        # Flow for the other direction, popping the service tag
908 1
        if not skip_out:
909 1
            pop_flow = self._prepare_pop_flow(
910
                path[-1].endpoint_b,
911
                self.uni_z.interface,
912
                out_vlan_z,
913
                queue_id=self.queue_id,
914
            )
915 1
            flows_z.append(pop_flow)
916
917 1
        uni_flows[self.uni_z.interface.switch.id] = flows_z
918
919 1
        return uni_flows
920
921 1
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
922
        """Install UNI flows."""
923 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
924
925 1
        for (dpid, flows) in uni_flows.items():
926 1
            self._send_flow_mods(dpid, flows)
927
928 1
    @staticmethod
929 1
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
930
        """Send a flow_mod list to a specific switch.
931
932
        Args:
933
            dpid(str): The target of flows (i.e. Switch.id).
934
            flow_mods(dict): Python dictionary with flow_mods.
935
            command(str): By default is 'flows'. To remove a flow is 'remove'.
936
            force(bool): True to send via consistency check in case of errors
937
938
        """
939
940 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
941
942 1
        data = {"flows": flow_mods, "force": force}
943 1
        response = requests.post(endpoint, json=data)
944 1
        if response.status_code >= 400:
945 1
            raise FlowModException(str(response.text))
946
947 1
    def get_cookie(self):
948
        """Return the cookie integer from evc id."""
949 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
950
951 1
    @staticmethod
952 1
    def get_id_from_cookie(cookie):
953
        """Return the evc id given a cookie value."""
954 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
955 1
        return f"{evc_id:x}".zfill(14)
956
957 1
    def _prepare_flow_mod(self, in_interface, out_interface,
958
                          queue_id=None, is_EVPL=True):
959
        """Prepare a common flow mod."""
960 1
        default_actions = [
961
            {"action_type": "output", "port": out_interface.port_number}
962
        ]
963 1
        if queue_id is not None:
964
            default_actions.append(
965
                {"action_type": "set_queue", "queue_id": queue_id}
966
            )
967
968 1
        flow_mod = {
969
            "match": {"in_port": in_interface.port_number},
970
            "cookie": self.get_cookie(),
971
            "actions": default_actions,
972
        }
973 1
        if self.sb_priority:
974
            flow_mod["priority"] = self.sb_priority
975
        else:
976 1
            if is_EVPL:
977 1
                flow_mod["priority"] = settings.EVPL_SB_PRIORITY
978
            else:
979 1
                flow_mod["priority"] = settings.EPL_SB_PRIORITY
980 1
        return flow_mod
981
982 1
    def _prepare_nni_flow(self, *args, queue_id=None):
983
        """Create NNI flows."""
984 1
        in_interface, out_interface, in_vlan, out_vlan = args
985 1
        flow_mod = self._prepare_flow_mod(
986
            in_interface, out_interface, queue_id
987
        )
988 1
        flow_mod["match"]["dl_vlan"] = in_vlan
989
990 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
991 1
        flow_mod["actions"].insert(0, new_action)
992
993 1
        return flow_mod
994
995
    # pylint: disable=too-many-arguments
996 1
    def _prepare_push_flow(self, *args, queue_id=None):
997
        """Prepare push flow.
998
999
        Arguments:
1000
            in_interface(str): Interface input.
1001
            out_interface(str): Interface output.
1002
            in_vlan(str): Vlan input.
1003
            out_vlan(str): Vlan output.
1004
            new_c_vlan(str): New client vlan.
1005
1006
        Return:
1007
            dict: An python dictionary representing a FlowMod
1008
1009
        """
1010
        # assign all arguments
1011 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
1012 1
        is_EVPL = (in_vlan is not None)
1013 1
        flow_mod = self._prepare_flow_mod(
1014
            in_interface, out_interface, queue_id, is_EVPL
1015
        )
1016
1017
        # the service tag must be always pushed
1018 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1019 1
        flow_mod["actions"].insert(0, new_action)
1020
1021 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
1022 1
        flow_mod["actions"].insert(0, new_action)
1023
1024 1
        if in_vlan:
1025
            # if in_vlan is set, it must be included in the match
1026 1
            flow_mod["match"]["dl_vlan"] = in_vlan
1027 1
        if new_c_vlan:
1028
            # new_in_vlan is set, so an action to set it is necessary
1029 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
1030 1
            flow_mod["actions"].insert(0, new_action)
1031 1
            if not in_vlan:
1032
                # new_in_vlan is set, but in_vlan is not, so there was no
1033
                # vlan set; then it is set now
1034 1
                new_action = {"action_type": "push_vlan", "tag_type": "c"}
1035 1
                flow_mod["actions"].insert(0, new_action)
1036 1
        elif in_vlan:
1037
            # in_vlan is set, but new_in_vlan is not, so the existing vlan
1038
            # must be removed
1039 1
            new_action = {"action_type": "pop_vlan"}
1040 1
            flow_mod["actions"].insert(0, new_action)
1041 1
        return flow_mod
1042
1043 1
    def _prepare_pop_flow(
1044
        self, in_interface, out_interface, out_vlan, queue_id=None
1045
    ):
1046
        # pylint: disable=too-many-arguments
1047
        """Prepare pop flow."""
1048 1
        flow_mod = self._prepare_flow_mod(
1049
            in_interface, out_interface, queue_id
1050
        )
1051 1
        flow_mod["match"]["dl_vlan"] = out_vlan
1052 1
        new_action = {"action_type": "pop_vlan"}
1053 1
        flow_mod["actions"].insert(0, new_action)
1054 1
        return flow_mod
1055
1056 1 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1057 1
    def run_sdntrace(uni):
1058
        """Run SDN trace on control plane starting from EVC UNIs."""
1059 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/trace"
1060 1
        data_uni = {
1061
            "trace": {
1062
                "switch": {
1063
                    "dpid": uni.interface.switch.dpid,
1064
                    "in_port": uni.interface.port_number,
1065
                }
1066
            }
1067
        }
1068 1
        if uni.user_tag:
1069 1
            data_uni["trace"]["eth"] = {
1070
                "dl_type": 0x8100,
1071
                "dl_vlan": uni.user_tag.value,
1072
            }
1073 1
        response = requests.put(endpoint, json=data_uni)
1074 1
        if response.status_code >= 400:
1075 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1076 1
            return []
1077 1
        return response.json().get('result', [])
1078
1079 1 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
1080 1
    def run_sdntraces(uni_list):
1081
        """Run SDN traces on control plane starting from EVC UNIs."""
1082 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/traces"
1083 1
        data = []
1084 1
        for uni in uni_list:
1085 1
            data_uni = {
1086
                "trace": {
1087
                            "switch": {
1088
                                "dpid": uni.interface.switch.dpid,
1089
                                "in_port": uni.interface.port_number,
1090
                            }
1091
                        }
1092
                }
1093 1
            if uni.user_tag:
1094 1
                data_uni["trace"]["eth"] = {
1095
                                            "dl_type": 0x8100,
1096
                                            "dl_vlan": uni.user_tag.value,
1097
                                            }
1098 1
            data.append(data_uni)
1099 1
        response = requests.put(endpoint, json=data)
1100 1
        if response.status_code >= 400:
1101 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1102 1
            return []
1103 1
        return response.json()
1104
1105 1
    def check_traces(self):
1106
        """Check if current_path is deployed comparing with SDN traces."""
1107 1
        dpid_a = self.uni_a.interface.switch.dpid
1108 1
        port_a = self.uni_a.interface.port_number
1109 1
        dpid_z = self.uni_z.interface.switch.dpid
1110 1
        port_z = self.uni_z.interface.port_number
1111
1112 1
        traces = self.run_sdntraces([self.uni_a, self.uni_z])
1113 1
        if dpid_a != dpid_z:
1114 1
            traces = traces[dpid_a] + traces[dpid_z]
1115
        else:
1116
            traces = traces[dpid_a]
1117 1
        trace_a = None
1118 1
        trace_z = None
1119 1
        for trace in traces:
1120 1
            if (trace[0]['dpid'] == dpid_a) and (trace[0]['port'] == port_a):
1121 1
                trace_a = trace
1122 1
            elif (trace[0]['dpid'] == dpid_z) and (trace[0]['port'] == port_z):
1123 1
                trace_z = trace
1124 1
            if (trace_a is not None) and (trace_z is not None):
1125 1
                break
1126 1
        if len(trace_a) != len(self.current_path) + 1:
1127 1
            log.warning(f"Invalid trace from uni_a: {trace_a}")
1128 1
            return False
1129 1
        if len(trace_z) != len(self.current_path) + 1:
1130 1
            log.warning(f"Invalid trace from uni_z: {trace_z}")
1131 1
            return False
1132
1133 1
        for link, trace1, trace2 in zip(self.current_path,
1134
                                        trace_a[1:],
1135
                                        trace_z[:0:-1]):
1136 1
            if compare_endpoint_trace(
1137
               link.endpoint_a,
1138
               glom(link.metadata, 's_vlan.value'), trace2) is False:
1139 1
                log.warning(f"Invalid trace from uni_a: {trace_a}")
1140 1
                return False
1141 1
            if compare_endpoint_trace(
1142
               link.endpoint_b,
1143
               glom(link.metadata, 's_vlan.value'), trace1) is False:
1144 1
                log.warning(f"Invalid trace from uni_z: {trace_z}")
1145 1
                return False
1146
1147 1
        return True
1148
1149
1150 1
class LinkProtection(EVCDeploy):
1151
    """Class to handle link protection."""
1152
1153 1
    def is_affected_by_link(self, link=None):
1154
        """Verify if the current path is affected by link down event."""
1155
        return self.current_path.is_affected_by_link(link)
1156
1157 1
    def is_using_primary_path(self):
1158
        """Verify if the current deployed path is self.primary_path."""
1159 1
        return self.current_path == self.primary_path
1160
1161 1
    def is_using_backup_path(self):
1162
        """Verify if the current deployed path is self.backup_path."""
1163 1
        return self.current_path == self.backup_path
1164
1165 1
    def is_using_dynamic_path(self):
1166
        """Verify if the current deployed path is dynamic."""
1167 1
        if (
1168
            self.current_path
1169
            and not self.is_using_primary_path()
1170
            and not self.is_using_backup_path()
1171
            and self.current_path.status is EntityStatus.UP
1172
        ):
1173
            return True
1174 1
        return False
1175
1176 1
    def deploy_to(self, path_name=None, path=None):
1177
        """Create a deploy to path."""
1178 1
        if self.current_path == path:
1179 1
            log.debug(f"{path_name} is equal to current_path.")
1180 1
            return True
1181
1182 1
        if path.status is EntityStatus.UP:
1183 1
            return self.deploy_to_path(path)
1184
1185 1
        return False
1186
1187 1
    def handle_link_up(self, link):
1188
        """Handle circuit when link down.
1189
1190
        Args:
1191
            link(Link): Link affected by link.down event.
1192
1193
        """
1194 1
        if self.is_using_primary_path():
1195 1
            return True
1196
1197 1
        success = False
1198 1
        if self.primary_path.is_affected_by_link(link):
1199 1
            success = self.deploy_to_primary_path()
1200
1201 1
        if success:
1202 1
            return True
1203
1204
        # We tried to deploy(primary_path) without success.
1205
        # And in this case is up by some how. Nothing to do.
1206 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1207 1
            return True
1208
1209
        # In this case, probably the circuit is not being used and
1210
        # we can move to backup
1211 1
        if self.backup_path.is_affected_by_link(link):
1212 1
            success = self.deploy_to_backup_path()
1213
1214
        # In this case, the circuit is not being used and we should
1215
        # try a dynamic path
1216 1
        if not success and self.dynamic_backup_path:
1217 1
            success = self.deploy_to_path()
1218
1219 1
        if success:
1220 1
            emit_event(self._controller, "redeployed_link_up", evc_id=self.id)
1221 1
            return True
1222
1223 1
        return True
1224
1225 1
    def handle_link_down(self):
1226
        """Handle circuit when link down.
1227
1228
        Returns:
1229
            bool: True if the re-deploy was successly otherwise False.
1230
1231
        """
1232 1
        success = False
1233 1
        if self.is_using_primary_path():
1234 1
            success = self.deploy_to_backup_path()
1235 1
        elif self.is_using_backup_path():
1236 1
            success = self.deploy_to_primary_path()
1237
1238 1
        if not success and self.dynamic_backup_path:
1239 1
            success = self.deploy_to_path()
1240
1241 1
        if success:
1242 1
            log.debug(f"{self} deployed after link down.")
1243
        else:
1244 1
            self.deactivate()
1245 1
            self.current_path = Path([])
1246 1
            self.sync()
1247 1
            log.debug(f"Failed to re-deploy {self} after link down.")
1248
1249 1
        return success
1250
1251
1252 1
class EVC(LinkProtection):
1253
    """Class that represents a E-Line Virtual Connection."""
1254