Passed
Pull Request — master (#166)
by Antonio
06:26 queued 54s
created

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

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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