Passed
Pull Request — master (#90)
by Antonio
12:57 queued 10:07
created

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

Complexity

Conditions 2

Size

Total Lines 33
Code Lines 13

Duplication

Lines 32
Ratio 96.97 %

Code Coverage

Tests 12
CRAP Score 2

Importance

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