Passed
Push — master ( 4fc02b...d65ad0 )
by Antonio
03:34
created

build.models.evc   F

Complexity

Total Complexity 153

Size/Duplication

Total Lines 960
Duplicated Lines 0 %

Test Coverage

Coverage 83.7%

Importance

Changes 0
Metric Value
wmc 153
eloc 556
dl 0
loc 960
ccs 385
cts 460
cp 0.837
rs 2
c 0
b 0
f 0

49 Methods

Rating   Name   Duplication   Size   Complexity  
A EVCDeploy.link_affected_by_interface() 0 3 1
A EVCDeploy.remove() 0 6 1
B EVCDeploy.deploy_to_backup_path() 0 28 6
A EVCDeploy.reprovision() 0 2 1
A EVCDeploy.create() 0 2 1
A EVCBase.__repr__() 0 3 1
B EVCBase._validate() 0 24 6
A EVCBase.as_dict() 0 54 4
A EVCDeploy.deploy_to_primary_path() 0 14 3
A EVCBase.__eq__() 0 10 4
A EVCBase.archive() 0 3 1
A EVCBase.shares_uni() 0 8 3
A EVCDeploy.discover_new_paths() 0 3 1
A EVCDeploy.change_path() 0 2 1
A EVCDeploy.is_backup_path_affected_by_link() 0 3 1
A EVCDeploy.is_using_backup_path() 0 3 1
A EVCBase.sync() 0 3 1
A LinkProtection.is_using_dynamic_path() 0 10 5
A LinkProtection.is_affected_by_link() 0 3 1
D EVCDeploy.deploy_to_path() 0 59 12
A EVCDeploy._prepare_nni_flow() 0 12 1
A EVCDeploy.run_sdntrace() 0 22 3
B EVCDeploy._install_uni_flows() 0 62 4
A EVCDeploy.is_primary_path_affected_by_link() 0 3 1
A EVCBase.id() 0 4 1
A EVCDeploy.get_path_status() 0 13 4
A EVCDeploy.get_id_from_cookie() 0 5 1
B EVCDeploy._prepare_push_flow() 0 46 5
A EVCDeploy.links_zipped() 0 6 2
A EVCDeploy.is_using_dynamic_path() 0 10 5
B EVCDeploy.remove_current_flows() 0 32 6
B EVCDeploy.check_traces() 0 26 6
A LinkProtection.is_using_primary_path() 0 3 1
C EVCBase.update() 0 43 10
A EVCDeploy._send_flow_mods() 0 17 2
A LinkProtection.is_using_backup_path() 0 3 1
C LinkProtection.handle_link_up() 0 36 9
A EVCDeploy.should_deploy() 0 15 4
A EVCDeploy.get_cookie() 0 3 1
A EVCDeploy._prepare_pop_flow() 0 12 1
A LinkProtection.deploy_to() 0 10 3
B EVCBase.__init__() 0 93 3
B EVCDeploy._install_direct_uni_flows() 0 39 7
A EVCDeploy.is_affected_by_link() 0 3 1
A EVCDeploy.is_using_primary_path() 0 3 1
A EVCDeploy._install_nni_flows() 0 29 2
B LinkProtection.handle_link_down() 0 25 6
A EVCDeploy._prepare_flow_mod() 0 19 3
A EVCDeploy.deploy() 0 16 4

How to fix   Complexity   

Complexity

Complex classes like build.models.evc often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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 (compare_endpoint_trace, emit_event,
17
                                         notify_link_available_tags)
18
19 1
from .path import DynamicPathManager, Path
20
21
22 1
class EVCBase(GenericEntity):
23
    """Class to represent a circuit."""
24
25 1
    read_only_attributes = [
26
        "creation_time",
27
        "active",
28
        "current_path",
29
        "_id",
30
        "archived",
31
    ]
32 1
    attributes_requiring_redeploy = [
33
        "primary_path",
34
        "backup_path",
35
        "dynamic_backup_path",
36
        "queue_id",
37
        "priority",
38
    ]
39 1
    required_attributes = ["name", "uni_a", "uni_z"]
40
41 1
    def __init__(self, controller, **kwargs):
42
        """Create an EVC instance with the provided parameters.
43
44
        Args:
45
            id(str): EVC identifier. Whether it's None an ID will be genereted.
46
                     Only the first 14 bytes passed will be used.
47
            name: represents an EVC name.(Required)
48
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
49
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
50
            start_date(datetime|str): Date when the EVC was registred.
51
                                      Default is now().
52
            end_date(datetime|str): Final date that the EVC will be fineshed.
53
                                    Default is None.
54
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
55
            primary_links(list): Primary links used by evc. Default is []
56
            backup_links(list): Backups links used by evc. Default is []
57
            current_path(list): Circuit being used at the moment if this is an
58
                                active circuit. Default is [].
59
            primary_path(list): primary circuit offered to user IF one or more
60
                                links were provided. Default is [].
61
            backup_path(list): backup circuit offered to the user IF one or
62
                               more links were provided. Default is [].
63
            dynamic_backup_path(bool): Enable computer backup path dynamically.
64
                                       Dafault is False.
65
            creation_time(datetime|str): datetime when the circuit should be
66
                                         activated. default is now().
67
            enabled(Boolean): attribute to indicate the administrative state;
68
                              default is False.
69
            active(Boolean): attribute to indicate the operational state;
70
                             default is False.
71
            archived(Boolean): indicate the EVC has been deleted and is
72
                               archived; default is False.
73
            owner(str): The EVC owner. Default is None.
74
            priority(int): Service level provided in the request. Default is 0.
75
76
        Raises:
77
            ValueError: raised when object attributes are invalid.
78
79
        """
80 1
        self._validate(**kwargs)
81 1
        super().__init__()
82
83
        # required attributes
84 1
        self._id = kwargs.get("id", uuid4().hex)[:14]
85 1
        self.uni_a = kwargs.get("uni_a")
86 1
        self.uni_z = kwargs.get("uni_z")
87 1
        self.name = kwargs.get("name")
88
89
        # optional attributes
90 1
        self.start_date = get_time(kwargs.get("start_date")) or now()
91 1
        self.end_date = get_time(kwargs.get("end_date")) or None
92 1
        self.queue_id = kwargs.get("queue_id", None)
93
94 1
        self.bandwidth = kwargs.get("bandwidth", 0)
95 1
        self.primary_links = Path(kwargs.get("primary_links", []))
96 1
        self.backup_links = Path(kwargs.get("backup_links", []))
97 1
        self.current_path = Path(kwargs.get("current_path", []))
98 1
        self.primary_path = Path(kwargs.get("primary_path", []))
99 1
        self.backup_path = Path(kwargs.get("backup_path", []))
100 1
        self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False)
101 1
        self.creation_time = get_time(kwargs.get("creation_time")) or now()
102 1
        self.owner = kwargs.get("owner", None)
103 1
        self.priority = kwargs.get("priority", -1)
104 1
        self.circuit_scheduler = kwargs.get("circuit_scheduler", [])
105
106 1
        self.current_links_cache = set()
107 1
        self.primary_links_cache = set()
108 1
        self.backup_links_cache = set()
109
110 1
        self.lock = Lock()
111
112 1
        self.archived = kwargs.get("archived", False)
113
114 1
        self.metadata = kwargs.get("metadata", {})
115
116 1
        self._controller = controller
117 1
        self._mongo_controller = controllers.ELineController()
118
119 1
        if kwargs.get("active", False):
120 1
            self.activate()
121
        else:
122 1
            self.deactivate()
123
124 1
        if kwargs.get("enabled", False):
125 1
            self.enable()
126
        else:
127 1
            self.disable()
128
129
        # datetime of user request for a EVC (or datetime when object was
130
        # created)
131 1
        self.request_time = kwargs.get("request_time", now())
132
        # dict with the user original request (input)
133 1
        self._requested = kwargs
134
135 1
    def sync(self):
136
        """Sync this EVC in the MongoDB."""
137 1
        self._mongo_controller.upsert_evc(self.as_dict())
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 1
                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(  # pylint: disable=raise-missing-from
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 1
    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 1
        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 1
        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 1
        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 1
        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 1
        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 1
        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 1
        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 1
        if self.archived:
401
            return False
402 1
        self.enable()
403 1
        success = self.deploy_to_primary_path()
404 1
        if not success:
405
            success = self.deploy_to_backup_path()
406
407 1
        if success:
408 1
            emit_event(self._controller, "deployed", evc_id=self.id)
409 1
        return success
410
411 1
    @staticmethod
412 1
    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, force=True):
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', force=force)
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
        for link in current_path:
463 1
            notify_link_available_tags(self._controller, link)
464 1
        self.current_path = Path([])
465 1
        self.deactivate()
466 1
        self.sync()
467
468 1
    @staticmethod
469 1
    def links_zipped(path=None):
470
        """Return an iterator which yields pairs of links in order."""
471 1
        if not path:
472
            return []
473 1
        return zip(path[:-1], path[1:])
474
475 1
    def should_deploy(self, path=None):
476
        """Verify if the circuit should be deployed."""
477 1
        if not path:
478 1
            log.debug("Path is empty.")
479 1
            return False
480
481 1
        if not self.is_enabled():
482 1
            log.debug(f"{self} is disabled.")
483 1
            return False
484
485 1
        if not self.is_active():
486 1
            log.debug(f"{self} will be deployed.")
487 1
            return True
488
489 1
        return False
490
491 1
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
492
        """Install the flows for this circuit.
493
494
        Procedures to deploy:
495
496
        0. Remove current flows installed
497
        1. Decide if will deploy "path" or discover a new path
498
        2. Choose vlan
499
        3. Install NNI flows
500
        4. Install UNI flows
501
        5. Activate
502
        6. Update current_path
503
        7. Update links caches(primary, current, backup)
504
505
        """
506 1
        self.remove_current_flows()
507 1
        use_path = path
508 1
        if self.should_deploy(use_path):
509 1
            try:
510 1
                use_path.choose_vlans()
511 1
                for link in use_path:
512 1
                    notify_link_available_tags(self._controller, link)
513
            except KytosNoTagAvailableError:
514
                use_path = None
515
        else:
516 1
            for use_path in self.discover_new_paths():
517 1
                if use_path is None:
518
                    continue
519 1
                try:
520 1
                    use_path.choose_vlans()
521 1
                    for link in use_path:
522 1
                        notify_link_available_tags(self._controller, link)
523 1
                    break
524
                except KytosNoTagAvailableError:
525
                    pass
526
            else:
527 1
                use_path = None
528
529 1
        try:
530 1
            if use_path:
531 1
                self._install_nni_flows(use_path)
532 1
                self._install_uni_flows(use_path)
533 1
            elif self.uni_a.interface.switch == self.uni_z.interface.switch:
534
                use_path = Path()
535
                self._install_direct_uni_flows()
536
            else:
537 1
                log.warn(
538
                    f"{self} was not deployed. " "No available path was found."
539
                )
540 1
                return False
541 1
        except FlowModException:
542 1
            log.error(f"Error deploying EVC {self} when calling flow_manager.")
543 1
            self.remove_current_flows(use_path)
544 1
            return False
545 1
        self.activate()
546 1
        self.current_path = use_path
547 1
        self.sync()
548 1
        log.info(f"{self} was deployed.")
549 1
        return True
550
551 1
    def _install_direct_uni_flows(self):
552
        """Install flows connecting two UNIs.
553
554
        This case happens when the circuit is between UNIs in the
555
        same switch.
556
        """
557 1
        vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
558 1
        vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
559
560 1
        flow_mod_az = self._prepare_flow_mod(
561
            self.uni_a.interface, self.uni_z.interface, self.queue_id
562
        )
563 1
        flow_mod_za = self._prepare_flow_mod(
564
            self.uni_z.interface, self.uni_a.interface, self.queue_id
565
        )
566
567 1
        if vlan_a and vlan_z:
568 1
            flow_mod_az["match"]["dl_vlan"] = vlan_a
569 1
            flow_mod_za["match"]["dl_vlan"] = vlan_z
570 1
            flow_mod_az["actions"].insert(
571
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
572
            )
573 1
            flow_mod_za["actions"].insert(
574
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
575
            )
576
        elif vlan_a:
577
            flow_mod_az["match"]["dl_vlan"] = vlan_a
578
            flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
579
            flow_mod_za["actions"].insert(
580
                0, {"action_type": "set_vlan", "vlan_id": vlan_a}
581
            )
582
        elif vlan_z:
583
            flow_mod_za["match"]["dl_vlan"] = vlan_z
584
            flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
585
            flow_mod_az["actions"].insert(
586
                0, {"action_type": "set_vlan", "vlan_id": vlan_z}
587
            )
588 1
        self._send_flow_mods(
589
            self.uni_a.interface.switch, [flow_mod_az, flow_mod_za]
590
        )
591
592 1
    def _install_nni_flows(self, path=None):
593
        """Install NNI flows."""
594 1
        for incoming, outcoming in self.links_zipped(path):
595 1
            in_vlan = incoming.get_metadata("s_vlan").value
596 1
            out_vlan = outcoming.get_metadata("s_vlan").value
597
598 1
            flows = []
599
            # Flow for one direction
600 1
            flows.append(
601
                self._prepare_nni_flow(
602
                    incoming.endpoint_b,
603
                    outcoming.endpoint_a,
604
                    in_vlan,
605
                    out_vlan,
606
                    queue_id=self.queue_id,
607
                )
608
            )
609
610
            # Flow for the other direction
611 1
            flows.append(
612
                self._prepare_nni_flow(
613
                    outcoming.endpoint_a,
614
                    incoming.endpoint_b,
615
                    out_vlan,
616
                    in_vlan,
617
                    queue_id=self.queue_id,
618
                )
619
            )
620 1
            self._send_flow_mods(incoming.endpoint_b.switch, flows)
621
622 1
    def _install_uni_flows(self, path=None):
623
        """Install UNI flows."""
624 1
        if not path:
625
            log.info("install uni flows without path.")
626
            return
627
628
        # Determine VLANs
629 1
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
630 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
631
632 1
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
633 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
634
635
        # Flows for the first UNI
636 1
        flows_a = []
637
638
        # Flow for one direction, pushing the service tag
639 1
        push_flow = self._prepare_push_flow(
640
            self.uni_a.interface,
641
            path[0].endpoint_a,
642
            in_vlan_a,
643
            out_vlan_a,
644
            in_vlan_z,
645
            queue_id=self.queue_id,
646
        )
647 1
        flows_a.append(push_flow)
648
649
        # Flow for the other direction, popping the service tag
650 1
        pop_flow = self._prepare_pop_flow(
651
            path[0].endpoint_a,
652
            self.uni_a.interface,
653
            out_vlan_a,
654
            queue_id=self.queue_id,
655
        )
656 1
        flows_a.append(pop_flow)
657
658 1
        self._send_flow_mods(self.uni_a.interface.switch, flows_a)
659
660
        # Flows for the second UNI
661 1
        flows_z = []
662
663
        # Flow for one direction, pushing the service tag
664 1
        push_flow = self._prepare_push_flow(
665
            self.uni_z.interface,
666
            path[-1].endpoint_b,
667
            in_vlan_z,
668
            out_vlan_z,
669
            in_vlan_a,
670
            queue_id=self.queue_id,
671
        )
672 1
        flows_z.append(push_flow)
673
674
        # Flow for the other direction, popping the service tag
675 1
        pop_flow = self._prepare_pop_flow(
676
            path[-1].endpoint_b,
677
            self.uni_z.interface,
678
            out_vlan_z,
679
            queue_id=self.queue_id,
680
        )
681 1
        flows_z.append(pop_flow)
682
683 1
        self._send_flow_mods(self.uni_z.interface.switch, flows_z)
684
685 1
    @staticmethod
686 1
    def _send_flow_mods(switch, flow_mods, command='flows', force=False):
687
        """Send a flow_mod list to a specific switch.
688
689
        Args:
690
            switch(Switch): The target of flows.
691
            flow_mods(dict): Python dictionary with flow_mods.
692
            command(str): By default is 'flows'. To remove a flow is 'remove'.
693
            force(bool): True to send via consistency check in case of errors
694
695
        """
696 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{switch.id}"
697
698 1
        data = {"flows": flow_mods, "force": force}
699 1
        response = requests.post(endpoint, json=data)
700 1
        if response.status_code >= 400:
701 1
            raise FlowModException
702
703 1
    def get_cookie(self):
704
        """Return the cookie integer from evc id."""
705 1
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
706
707 1
    @staticmethod
708 1
    def get_id_from_cookie(cookie):
709
        """Return the evc id given a cookie value."""
710 1
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
711 1
        return f"{evc_id:x}".zfill(14)
712
713 1
    def _prepare_flow_mod(self, in_interface, out_interface, queue_id=None):
714
        """Prepare a common flow mod."""
715 1
        default_actions = [
716
            {"action_type": "output", "port": out_interface.port_number}
717
        ]
718 1
        if queue_id:
719
            default_actions.append(
720
                {"action_type": "set_queue", "queue_id": queue_id}
721
            )
722
723 1
        flow_mod = {
724
            "match": {"in_port": in_interface.port_number},
725
            "cookie": self.get_cookie(),
726
            "actions": default_actions,
727
        }
728 1
        if self.priority > -1:
729
            flow_mod["priority"] = self.priority
730
731 1
        return flow_mod
732
733 1
    def _prepare_nni_flow(self, *args, queue_id=None):
734
        """Create NNI flows."""
735 1
        in_interface, out_interface, in_vlan, out_vlan = args
736 1
        flow_mod = self._prepare_flow_mod(
737
            in_interface, out_interface, queue_id
738
        )
739 1
        flow_mod["match"]["dl_vlan"] = in_vlan
740
741 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
742 1
        flow_mod["actions"].insert(0, new_action)
743
744 1
        return flow_mod
745
746 1
    def _prepare_push_flow(self, *args, queue_id=None):
747
        """Prepare push flow.
748
749
        Arguments:
750
            in_interface(str): Interface input.
751
            out_interface(str): Interface output.
752
            in_vlan(str): Vlan input.
753
            out_vlan(str): Vlan output.
754
            new_c_vlan(str): New client vlan.
755
756
        Return:
757
            dict: An python dictionary representing a FlowMod
758
759
        """
760
        # assign all arguments
761 1
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
762
763 1
        flow_mod = self._prepare_flow_mod(
764
            in_interface, out_interface, queue_id
765
        )
766
767
        # the service tag must be always pushed
768 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
769 1
        flow_mod["actions"].insert(0, new_action)
770
771 1
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
772 1
        flow_mod["actions"].insert(0, new_action)
773
774 1
        if in_vlan:
775
            # if in_vlan is set, it must be included in the match
776 1
            flow_mod["match"]["dl_vlan"] = in_vlan
777 1
        if new_c_vlan:
778
            # new_in_vlan is set, so an action to set it is necessary
779 1
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
780 1
            flow_mod["actions"].insert(0, new_action)
781 1
            if not in_vlan:
782
                # new_in_vlan is set, but in_vlan is not, so there was no
783
                # vlan set; then it is set now
784 1
                new_action = {"action_type": "push_vlan", "tag_type": "c"}
785 1
                flow_mod["actions"].insert(0, new_action)
786 1
        elif in_vlan:
787
            # in_vlan is set, but new_in_vlan is not, so the existing vlan
788
            # must be removed
789 1
            new_action = {"action_type": "pop_vlan"}
790 1
            flow_mod["actions"].insert(0, new_action)
791 1
        return flow_mod
792
793 1
    def _prepare_pop_flow(
794
        self, in_interface, out_interface, out_vlan, queue_id=None
795
    ):
796
        # pylint: disable=too-many-arguments
797
        """Prepare pop flow."""
798 1
        flow_mod = self._prepare_flow_mod(
799
            in_interface, out_interface, queue_id
800
        )
801 1
        flow_mod["match"]["dl_vlan"] = out_vlan
802 1
        new_action = {"action_type": "pop_vlan"}
803 1
        flow_mod["actions"].insert(0, new_action)
804 1
        return flow_mod
805
806 1
    @staticmethod
807 1
    def run_sdntrace(uni):
808
        """Run SDN trace on control plane starting from EVC UNIs."""
809
        endpoint = f"{settings.SDN_TRACE_CP_URL}/trace"
810
        data_uni = {
811
            "trace": {
812
                "switch": {
813
                    "dpid": uni.interface.switch.dpid,
814
                    "in_port": uni.interface.port_number,
815
                }
816
            }
817
        }
818
        if uni.user_tag:
819
            data_uni["trace"]["eth"] = {
820
                "dl_type": 0x8100,
821
                "dl_vlan": uni.user_tag.value,
822
            }
823
        response = requests.put(endpoint, json=data_uni)
824
        if response.status_code >= 400:
825
            log.error(f"Failed to run sdntrace-cp: {response.text}")
826
            return []
827
        return response.json().get('result', [])
828
829 1
    def check_traces(self):
830
        """Check if current_path is deployed comparing with SDN traces."""
831
        trace_a = self.run_sdntrace(self.uni_a)
832
        if len(trace_a) != len(self.current_path) + 1:
833
            log.warn(f"Invalid trace from uni_a: {trace_a}")
834
            return False
835
        trace_z = self.run_sdntrace(self.uni_z)
836
        if len(trace_z) != len(self.current_path) + 1:
837
            log.warn(f"Invalid trace from uni_z: {trace_z}")
838
            return False
839
840
        for link, trace1, trace2 in zip(self.current_path,
841
                                        trace_a[1:],
842
                                        trace_z[:0:-1]):
843
            if compare_endpoint_trace(
844
               link.endpoint_a,
845
               glom(link.metadata, 's_vlan.value'), trace2) is False:
846
                log.warn(f"Invalid trace from uni_a: {trace_a}")
847
                return False
848
            if compare_endpoint_trace(
849
               link.endpoint_b,
850
               glom(link.metadata, 's_vlan.value'), trace1) is False:
851
                log.warn(f"Invalid trace from uni_z: {trace_z}")
852
                return False
853
854
        return True
855
856
857 1
class LinkProtection(EVCDeploy):
858
    """Class to handle link protection."""
859
860 1
    def is_affected_by_link(self, link=None):
861
        """Verify if the current path is affected by link down event."""
862
        return self.current_path.is_affected_by_link(link)
863
864 1
    def is_using_primary_path(self):
865
        """Verify if the current deployed path is self.primary_path."""
866 1
        return self.current_path == self.primary_path
867
868 1
    def is_using_backup_path(self):
869
        """Verify if the current deployed path is self.backup_path."""
870 1
        return self.current_path == self.backup_path
871
872 1
    def is_using_dynamic_path(self):
873
        """Verify if the current deployed path is dynamic."""
874 1
        if (
875
            self.current_path
876
            and not self.is_using_primary_path()
877
            and not self.is_using_backup_path()
878
            and self.current_path.status is EntityStatus.UP
879
        ):
880
            return True
881 1
        return False
882
883 1
    def deploy_to(self, path_name=None, path=None):
884
        """Create a deploy to path."""
885 1
        if self.current_path == path:
886 1
            log.debug(f"{path_name} is equal to current_path.")
887 1
            return True
888
889 1
        if path.status is EntityStatus.UP:
890 1
            return self.deploy_to_path(path)
891
892 1
        return False
893
894 1
    def handle_link_up(self, link):
895
        """Handle circuit when link down.
896
897
        Args:
898
            link(Link): Link affected by link.down event.
899
900
        """
901 1
        if self.is_using_primary_path():
902 1
            return True
903
904 1
        success = False
905 1
        if self.primary_path.is_affected_by_link(link):
906 1
            success = self.deploy_to_primary_path()
907
908 1
        if success:
909 1
            return True
910
911
        # We tried to deploy(primary_path) without success.
912
        # And in this case is up by some how. Nothing to do.
913 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
914
            return True
915
916
        # In this case, probably the circuit is not being used and
917
        # we can move to backup
918 1
        if self.backup_path.is_affected_by_link(link):
919 1
            success = self.deploy_to_backup_path()
920
921 1
        if success:
922 1
            return True
923
924
        # In this case, the circuit is not being used and we should
925
        # try a dynamic path
926
        if self.dynamic_backup_path:
927
            return self.deploy_to_path()
928
929
        return True
930
931 1
    def handle_link_down(self):
932
        """Handle circuit when link down.
933
934
        Returns:
935
            bool: True if the re-deploy was successly otherwise False.
936
937
        """
938 1
        success = False
939 1
        if self.is_using_primary_path():
940 1
            success = self.deploy_to_backup_path()
941 1
        elif self.is_using_backup_path():
942 1
            success = self.deploy_to_primary_path()
943
944 1
        if not success and self.dynamic_backup_path:
945 1
            success = self.deploy_to_path()
946
947 1
        if success:
948 1
            log.debug(f"{self} deployed after link down.")
949
        else:
950 1
            self.deactivate()
951 1
            self.current_path = Path([])
952 1
            self.sync()
953 1
            log.debug(f"Failed to re-deploy {self} after link down.")
954
955 1
        return success
956
957
958 1
class EVC(LinkProtection):
959
    """Class that represents a E-Line Virtual Connection."""
960