Passed
Pull Request — master (#166)
by Italo Valcy
03:51
created

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

Complexity

Conditions 3

Size

Total Lines 93
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 37
nop 3
dl 0
loc 93
ccs 37
cts 37
cp 1
crap 3
rs 8.9919
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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