Passed
Pull Request — master (#246)
by Italo Valcy
03:24
created

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

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

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