Test Failed
Pull Request — master (#258)
by
unknown
03:34
created

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

Complexity

Conditions 9

Size

Total Lines 51
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 9

Importance

Changes 0
Metric Value
cc 9
eloc 27
nop 3
dl 0
loc 51
rs 6.6666
c 0
b 0
f 0
ccs 25
cts 25
cp 1
crap 9

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 collections import OrderedDict
3 1
from datetime import datetime
4 1
from threading import Lock
5 1
from uuid import uuid4
6
7 1
import requests
8 1
from glom import glom
9 1
from requests.exceptions import ConnectTimeout
10
11 1
from kytos.core import log
12 1
from kytos.core.common import EntityStatus, GenericEntity
13 1
from kytos.core.exceptions import KytosNoTagAvailableError
14 1
from kytos.core.helpers import get_time, now
15 1
from kytos.core.interface import UNI
16 1
from napps.kytos.mef_eline import controllers, settings
17 1
from napps.kytos.mef_eline.exceptions import FlowModException, InvalidPath
18 1
from napps.kytos.mef_eline.utils import (compare_endpoint_trace,
19
                                         compare_uni_out_trace, emit_event,
20
                                         map_evc_event_content,
21
                                         notify_link_available_tags)
22
23 1
from .path import DynamicPathManager, Path
24
25
26 1
class EVCBase(GenericEntity):
27
    """Class to represent a circuit."""
28
29 1
    read_only_attributes = [
30
        "creation_time",
31
        "active",
32
        "current_path",
33
        "failover_path",
34
        "_id",
35
        "archived",
36
    ]
37 1
    attributes_requiring_redeploy = [
38
        "primary_path",
39
        "backup_path",
40
        "dynamic_backup_path",
41
        "queue_id",
42
        "sb_priority",
43
        "primary_constraints",
44
        "secondary_constraints",
45
        "uni_a",
46
        "uni_z",
47
    ]
48 1
    required_attributes = ["name", "uni_a", "uni_z"]
49
50 1
    def __init__(self, controller, **kwargs):
51
        """Create an EVC instance with the provided parameters.
52
53
        Args:
54
            id(str): EVC identifier. Whether it's None an ID will be genereted.
55
                     Only the first 14 bytes passed will be used.
56
            name: represents an EVC name.(Required)
57
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
58
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
59
            start_date(datetime|str): Date when the EVC was registred.
60
                                      Default is now().
61
            end_date(datetime|str): Final date that the EVC will be fineshed.
62
                                    Default is None.
63
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
64
            primary_links(list): Primary links used by evc. Default is []
65
            backup_links(list): Backups links used by evc. Default is []
66
            current_path(list): Circuit being used at the moment if this is an
67
                                active circuit. Default is [].
68
            failover_path(list): Path being used to provide EVC protection via
69
                                failover during link failures. Default is [].
70
            primary_path(list): primary circuit offered to user IF one or more
71
                                links were provided. Default is [].
72
            backup_path(list): backup circuit offered to the user IF one or
73
                               more links were provided. Default is [].
74
            dynamic_backup_path(bool): Enable computer backup path dynamically.
75
                                       Dafault is False.
76
            creation_time(datetime|str): datetime when the circuit should be
77
                                         activated. default is now().
78
            enabled(Boolean): attribute to indicate the administrative state;
79
                              default is False.
80
            active(Boolean): attribute to indicate the operational state;
81
                             default is False.
82
            archived(Boolean): indicate the EVC has been deleted and is
83
                               archived; default is False.
84
            owner(str): The EVC owner. Default is None.
85
            sb_priority(int): Service level provided in the request.
86
                              Default is None.
87
            service_level(int): Service level provided. The higher the better.
88
                                Default is 0.
89
90
        Raises:
91
            ValueError: raised when object attributes are invalid.
92
93
        """
94 1
        self._validate(**kwargs)
95 1
        super().__init__()
96
97
        # required attributes
98 1
        self._id = kwargs.get("id", uuid4().hex)[:14]
99 1
        self.uni_a = kwargs.get("uni_a")
100 1
        self.uni_z = kwargs.get("uni_z")
101 1
        self.name = kwargs.get("name")
102
103
        # optional attributes
104 1
        self.start_date = get_time(kwargs.get("start_date")) or now()
105 1
        self.end_date = get_time(kwargs.get("end_date")) or None
106 1
        self.queue_id = kwargs.get("queue_id", None)
107
108 1
        self.bandwidth = kwargs.get("bandwidth", 0)
109 1
        self.primary_links = Path(kwargs.get("primary_links", []))
110 1
        self.backup_links = Path(kwargs.get("backup_links", []))
111 1
        self.current_path = Path(kwargs.get("current_path", []))
112 1
        self.failover_path = Path(kwargs.get("failover_path", []))
113 1
        self.primary_path = Path(kwargs.get("primary_path", []))
114 1
        self.backup_path = Path(kwargs.get("backup_path", []))
115 1
        self.dynamic_backup_path = kwargs.get("dynamic_backup_path", False)
116 1
        self.primary_constraints = kwargs.get("primary_constraints", {})
117 1
        self.secondary_constraints = kwargs.get("secondary_constraints", {})
118 1
        self.creation_time = get_time(kwargs.get("creation_time")) or now()
119 1
        self.owner = kwargs.get("owner", None)
120 1
        self.sb_priority = kwargs.get("sb_priority", None) or kwargs.get(
121
            "priority", None
122
        )
123 1
        self.service_level = kwargs.get("service_level", 0)
124 1
        self.circuit_scheduler = kwargs.get("circuit_scheduler", [])
125 1
        self.flow_removed_at = get_time(kwargs.get("flow_removed_at")) or None
126 1
        self.updated_at = get_time(kwargs.get("updated_at")) or now()
127 1
        self.execution_rounds = kwargs.get("execution_rounds", 0)
128
129 1
        self.current_links_cache = set()
130 1
        self.primary_links_cache = set()
131 1
        self.backup_links_cache = set()
132
133 1
        self.lock = Lock()
134
135 1
        self.archived = kwargs.get("archived", False)
136
137 1
        self.metadata = kwargs.get("metadata", {})
138
139 1
        self._controller = controller
140 1
        self._mongo_controller = controllers.ELineController()
141
142 1
        if kwargs.get("active", False):
143 1
            self.activate()
144
        else:
145 1
            self.deactivate()
146
147 1
        if kwargs.get("enabled", False):
148 1
            self.enable()
149
        else:
150 1
            self.disable()
151
152
        # datetime of user request for a EVC (or datetime when object was
153
        # created)
154 1
        self.request_time = kwargs.get("request_time", now())
155
        # dict with the user original request (input)
156 1
        self._requested = kwargs
157
158 1
    def sync(self):
159
        """Sync this EVC in the MongoDB."""
160 1
        self.updated_at = now()
161 1
        self._mongo_controller.upsert_evc(self.as_dict())
162
163 1
    def update(self, **kwargs):
164
        """Update evc attributes.
165
166
        This method will raises an error trying to change the following
167
        attributes: [name, uni_a and uni_z]
168
169
        Returns:
170
            the values for enable and a redeploy attribute, if exists and None
171
            otherwise
172
        Raises:
173
            ValueError: message with error detail.
174
175
        """
176 1
        enable, redeploy = (None, None)
177 1
        uni_a = kwargs.get("uni_a") or self.uni_a
178 1
        uni_z = kwargs.get("uni_z") or self.uni_z
179 1
        self._validate_has_primary_or_dynamic(
180
            primary_path=kwargs.get("primary_path"),
181
            dynamic_backup_path=kwargs.get("dynamic_backup_path"),
182
            uni_a=uni_a,
183
            uni_z=uni_z,
184
        )
185 1
        for attribute, value in kwargs.items():
186 1
            if attribute in self.read_only_attributes:
187 1
                raise ValueError(f"{attribute} can't be updated.")
188 1
            if not hasattr(self, attribute):
189 1
                raise ValueError(f'The attribute "{attribute}" is invalid.')
190 1
            if attribute in ("primary_path", "backup_path"):
191 1
                try:
192 1
                    value.is_valid(
193
                        uni_a.interface.switch, uni_z.interface.switch
194
                    )
195 1
                except InvalidPath as exception:
196 1
                    raise ValueError(  # pylint: disable=raise-missing-from
197
                        f"{attribute} is not a " f"valid path: {exception}"
198
                    )
199 1
        for attribute, value in kwargs.items():
200 1
            if attribute in ("enable", "enabled"):
201 1
                if value:
202 1
                    self.enable()
203
                else:
204 1
                    self.disable()
205 1
                enable = value
206
            else:
207 1
                setattr(self, attribute, value)
208 1
                if attribute in self.attributes_requiring_redeploy:
209 1
                    redeploy = value
210 1
        self.sync()
211 1
        return enable, redeploy
212
213 1
    def set_flow_removed_at(self):
214
        """Update flow_removed_at attribute."""
215
        self.flow_removed_at = now()
216
217 1
    def has_recent_removed_flow(self, setting=settings):
218
        """Check if any flow has been removed from the evc"""
219
        if self.flow_removed_at is None:
220
            return False
221
        res_seconds = (now() - self.flow_removed_at).seconds
222
        return res_seconds < setting.TIME_RECENT_DELETED_FLOWS
223
224 1
    def is_recent_updated(self, setting=settings):
225
        """Check if the evc has been updated recently"""
226
        res_seconds = (now() - self.updated_at).seconds
227
        return res_seconds < setting.TIME_RECENT_UPDATED
228
229 1
    def __repr__(self):
230
        """Repr method."""
231 1
        return f"EVC({self._id}, {self.name})"
232
233 1
    def _validate(self, **kwargs):
234
        """Do Basic validations.
235
236
        Verify required attributes: name, uni_a, uni_z
237
        Verify if the attributes uni_a and uni_z are valid.
238
239
        Raises:
240
            ValueError: message with error detail.
241
242
        """
243 1
        for attribute in self.required_attributes:
244
245 1
            if attribute not in kwargs:
246 1
                raise ValueError(f"{attribute} is required.")
247
248 1
            if "uni" in attribute:
249 1
                uni = kwargs.get(attribute)
250 1
                if not isinstance(uni, UNI):
251
                    raise ValueError(f"{attribute} is an invalid UNI.")
252
253 1
                if not uni.is_valid():
254 1
                    try:
255 1
                        tag = uni.user_tag.value
256 1
                    except AttributeError:
257
                        tag = None
258 1
                    message = f"VLAN tag {tag} is not available in {attribute}"
259
                    raise ValueError(message)
260
261
    def _validate_has_primary_or_dynamic(
262
        self,
263
        primary_path=None,
264
        dynamic_backup_path=None,
265
        uni_a=None,
266 1
        uni_z=None,
267
    ) -> None:
268
        """Validate that it must have a primary path or allow dynamic paths."""
269
        primary_path = (
270
            primary_path
271 1
            if primary_path is not None
272
            else self.primary_path
273
        )
274
        dynamic_backup_path = (
275
            dynamic_backup_path
276 1
            if dynamic_backup_path is not None
277 1
            else self.dynamic_backup_path
278 1
        )
279
        uni_a = uni_a if uni_a is not None else self.uni_a
280
        uni_z = uni_z if uni_z is not None else self.uni_z
281
        if (
282
            not primary_path
283
            and not dynamic_backup_path
284 1
            and uni_a and uni_z
285 1
            and uni_a.interface.switch != uni_z.interface.switch
286
        ):
287 1
            msg = "The EVC must have a primary path or allow dynamic paths."
288
            raise ValueError(msg)
289 1
290
    def __eq__(self, other):
291
        """Override the default implementation."""
292 1
        if not isinstance(other, EVC):
293 1
            return False
294 1
295 1
        attrs_to_compare = ["name", "uni_a", "uni_z", "owner", "bandwidth"]
296 1
        for attribute in attrs_to_compare:
297
            if getattr(other, attribute) != getattr(self, attribute):
298 1
                return False
299
        return True
300 1
301
    def is_intra_switch(self):
302 1
        """Check if the UNIs are in the same switch."""
303
        return self.uni_a.interface.switch == self.uni_z.interface.switch
304 1
305
    def shares_uni(self, other):
306
        """Check if two EVCs share an UNI."""
307
        if other.uni_a in (self.uni_a, self.uni_z) or other.uni_z in (
308 1
            self.uni_a,
309
            self.uni_z,
310
        ):
311 1
            return True
312
        return False
313 1
314
    def as_dict(self):
315
        """Return a dictionary representing an EVC object."""
316
        evc_dict = {
317
            "id": self.id,
318
            "name": self.name,
319
            "uni_a": self.uni_a.as_dict(),
320 1
            "uni_z": self.uni_z.as_dict(),
321
        }
322 1
323 1
        time_fmt = "%Y-%m-%dT%H:%M:%S"
324 1
325
        evc_dict["start_date"] = self.start_date
326 1
        if isinstance(self.start_date, datetime):
327 1
            evc_dict["start_date"] = self.start_date.strftime(time_fmt)
328 1
329
        evc_dict["end_date"] = self.end_date
330 1
        if isinstance(self.end_date, datetime):
331 1
            evc_dict["end_date"] = self.end_date.strftime(time_fmt)
332 1
333 1
        evc_dict["queue_id"] = self.queue_id
334 1
        evc_dict["bandwidth"] = self.bandwidth
335 1
        evc_dict["primary_links"] = self.primary_links.as_dict()
336 1
        evc_dict["backup_links"] = self.backup_links.as_dict()
337 1
        evc_dict["current_path"] = self.current_path.as_dict()
338 1
        evc_dict["failover_path"] = self.failover_path.as_dict()
339 1
        evc_dict["primary_path"] = self.primary_path.as_dict()
340
        evc_dict["backup_path"] = self.backup_path.as_dict()
341 1
        evc_dict["dynamic_backup_path"] = self.dynamic_backup_path
342 1
        evc_dict["metadata"] = self.metadata
343 1
344
        evc_dict["request_time"] = self.request_time
345 1
        if isinstance(self.request_time, datetime):
346 1
            evc_dict["request_time"] = self.request_time.strftime(time_fmt)
347
348 1
        time = self.creation_time.strftime(time_fmt)
349 1
        evc_dict["creation_time"] = time
350
351
        evc_dict["owner"] = self.owner
352
        evc_dict["circuit_scheduler"] = [
353 1
            sc.as_dict() for sc in self.circuit_scheduler
354 1
        ]
355 1
356 1
        evc_dict["active"] = self.is_active()
357 1
        evc_dict["enabled"] = self.is_enabled()
358 1
        evc_dict["archived"] = self.archived
359 1
        evc_dict["sb_priority"] = self.sb_priority
360 1
        evc_dict["service_level"] = self.service_level
361 1
        evc_dict["primary_constraints"] = self.primary_constraints
362
        evc_dict["secondary_constraints"] = self.secondary_constraints
363 1
        evc_dict["flow_removed_at"] = self.flow_removed_at
364
        evc_dict["updated_at"] = self.updated_at
365 1
366 1
        return evc_dict
367
368 1
    @property
369
    def id(self):  # pylint: disable=invalid-name
370 1
        """Return this EVC's ID."""
371
        return self._id
372 1
373
    def archive(self):
374
        """Archive this EVC on deletion."""
375
        self.archived = True
376 1
377
378
# pylint: disable=fixme, too-many-public-methods
379 1
class EVCDeploy(EVCBase):
380
    """Class to handle the deploy procedures."""
381
382 1
    def create(self):
383
        """Create a EVC."""
384
385
    def discover_new_paths(self):
386
        """Discover new paths to satisfy this circuit and deploy it."""
387 1
        return DynamicPathManager.get_best_paths(self,
388
                                                 **self.primary_constraints)
389
390
    def get_failover_path_candidates(self):
391
        """Get failover paths to satisfy this EVC."""
392
        # in the future we can return primary/backup paths as well
393
        # we just have to properly handle link_up and failover paths
394
        # if (
395
        #     self.is_using_primary_path() and
396 1
        #     self.backup_path.status is EntityStatus.UP
397
        # ):
398 1
        #     yield self.backup_path
399
        return DynamicPathManager.get_disjoint_paths(self, self.current_path)
400
401 1
    def change_path(self):
402
        """Change EVC path."""
403
404 1
    def reprovision(self):
405
        """Force the EVC (re-)provisioning."""
406 1
407
    def is_affected_by_link(self, link):
408 1
        """Return True if this EVC has the given link on its current path."""
409
        return link in self.current_path
410
411
    def link_affected_by_interface(self, interface):
412 1
        """Return True if this EVC has the given link on its current path."""
413
        return self.current_path.link_affected_by_interface(interface)
414 1
415
    def is_backup_path_affected_by_link(self, link):
416
        """Return True if the backup path of this EVC uses the given link."""
417 1
        return link in self.backup_path
418
419 1
    # pylint: disable=invalid-name
420
    def is_primary_path_affected_by_link(self, link):
421 1
        """Return True if the primary path of this EVC uses the given link."""
422
        return link in self.primary_path
423 1
424
    def is_failover_path_affected_by_link(self, link):
425 1
        """Return True if this EVC has the given link on its failover path."""
426
        return link in self.failover_path
427
428
    def is_eligible_for_failover_path(self):
429 1
        """Verify if this EVC is eligible for failover path (EP029)"""
430
        # In the future this function can be augmented to consider
431
        # primary/backup, primary/dynamic, and other path combinations
432
        return (
433
            self.dynamic_backup_path and
434 1
            not self.primary_path and not self.backup_path
435
        )
436 1
437
    def is_using_primary_path(self):
438 1
        """Verify if the current deployed path is self.primary_path."""
439
        return self.primary_path and (self.current_path == self.primary_path)
440 1
441
    def is_using_backup_path(self):
442 1
        """Verify if the current deployed path is self.backup_path."""
443
        return self.backup_path and (self.current_path == self.backup_path)
444 1
445
    def is_using_dynamic_path(self):
446
        """Verify if the current deployed path is a dynamic path."""
447
        if (
448
            self.current_path
449
            and not self.is_using_primary_path()
450
            and not self.is_using_backup_path()
451 1
            and self.current_path.status == EntityStatus.UP
452
        ):
453 1
            return True
454
        return False
455
456
    def deploy_to_backup_path(self):
457
        """Deploy the backup path into the datapaths of this circuit.
458
459
        If the backup_path attribute is valid and up, this method will try to
460
        deploy this backup_path.
461
462
        If everything fails and dynamic_backup_path is True, then tries to
463 1
        deploy a dynamic path.
464
        """
465
        # TODO: Remove flows from current (cookies)
466
        if self.is_using_backup_path():
467 1
            # TODO: Log to say that cannot move backup to backup
468 1
            return True
469 1
470
        success = False
471 1
        if self.backup_path.status is EntityStatus.UP:
472 1
            success = self.deploy_to_path(self.backup_path)
473
474 1
        if success:
475 1
            return True
476
477
        if self.dynamic_backup_path or self.is_intra_switch():
478
            return self.deploy_to_path()
479 1
480
        return False
481
482
    def deploy_to_primary_path(self):
483
        """Deploy the primary path into the datapaths of this circuit.
484
485
        If the primary_path attribute is valid and up, this method will try to
486 1
        deploy this primary_path.
487
        """
488
        # TODO: Remove flows from current (cookies)
489
        if self.is_using_primary_path():
490 1
            # TODO: Log to say that cannot move primary to primary
491 1
            return True
492 1
493
        if self.primary_path.status is EntityStatus.UP:
494 1
            return self.deploy_to_path(self.primary_path)
495
        return False
496
497
    def deploy(self):
498
        """Deploy EVC to best path.
499
500 1
        Best path can be the primary path, if available. If not, the backup
501 1
        path, and, if it is also not available, a dynamic path.
502 1
        """
503 1
        if self.archived:
504 1
            return False
505 1
        self.enable()
506
        success = self.deploy_to_primary_path()
507 1
        if not success:
508 1
            success = self.deploy_to_backup_path()
509
510 1
        if success:
511
            emit_event(self._controller, "deployed",
512 1
                       content=map_evc_event_content(self))
513 1
        return success
514
515
    @staticmethod
516
    def get_path_status(path):
517
        """Check for the current status of a path.
518 1
519 1
        If any link in this path is down, the path is considered down.
520
        """
521 1
        if not path:
522 1
            return EntityStatus.DISABLED
523 1
524 1
        for link in path:
525
            if link.status is not EntityStatus.UP:
526
                return link.status
527
        return EntityStatus.UP
528
529 1
    #    def discover_new_path(self):
530
    #        # TODO: discover a new path to satisfy this circuit and deploy
531 1
532 1
    def remove(self):
533 1
        """Remove EVC path and disable it."""
534 1
        self.remove_current_flows()
535 1
        self.remove_failover_flows()
536
        self.disable()
537
        self.sync()
538 1
        emit_event(self._controller, "undeployed",
539
                   content=map_evc_event_content(self))
540
541
    def remove_failover_flows(self, exclude_uni_switches=True,
542
                              force=True, sync=True) -> None:
543
        """Remove failover_flows.
544
545
        By default, it'll exclude UNI switches, if mef_eline has already
546 1
        called remove_current_flows before then this minimizes the number
547 1
        of FlowMods and IO.
548 1
        """
549 1
        if not self.failover_path:
550 1
            return
551 1
        switches, cookie, excluded = OrderedDict(), self.get_cookie(), set()
552 1
        links = set()
553 1
        if exclude_uni_switches:
554 1
            excluded.add(self.uni_a.interface.switch.id)
555 1
            excluded.add(self.uni_z.interface.switch.id)
556 1
        for link in self.failover_path:
557 1
            if link.endpoint_a.switch.id not in excluded:
558 1
                switches[link.endpoint_a.switch.id] = link.endpoint_a.switch
559 1
                links.add(link)
560 1
            if link.endpoint_b.switch.id not in excluded:
561 1
                switches[link.endpoint_b.switch.id] = link.endpoint_b.switch
562 1
                links.add(link)
563
        for switch in switches.values():
564
            try:
565
                self._send_flow_mods(
566
                    switch.id,
567
                    [
568
                        {
569
                            "cookie": cookie,
570
                            "cookie_mask": int(0xffffffffffffffff),
571
                        }
572
                    ],
573
                    "delete",
574
                    force=force,
575
                )
576
            except FlowModException as err:
577
                log.error(
578 1
                    f"Error removing flows from switch {switch.id} for"
579 1
                    f"EVC {self}: {err}"
580 1
                )
581 1
        for link in links:
582 1
            link.make_tag_available(link.get_metadata("s_vlan"))
583 1
            link.remove_metadata("s_vlan")
584 1
            notify_link_available_tags(self._controller, link)
585
        self.failover_path = Path([])
586 1
        if sync:
587
            self.sync()
588 1
589
    def remove_current_flows(self, current_path=None, force=True):
590 1
        """Remove all flows from current path."""
591 1
        switches = set()
592 1
593 1
        switches.add(self.uni_a.interface.switch)
594 1
        switches.add(self.uni_z.interface.switch)
595 1
        if not current_path:
596 1
            current_path = self.current_path
597
        for link in current_path:
598 1
            switches.add(link.endpoint_a.switch)
599
            switches.add(link.endpoint_b.switch)
600
601
        match = {
602
            "cookie": self.get_cookie(),
603 1
            "cookie_mask": int(0xffffffffffffffff)
604 1
        }
605 1
606 1
        for switch in switches:
607 1
            try:
608
                self._send_flow_mods(switch.id, [match], 'delete', force=force)
609
            except FlowModException as err:
610
                log.error(
611
                    f"Error removing flows from switch {switch.id} for"
612 1
                    f"EVC {self}: {err}"
613 1
                )
614 1
615 1
        current_path.make_vlans_available()
616 1
        for link in current_path:
617 1
            notify_link_available_tags(self._controller, link)
618
        self.current_path = Path([])
619 1
        self.deactivate()
620
        self.sync()
621 1
622 1
    def remove_path_flows(self, path=None, force=True):
623
        """Remove all flows from path."""
624 1
        if not path:
625 1
            return
626 1
627 1
        dpid_flows_match = {}
628 1
        for dpid, flows in self._prepare_nni_flows(path).items():
629
            dpid_flows_match.setdefault(dpid, [])
630
            for flow in flows:
631
                dpid_flows_match[dpid].append({
632
                    "cookie": flow["cookie"],
633 1
                    "match": flow["match"],
634 1
                    "cookie_mask": int(0xffffffffffffffff)
635 1
                })
636 1
        for dpid, flows in self._prepare_uni_flows(path, skip_in=True).items():
637
            dpid_flows_match.setdefault(dpid, [])
638
            for flow in flows:
639
                dpid_flows_match[dpid].append({
640
                    "cookie": flow["cookie"],
641
                    "match": flow["match"],
642 1
                    "cookie_mask": int(0xffffffffffffffff)
643 1
                })
644 1
645 1
        for dpid, flows in dpid_flows_match.items():
646 1
            try:
647
                self._send_flow_mods(dpid, flows, 'delete', force=force)
648
            except FlowModException as err:
649
                log.error(
650
                    "Error removing failover flows: "
651 1
                    f"dpid={dpid} evc={self} error={err}"
652 1
                )
653 1
654
        path.make_vlans_available()
655 1
        for link in path:
656 1
            notify_link_available_tags(self._controller, link)
657
658 1
    @staticmethod
659
    def links_zipped(path=None):
660 1
        """Return an iterator which yields pairs of links in order."""
661
        if not path:
662 1
            return []
663
        return zip(path[:-1], path[1:])
664 1
665 1
    def should_deploy(self, path=None):
666 1
        """Verify if the circuit should be deployed."""
667
        if not path:
668 1
            log.debug("Path is empty.")
669 1
            return False
670 1
671
        if not self.is_enabled():
672 1
            log.debug(f"{self} is disabled.")
673 1
            return False
674 1
675
        if not self.is_active():
676 1
            log.debug(f"{self} will be deployed.")
677
            return True
678 1
679
        return False
680
681
    def deploy_to_path(self, path=None):  # pylint: disable=too-many-branches
682
        """Install the flows for this circuit.
683
684
        Procedures to deploy:
685
686
        0. Remove current flows installed
687
        1. Decide if will deploy "path" or discover a new path
688
        2. Choose vlan
689
        3. Install NNI flows
690
        4. Install UNI flows
691
        5. Activate
692
        6. Update current_path
693 1
        7. Update links caches(primary, current, backup)
694 1
695 1
        """
696 1
        self.remove_current_flows()
697 1
        use_path = path
698 1
        if self.should_deploy(use_path):
699 1
            try:
700 1
                use_path.choose_vlans()
701 1
                for link in use_path:
702
                    notify_link_available_tags(self._controller, link)
703 1
            except KytosNoTagAvailableError:
704 1
                use_path = None
705
        else:
706 1
            for use_path in self.discover_new_paths():
707 1
                if use_path is None:
708 1
                    continue
709 1
                try:
710 1
                    use_path.choose_vlans()
711 1
                    for link in use_path:
712 1
                        notify_link_available_tags(self._controller, link)
713
                    break
714 1
                except KytosNoTagAvailableError:
715
                    pass
716 1
            else:
717 1
                use_path = None
718 1
719 1
        try:
720 1
            if use_path:
721 1
                self._install_nni_flows(use_path)
722 1
                self._install_uni_flows(use_path)
723
            elif self.is_intra_switch():
724 1
                use_path = Path()
725
                self._install_direct_uni_flows()
726
            else:
727 1
                log.warning(
728 1
                    f"{self} was not deployed. " "No available path was found."
729 1
                )
730
                return False
731
        except FlowModException as err:
732 1
            log.error(
733 1
                f"Error deploying EVC {self} when calling flow_manager: {err}"
734 1
            )
735 1
            self.remove_current_flows(use_path)
736 1
            return False
737 1
        self.activate()
738 1
        self.current_path = use_path
739
        self.sync()
740 1
        log.info(f"{self} was deployed.")
741
        return True
742
743
    def setup_failover_path(self):
744
        """Install flows for the failover path of this EVC.
745
746
        Procedures to deploy:
747
748
        0. Remove flows currently installed for failover_path (if any)
749
        1. Discover a disjoint path from current_path
750
        2. Choose vlans
751
        3. Install NNI flows
752
        4. Install UNI egress flows
753 1
        5. Update failover_path
754 1
        """
755
        # Intra-switch EVCs have no failover_path
756
        if self.is_intra_switch():
757 1
            return False
758 1
759
        # For not only setup failover path for totally dynamic EVCs
760 1
        if not self.is_eligible_for_failover_path():
761 1
            return False
762 1
763 1
        reason = ""
764 1
        self.remove_path_flows(self.failover_path)
765 1
        for use_path in self.get_failover_path_candidates():
766 1
            if not use_path:
767 1
                continue
768 1
            try:
769 1
                use_path.choose_vlans()
770 1
                for link in use_path:
771 1
                    notify_link_available_tags(self._controller, link)
772
                break
773 1
            except KytosNoTagAvailableError:
774 1
                pass
775
        else:
776 1
            use_path = Path([])
777 1
            reason = "No available path was found"
778 1
779 1
        try:
780 1
            if use_path:
781 1
                self._install_nni_flows(use_path)
782 1
                self._install_uni_flows(use_path, skip_in=True)
783
        except FlowModException as err:
784
            reason = "Error deploying failover path"
785 1
            log.error(
786 1
                f"{reason} for {self}. FlowManager error: {err}"
787
            )
788 1
            self.remove_path_flows(use_path)
789 1
            use_path = Path([])
790
791 1
        self.failover_path = use_path
792 1
        self.sync()
793
794
        if not use_path:
795 1
            log.warning(
796 1
                f"Failover path for {self} was not deployed: {reason}"
797 1
            )
798
            return False
799 1
        log.info(f"Failover path for {self} was deployed.")
800
        return True
801
802
    def get_failover_flows(self):
803
        """Return the flows needed to make the failover path active, i.e. the
804
        flows for ingress forwarding.
805
806
        Return:
807 1
            dict: A dict of flows indexed by the switch_id will be returned, or
808 1
                an empty dict if no failover_path is available.
809 1
        """
810
        if not self.failover_path:
811 1
            return {}
812
        return self._prepare_uni_flows(self.failover_path, skip_out=True)
813 1
814 1
    # pylint: disable=too-many-branches
815
    def _prepare_direct_uni_flows(self):
816 1
        """Prepare flows connecting two UNIs for intra-switch EVC."""
817 1
        vlan_a = self._get_value_from_uni_tag(self.uni_a)
818
        vlan_z = self._get_value_from_uni_tag(self.uni_z)
819
820
        is_EVPL = (vlan_a is not None)
821 1
        flow_mod_az = self._prepare_flow_mod(
822 1
            self.uni_a.interface, self.uni_z.interface,
823
            self.queue_id, is_EVPL
824
        )
825
        is_EVPL = (vlan_z is not None)
826
        flow_mod_za = self._prepare_flow_mod(
827 1
            self.uni_z.interface, self.uni_a.interface,
828 1
            self.queue_id, is_EVPL
829 1
        )
830 1
831
        if vlan_a is not None:
832
            flow_mod_az["match"]["dl_vlan"] = vlan_a
833 1
834
        if vlan_z is not None:
835
            flow_mod_za["match"]["dl_vlan"] = vlan_z
836 1
837 1
        if vlan_a not in {None, "4096/4096", 0}:
838 1
            flow_mod_za["actions"].insert(
839 1
                    0, {"action_type": "set_vlan", "vlan_id": vlan_a}
840
                )
841
            if vlan_z not in {None, "4096/4096", 0}:
842 1
                flow_mod_az["actions"].insert(
843 1
                    0, {"action_type": "set_vlan", "vlan_id": vlan_z}
844 1
                )
845 1
            if not vlan_z:
846
                flow_mod_za["actions"].insert(
847
                    0, {"action_type": "push_vlan", "tag_type": "c"}
848 1
                )
849
            if vlan_z == 0:
850
                flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
851
852 1
        elif vlan_a == "4096/4096":
853
            if vlan_z not in {None, "4096/4096", 0}:
854
                flow_mod_az["actions"].insert(
855
                    0, {"action_type": "set_vlan", "vlan_id": vlan_z}
856
                )
857
            if vlan_z == 0:
858 1
                flow_mod_az["actions"].insert(0, {"action_type": "pop_vlan"})
859 1
860
        elif vlan_a == 0:
861 1
            if vlan_z not in {None, "4096/4096", 0}:
862
                flow_mod_az["actions"].insert(
863 1
                    0, {"action_type": "set_vlan", "vlan_id": vlan_z}
864 1
                )
865 1
                flow_mod_az["actions"].insert(
866 1
                    0, {"action_type": "push_vlan", "tag_type": "c"}
867
                )
868 1
            if vlan_z:
869
                flow_mod_za["actions"].insert(0, {"action_type": "pop_vlan"})
870 1
871
        elif vlan_a is None:
872
            if vlan_z not in {None, "4096/4096", 0}:
873
                flow_mod_az["actions"].insert(
874
                    0, {"action_type": "set_vlan", "vlan_id": vlan_z}
875
                )
876
                flow_mod_az["actions"].insert(
877
                    0, {"action_type": "push_vlan", "tag_type": "c"}
878
                )
879
880
        return (
881 1
            self.uni_a.interface.switch.id, [flow_mod_az, flow_mod_za]
882
        )
883
884
    def _install_direct_uni_flows(self):
885
        """Install flows connecting two UNIs.
886
887
        This case happens when the circuit is between UNIs in the
888
        same switch.
889
        """
890 1
        (dpid, flows) = self._prepare_direct_uni_flows()
891 1
        self._send_flow_mods(dpid, flows)
892
893 1
    def _prepare_nni_flows(self, path=None):
894
        """Prepare NNI flows."""
895 1
        nni_flows = OrderedDict()
896 1
        for incoming, outcoming in self.links_zipped(path):
897
            in_vlan = incoming.get_metadata("s_vlan").value
898 1
            out_vlan = outcoming.get_metadata("s_vlan").value
899
900 1
            flows = []
901 1
            # Flow for one direction
902 1
            flows.append(
903 1
                self._prepare_nni_flow(
904
                    incoming.endpoint_b,
905
                    outcoming.endpoint_a,
906 1
                    in_vlan,
907 1
                    out_vlan,
908
                    queue_id=self.queue_id,
909 1
                )
910 1
            )
911
912
            # Flow for the other direction
913 1
            flows.append(
914
                self._prepare_nni_flow(
915
                    outcoming.endpoint_a,
916 1
                    incoming.endpoint_b,
917 1
                    out_vlan,
918
                    in_vlan,
919
                    queue_id=self.queue_id,
920
                )
921
            )
922
            nni_flows[incoming.endpoint_b.switch.id] = flows
923
        return nni_flows
924
925 1
    def _install_nni_flows(self, path=None):
926
        """Install NNI flows."""
927
        for dpid, flows in self._prepare_nni_flows(path).items():
928 1
            self._send_flow_mods(dpid, flows)
929 1
930
    @staticmethod
931
    def _get_value_from_uni_tag(uni):
932
        """Returns the value from tag. In case of any and untagged
933
        it should return 4096/4096 and 0 respectively"""
934
        special = {"any": "4096/4096", "untagged": 0}
935 1
936
        if uni.user_tag:
937 1
            value = uni.user_tag.value
938
            if isinstance(value, str):
939
                return special.get(value, value)
940 1
            return value
941
        return None
942
943 1
    def _prepare_uni_flows(self, path=None, skip_in=False, skip_out=False):
944 1
        """Prepare flows to install UNIs."""
945
        uni_flows = {}
946
        if not path:
947
            log.info("install uni flows without path.")
948
            return uni_flows
949
950
        # Determine VLANs
951
        in_vlan_a = self._get_value_from_uni_tag(self.uni_a)
952 1
        out_vlan_a = path[0].get_metadata("s_vlan").value
953
954
        in_vlan_z = self._get_value_from_uni_tag(self.uni_z)
955 1
        out_vlan_z = path[-1].get_metadata("s_vlan").value
956 1
957
        # Flows for the first UNI
958
        flows_a = []
959
960
        # Flow for one direction, pushing the service tag
961
        if not skip_in:
962 1
            push_flow = self._prepare_push_flow(
963
                self.uni_a.interface,
964 1
                path[0].endpoint_a,
965
                in_vlan_a,
966 1
                out_vlan_a,
967
                in_vlan_z,
968 1
                queue_id=self.queue_id,
969
            )
970 1
            flows_a.append(push_flow)
971
972 1
        # Flow for the other direction, popping the service tag
973 1
        if not skip_out:
974
            pop_flow = self._prepare_pop_flow(
975 1
                path[0].endpoint_a,
976 1
                self.uni_a.interface,
977
                out_vlan_a,
978
                queue_id=self.queue_id,
979
            )
980
            flows_a.append(pop_flow)
981
982
        uni_flows[self.uni_a.interface.switch.id] = flows_a
983
984
        # Flows for the second UNI
985
        flows_z = []
986
987 1
        # Flow for one direction, pushing the service tag
988
        if not skip_in:
989 1
            push_flow = self._prepare_push_flow(
990 1
                self.uni_z.interface,
991 1
                path[-1].endpoint_b,
992 1
                in_vlan_z,
993
                out_vlan_z,
994 1
                in_vlan_a,
995
                queue_id=self.queue_id,
996 1
            )
997
            flows_z.append(push_flow)
998 1
999 1
        # Flow for the other direction, popping the service tag
1000
        if not skip_out:
1001 1
            pop_flow = self._prepare_pop_flow(
1002 1
                path[-1].endpoint_b,
1003
                self.uni_z.interface,
1004 1
                out_vlan_z,
1005
                queue_id=self.queue_id,
1006
            )
1007 1
            flows_z.append(pop_flow)
1008
1009
        uni_flows[self.uni_z.interface.switch.id] = flows_z
1010 1
1011
        return uni_flows
1012
1013
    def _install_uni_flows(self, path=None, skip_in=False, skip_out=False):
1014
        """Install UNI flows."""
1015 1
        uni_flows = self._prepare_uni_flows(path, skip_in, skip_out)
1016
1017
        for (dpid, flows) in uni_flows.items():
1018
            self._send_flow_mods(dpid, flows)
1019
1020 1
    @staticmethod
1021
    def _send_flow_mods(dpid, flow_mods, command='flows', force=False):
1022
        """Send a flow_mod list to a specific switch.
1023 1
1024 1
        Args:
1025
            dpid(str): The target of flows (i.e. Switch.id).
1026 1
            flow_mods(dict): Python dictionary with flow_mods.
1027 1
            command(str): By default is 'flows'. To remove a flow is 'remove'.
1028
            force(bool): True to send via consistency check in case of errors
1029 1
1030
        """
1031 1
1032 1
        endpoint = f"{settings.MANAGER_URL}/{command}/{dpid}"
1033
1034
        data = {"flows": flow_mods, "force": force}
1035 1
        response = requests.post(endpoint, json=data)
1036
        if response.status_code >= 400:
1037 1
            raise FlowModException(str(response.text))
1038 1
1039
    def get_cookie(self):
1040 1
        """Return the cookie integer from evc id."""
1041
        return int(self.id, 16) + (settings.COOKIE_PREFIX << 56)
1042
1043 1
    @staticmethod
1044
    def get_id_from_cookie(cookie):
1045
        """Return the evc id given a cookie value."""
1046
        evc_id = cookie - (settings.COOKIE_PREFIX << 56)
1047
        return f"{evc_id:x}".zfill(14)
1048
1049
    def _prepare_flow_mod(self, in_interface, out_interface,
1050
                          queue_id=None, is_EVPL=True):
1051
        """Prepare a common flow mod."""
1052
        default_actions = [
1053
            {"action_type": "output", "port": out_interface.port_number}
1054
        ]
1055
        if queue_id is not None:
1056
            default_actions.append(
1057
                {"action_type": "set_queue", "queue_id": queue_id}
1058 1
            )
1059 1
1060 1
        flow_mod = {
1061
            "match": {"in_port": in_interface.port_number},
1062
            "cookie": self.get_cookie(),
1063
            "actions": default_actions,
1064
        }
1065 1
        if self.sb_priority:
1066 1
            flow_mod["priority"] = self.sb_priority
1067
        else:
1068 1
            if is_EVPL:
1069 1
                flow_mod["priority"] = settings.EVPL_SB_PRIORITY
1070
            else:
1071 1
                flow_mod["priority"] = settings.EPL_SB_PRIORITY
1072
        return flow_mod
1073 1
1074 1
    def _prepare_nni_flow(self, *args, queue_id=None):
1075
        """Create NNI flows."""
1076 1
        in_interface, out_interface, in_vlan, out_vlan = args
1077 1
        flow_mod = self._prepare_flow_mod(
1078 1
            in_interface, out_interface, queue_id
1079
        )
1080
        flow_mod["match"]["dl_vlan"] = in_vlan
1081 1
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1082 1
        flow_mod["actions"].insert(0, new_action)
1083 1
1084
        return flow_mod
1085
1086 1
    # pylint: disable=too-many-arguments
1087 1
    def _prepare_push_flow(self, *args, queue_id=None):
1088 1
        """Prepare push flow.
1089
1090 1
        Arguments:
1091
            in_interface(str): Interface input.
1092
            out_interface(str): Interface output.
1093
            in_vlan(str): Vlan input.
1094
            out_vlan(str): Vlan output.
1095 1
            new_c_vlan(str): New client vlan.
1096
1097
        Return:
1098 1
            dict: An python dictionary representing a FlowMod
1099 1
1100 1
        """
1101 1
        # assign all arguments
1102
        in_interface, out_interface, in_vlan, out_vlan, new_c_vlan = args
1103 1
        is_EVPL = (in_vlan is not None)
1104 1
        flow_mod = self._prepare_flow_mod(
1105
            in_interface, out_interface, queue_id, is_EVPL
1106 1
        )
1107 1
        # the service tag must be always pushed
1108
        new_action = {"action_type": "set_vlan", "vlan_id": out_vlan}
1109
        flow_mod["actions"].insert(0, new_action)
1110
1111
        new_action = {"action_type": "push_vlan", "tag_type": "s"}
1112
        flow_mod["actions"].insert(0, new_action)
1113
1114
        if in_vlan is not None:
1115 1
            # if in_vlan is set, it must be included in the match
1116 1
            flow_mod["match"]["dl_vlan"] = in_vlan
1117
1118
        if new_c_vlan not in {"4096/4096", 0, None}:
1119
            new_action = {"action_type": "set_vlan", "vlan_id": new_c_vlan}
1120 1
            flow_mod["actions"].insert(0, new_action)
1121 1
1122 1
        if in_vlan not in {"4096/4096", 0, None}:
1123 1
            if new_c_vlan == 0:
1124 1
                new_action = {"action_type": "pop_vlan"}
1125
                flow_mod["actions"].insert(0, new_action)
1126 1
1127 1
        elif in_vlan == "4096/4096":
1128
            if new_c_vlan == 0:
1129 1
                new_action = {"action_type": "pop_vlan"}
1130 1
                flow_mod["actions"].insert(0, new_action)
1131 1
1132 1
        elif not in_vlan:
1133
            if new_c_vlan not in {"4096/4096", 0, None}:
1134
                new_action = {"action_type": "push_vlan", "tag_type": "c"}
1135
                flow_mod["actions"].insert(0, new_action)
1136
1137
        return flow_mod
1138
1139
    def _prepare_pop_flow(
1140 1
        self, in_interface, out_interface, out_vlan, queue_id=None
1141 1
    ):
1142
        # pylint: disable=too-many-arguments
1143
        """Prepare pop flow."""
1144
        flow_mod = self._prepare_flow_mod(
1145 1
            in_interface, out_interface, queue_id
1146 1
        )
1147 1
        flow_mod["match"]["dl_vlan"] = out_vlan
1148
        new_action = {"action_type": "pop_vlan"}
1149
        flow_mod["actions"].insert(0, new_action)
1150
        return flow_mod
1151 1
1152 1
    @staticmethod
1153 1
    def run_sdntrace(uni):
1154 1
        """Run SDN trace on control plane starting from EVC UNIs."""
1155
        endpoint = f"{settings.SDN_TRACE_CP_URL}/trace"
1156 1
        data_uni = {
1157 1
            "trace": {
1158
                "switch": {
1159 1
                    "dpid": uni.interface.switch.dpid,
1160
                    "in_port": uni.interface.port_number,
1161 1
                }
1162
            }
1163
        }
1164
        if uni.user_tag:
1165 1
            data_uni["trace"]["eth"] = {
1166 1
                "dl_type": 0x8100,
1167 1
                "dl_vlan": uni.user_tag.value,
1168
            }
1169
        response = requests.put(endpoint, json=data_uni)
1170
        if response.status_code >= 400:
1171 1
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1172 1
            return []
1173
        return response.json().get('result', [])
1174 1
1175
    @staticmethod
1176
    def run_bulk_sdntraces(uni_list):
1177 1
        """Run SDN traces on control plane starting from EVC UNIs."""
1178 1
        endpoint = f"{settings.SDN_TRACE_CP_URL}/traces"
1179 1
        data = []
1180 1
        for uni in uni_list:
1181
            data_uni = {
1182
                "trace": {
1183
                            "switch": {
1184
                                "dpid": uni.interface.switch.dpid,
1185 1
                                "in_port": uni.interface.port_number,
1186 1
                            }
1187 1
                        }
1188
                }
1189
            if uni.user_tag:
1190
                data_uni["trace"]["eth"] = {
1191
                                            "dl_type": 0x8100,
1192 1
                                            "dl_vlan": uni.user_tag.value,
1193 1
                                            }
1194
            data.append(data_uni)
1195 1
        try:
1196
            response = requests.put(endpoint, json=data, timeout=30)
1197 1
        except ConnectTimeout as exception:
1198 1
            log.error(f"Request has timed out: {exception}")
1199
1200 1
        if response.status_code >= 400:
1201
            log.error(f"Failed to run sdntrace-cp: {response.text}")
1202 1
            return {"result": []}
1203 1
        return response.json()
1204 1
1205 1
    @staticmethod
1206
    def check_trace(circuit, trace_a, trace_z):
1207 1
        """Auxiliar function to check an individual trace"""
1208 1
        if not trace_a or not trace_z:
1209
            return False
1210 1
        if (
1211
            len(trace_a) != len(circuit.current_path) + 1
1212 1
            or not compare_uni_out_trace(circuit.uni_z, trace_a[-1])
1213 1
        ):
1214 1
            log.warning(f"Invalid trace from uni_a: {trace_a}")
1215 1
            return False
1216 1
        if (
1217
            len(trace_z) != len(circuit.current_path) + 1
1218
            or not compare_uni_out_trace(circuit.uni_a, trace_z[-1])
1219
        ):
1220
            log.warning(f"Invalid trace from uni_z: {trace_z}")
1221
            return False
1222
1223
        for link, trace1, trace2 in zip(circuit.current_path,
1224
                                        trace_a[1:],
1225 1
                                        trace_z[:0:-1]):
1226
            metadata_vlan = None
1227
            if link.metadata:
1228 1
                metadata_vlan = glom(link.metadata, 's_vlan.value')
1229
            if compare_endpoint_trace(
1230
                                        link.endpoint_a,
1231 1
                                        metadata_vlan,
1232
                                        trace2
1233
                                    ) is False:
1234
                log.warning(f"Invalid trace from uni_a: {trace_a}")
1235 1
                return False
1236
            if compare_endpoint_trace(
1237 1
                                        link.endpoint_b,
1238
                                        metadata_vlan,
1239 1
                                        trace1
1240
                                    ) is False:
1241 1
                log.warning(f"Invalid trace from uni_z: {trace_z}")
1242
                return False
1243 1
1244
        return True
1245 1
1246
    @staticmethod
1247
    def check_list_traces(list_circuits):
1248
        """Check if current_path is deployed comparing with SDN traces."""
1249
        if not list_circuits:
1250
            return {}
1251
        uni_list = []
1252 1
        for circuit in list_circuits:
1253
            uni_list.append(circuit.uni_a)
1254 1
            uni_list.append(circuit.uni_z)
1255
1256 1
        traces = EVCDeploy.run_bulk_sdntraces(uni_list)
1257 1
        traces = traces["result"]
1258 1
1259
        circuits_checked = {}
1260 1
1261 1
        try:
1262
            for i, circuit in enumerate(list_circuits):
1263 1
                trace_a = traces[2*i]
1264
                trace_z = traces[2*i+1]
1265 1
                circuits_checked[circuit.id] = EVCDeploy.check_trace(
1266
                        circuit, trace_a, trace_z
1267
                    )
1268
        except IndexError as err:
1269
            log.error(
1270
                f"Bulk sdntraces returned fewer items than expected."
1271
                f"Error = {err}"
1272 1
            )
1273
1274
        return circuits_checked
1275 1
1276 1
1277
class LinkProtection(EVCDeploy):
1278 1
    """Class to handle link protection."""
1279 1
1280 1
    def is_affected_by_link(self, link=None):
1281
        """Verify if the current path is affected by link down event."""
1282 1
        return self.current_path.is_affected_by_link(link)
1283 1
1284
    def is_using_primary_path(self):
1285
        """Verify if the current deployed path is self.primary_path."""
1286
        return self.current_path == self.primary_path
1287 1
1288 1
    def is_using_backup_path(self):
1289
        """Verify if the current deployed path is self.backup_path."""
1290
        return self.current_path == self.backup_path
1291
1292 1
    def is_using_dynamic_path(self):
1293 1
        """Verify if the current deployed path is dynamic."""
1294
        if (
1295
            self.current_path
1296
            and not self.is_using_primary_path()
1297 1
            and not self.is_using_backup_path()
1298 1
            and self.current_path.status is EntityStatus.UP
1299
        ):
1300 1
            return True
1301 1
        return False
1302
1303 1
    def deploy_to(self, path_name=None, path=None):
1304
        """Create a deploy to path."""
1305 1
        if self.current_path == path:
1306
            log.debug(f"{path_name} is equal to current_path.")
1307 1
            return True
1308
1309
        if path.status is EntityStatus.UP:
1310
            return self.deploy_to_path(path)
1311
1312
        return False
1313
1314 1
    def handle_link_up(self, link):
1315 1
        """Handle circuit when link down.
1316 1
1317 1
        Args:
1318 1
            link(Link): Link affected by link.down event.
1319
1320 1
        """
1321 1
        if self.is_intra_switch():
1322
            return True
1323 1
1324 1
        if self.is_using_primary_path():
1325
            return True
1326 1
1327 1
        success = False
1328 1
        if self.primary_path.is_affected_by_link(link):
1329 1
            success = self.deploy_to_primary_path()
1330
1331 1
        if success:
1332
            return True
1333
1334 1
        # We tried to deploy(primary_path) without success.
1335
        # And in this case is up by some how. Nothing to do.
1336
        if self.is_using_backup_path() or self.is_using_dynamic_path():
1337
            return True
1338
1339
        # In this case, probably the circuit is not being used and
1340
        # we can move to backup
1341
        if self.backup_path.is_affected_by_link(link):
1342
            success = self.deploy_to_backup_path()
1343
1344
        # In this case, the circuit is not being used and we should
1345
        # try a dynamic path
1346
        if not success and self.dynamic_backup_path:
1347
            success = self.deploy_to_path()
1348
1349
        if success:
1350
            emit_event(self._controller, "redeployed_link_up",
1351
                       content=map_evc_event_content(self))
1352
            return True
1353
1354
        return True
1355
1356
    def handle_link_down(self):
1357
        """Handle circuit when link down.
1358
1359
        Returns:
1360
            bool: True if the re-deploy was successly otherwise False.
1361
1362
        """
1363
        success = False
1364
        if self.is_using_primary_path():
1365
            success = self.deploy_to_backup_path()
1366
        elif self.is_using_backup_path():
1367
            success = self.deploy_to_primary_path()
1368
1369
        if not success and self.dynamic_backup_path:
1370
            success = self.deploy_to_path()
1371
1372
        if success:
1373
            log.debug(f"{self} deployed after link down.")
1374
        else:
1375
            self.deactivate()
1376
            self.current_path = Path([])
1377
            self.sync()
1378
            log.debug(f"Failed to re-deploy {self} after link down.")
1379
1380
        return success
1381
1382
1383
class EVC(LinkProtection):
1384
    """Class that represents a E-Line Virtual Connection."""
1385