Passed
Pull Request — master (#119)
by Antonio
03:37
created

build.models.LinkProtection.deploy_to()   A

Complexity

Conditions 3

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 7
nop 3
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 3
rs 10
c 0
b 0
f 0
1
"""Classes used in the main application."""
2 2
from datetime import datetime
3 2
from uuid import uuid4
4
5 2
import requests
6
7 2
from kytos.core import log
8 2
from kytos.core.common import EntityStatus, GenericEntity
9 2
from kytos.core.helpers import get_time, now
10 2
from kytos.core.interface import UNI
11 2
from kytos.core.link import Link
12 2
from napps.kytos.mef_eline import settings
13 2
from napps.kytos.mef_eline.storehouse import StoreHouse
14
15
16 2
class Path(list, GenericEntity):
17
    """Class to represent a Path."""
18
19 2
    def __eq__(self, other=None):
20
        """Compare paths."""
21 2
        if not other or not isinstance(other, Path):
22 2
            return False
23 2
        return super().__eq__(other)
24
25 2
    def is_affected_by_link(self, link=None):
26
        """Verify if the current path is affected by link."""
27 2
        if not link:
28
            return False
29 2
        return link in self
30
31 2
    def link_affected_by_interface(self, interface=None):
32
        """Return the link using this interface, if any, or None otherwise."""
33
        if not interface:
34
            return None
35
        for link in self:
36
            if interface in (link.endpoint_a, link.endpoint_b):
37
                return link
38
        return None
39
40 2
    @property
41
    def status(self):
42
        """Check for the  status of a path.
43
44
        If any link in this path is down, the path is considered down.
45
        """
46 2
        if not self:
47 2
            return EntityStatus.DISABLED
48
49 2
        endpoint = '%s/%s' % (settings.TOPOLOGY_URL, 'links')
50 2
        api_reply = requests.get(endpoint)
51 2
        if api_reply.status_code != getattr(requests.codes, 'ok'):
52
            log.error('Failed to get links at %s. Returned %s',
53
                      endpoint, api_reply.status_code)
54
            return None
55 2
        links = api_reply.json()['links']
56 2
        for path_link in self:
57 2
            link = links[path_link.id]
58 2
            if link['active'] is False:
59 2
                return EntityStatus.DOWN
60 2
        return EntityStatus.UP
61
62 2
    def as_dict(self):
63
        """Return list comprehension of links as_dict."""
64 2
        return [link.as_dict() for link in self if link]
65
66
67 2
class DynamicPathManager:
68
    """Class to handle and create paths."""
69
70 2
    controller = None
71
72 2
    @classmethod
73 2
    def set_controller(cls, controller=None):
74
        """Set the controller to discovery news paths."""
75 2
        cls.controller = controller
76
77 2
    @staticmethod
78
    def get_paths(circuit):
79
        """Get a valid path for the circuit from the Pathfinder."""
80
        endpoint = settings.PATHFINDER_URL
81
        request_data = {"source": circuit.uni_a.interface.id,
82
                        "destination": circuit.uni_z.interface.id}
83
        api_reply = requests.post(endpoint, json=request_data)
84
85
        if api_reply.status_code != getattr(requests.codes, 'ok'):
86
            log.error("Failed to get paths at %s. Returned %s",
87
                      endpoint, api_reply.status_code)
88
            return None
89
        reply_data = api_reply.json()
90
        return reply_data.get('paths')
91
92 2
    @staticmethod
93
    def _clear_path(path):
94
        """Remove switches from a path, returning only interfaeces."""
95
        return [endpoint for endpoint in path if len(endpoint) > 23]
96
97 2
    @classmethod
98
    def get_best_path(cls, circuit):
99
        """Return the best path available for a circuit, if exists."""
100
        paths = cls.get_paths(circuit)
101
        if paths:
102
            return cls.create_path(cls.get_paths(circuit)[0]['hops'])
103
        return None
104
105 2
    @classmethod
106
    def create_path(cls, path):
107
        """Return the path containing only the interfaces."""
108
        new_path = Path()
109
        clean_path = cls._clear_path(path)
110
111
        if len(clean_path) % 2:
112
            return None
113
114
        for link in zip(clean_path[1:-1:2], clean_path[2::2]):
115
            interface_a = cls.controller.get_interface_by_id(link[0])
116
            interface_b = cls.controller.get_interface_by_id(link[1])
117
            if interface_a is None or interface_b is None:
118
                return None
119
            new_path.append(Link(interface_a, interface_b))
120
121
        return new_path
122
123
124 2
class EVCBase(GenericEntity):
125
    """Class to represent a circuit."""
126
127 2
    unique_attributes = ['name', 'uni_a', 'uni_z']
128
129 2
    def __init__(self, controller, **kwargs):
130
        """Create an EVC instance with the provided parameters.
131
132
        Args:
133
            id(str): EVC identifier. Whether it's None an ID will be genereted.
134
            name: represents an EVC name.(Required)
135
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
136
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
137
            start_date(datetime|str): Date when the EVC was registred.
138
                                      Default is now().
139
            end_date(datetime|str): Final date that the EVC will be fineshed.
140
                                    Default is None.
141
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
142
            primary_links(list): Primary links used by evc. Default is []
143
            backup_links(list): Backups links used by evc. Default is []
144
            current_path(list): Circuit being used at the moment if this is an
145
                                active circuit. Default is [].
146
            primary_path(list): primary circuit offered to user IF one or more
147
                                links were provided. Default is [].
148
            backup_path(list): backup circuit offered to the user IF one or
149
                               more links were provided. Default is [].
150
            dynamic_backup_path(bool): Enable computer backup path dynamically.
151
                                       Dafault is False.
152
            creation_time(datetime|str): datetime when the circuit should be
153
                                         activated. default is now().
154
            enabled(Boolean): attribute to indicate the operational state.
155
                              default is False.
156
            active(Boolean): attribute to Administrative state;
157
                             default is False.
158
            owner(str): The EVC owner. Default is None.
159
            priority(int): Service level provided in the request. Default is 0.
160
161
        Raises:
162
            ValueError: raised when object attributes are invalid.
163
164
        """
165 2
        self._validate(**kwargs)
166 2
        super().__init__()
167
168
        # required attributes
169 2
        self._id = kwargs.get('id', uuid4().hex)
170 2
        self.uni_a = kwargs.get('uni_a')
171 2
        self.uni_z = kwargs.get('uni_z')
172 2
        self.name = kwargs.get('name')
173
174
        # optional attributes
175 2
        self.start_date = get_time(kwargs.get('start_date')) or now()
176 2
        self.end_date = get_time(kwargs.get('end_date')) or None
177
178 2
        self.bandwidth = kwargs.get('bandwidth', 0)
179 2
        self.primary_links = Path(kwargs.get('primary_links', []))
180 2
        self.backup_links = Path(kwargs.get('backup_links', []))
181 2
        self.current_path = Path(kwargs.get('current_path', []))
182 2
        self.primary_path = Path(kwargs.get('primary_path', []))
183 2
        self.backup_path = Path(kwargs.get('backup_path', []))
184 2
        self.dynamic_backup_path = kwargs.get('dynamic_backup_path', False)
185 2
        self.creation_time = get_time(kwargs.get('creation_time')) or now()
186 2
        self.owner = kwargs.get('owner', None)
187 2
        self.priority = kwargs.get('priority', 0)
188 2
        self.circuit_scheduler = kwargs.get('circuit_scheduler', [])
189
190 2
        self.current_links_cache = set()
191 2
        self.primary_links_cache = set()
192 2
        self.backup_links_cache = set()
193
194 2
        self._storehouse = StoreHouse(controller)
195
196 2
        if kwargs.get('active', False):
197 2
            self.activate()
198
        else:
199 2
            self.deactivate()
200
201 2
        if kwargs.get('enabled', False):
202 2
            self.enable()
203
        else:
204 2
            self.disable()
205
206
        # datetime of user request for a EVC (or datetime when object was
207
        # created)
208 2
        self.request_time = kwargs.get('request_time', now())
209
        # dict with the user original request (input)
210 2
        self._requested = kwargs
211
212 2
    def sync(self):
213
        """Sync this EVC in the storehouse."""
214 2
        self._storehouse.save_evc(self)
215
216 2
    def update(self, **kwargs):
217
        """Update evc attributes.
218
219
        This method will raises an error trying to change the following
220
        attributes: [name, uni_a and uni_z]
221
222
        Raises:
223
            ValueError: message with error detail.
224
225
        """
226 2
        for attribute, value in kwargs.items():
227 2
            if attribute in self.unique_attributes:
228 2
                raise ValueError(f'{attribute} can\'t be be updated.')
229
            if hasattr(self, attribute):
230
                setattr(self, attribute, value)
231
            else:
232
                raise ValueError(f'The attribute "{attribute}" is invalid.')
233
        self.sync()
234
235 2
    def __repr__(self):
236
        """Repr method."""
237 2
        return f"EVC({self._id}, {self.name})"
238
239 2
    def _validate(self, **kwargs):
240
        """Do Basic validations.
241
242
        Verify required attributes: name, uni_a, uni_z
243
        Verify if the attributes uni_a and uni_z are valid.
244
245
        Raises:
246
            ValueError: message with error detail.
247
248
        """
249 2
        for attribute in self.unique_attributes:
250
251 2
            if attribute not in kwargs:
252 2
                raise ValueError(f'{attribute} is required.')
253
254 2
            if 'uni' in attribute:
255 2
                uni = kwargs.get(attribute)
256 2
                if not isinstance(uni, UNI):
257
                    raise ValueError(f'{attribute} is an invalid UNI.')
258
259 2
                elif not uni.is_valid():
260 2
                    tag = uni.user_tag.value
261 2
                    message = f'VLAN tag {tag} is not available in {attribute}'
262 2
                    raise ValueError(message)
263
264 2
    def __eq__(self, other):
265
        """Override the default implementation."""
266 2
        if not isinstance(other, EVC):
267
            return False
268
269 2
        attrs_to_compare = ['name', 'uni_a', 'uni_z', 'owner', 'bandwidth']
270 2
        for attribute in attrs_to_compare:
271 2
            if getattr(other, attribute) != getattr(self, attribute):
272 2
                return False
273 2
        return True
274
275 2
    def as_dict(self):
276
        """Return a dictionary representing an EVC object."""
277 2
        evc_dict = {"id": self.id, "name": self.name,
278
                    "uni_a": self.uni_a.as_dict(),
279
                    "uni_z": self.uni_z.as_dict()}
280
281 2
        time_fmt = "%Y-%m-%dT%H:%M:%S"
282
283 2
        evc_dict["start_date"] = self.start_date
284 2
        if isinstance(self.start_date, datetime):
285 2
            evc_dict["start_date"] = self.start_date.strftime(time_fmt)
286
287 2
        evc_dict["end_date"] = self.end_date
288 2
        if isinstance(self.end_date, datetime):
289 2
            evc_dict["end_date"] = self.end_date.strftime(time_fmt)
290
291 2
        evc_dict['bandwidth'] = self.bandwidth
292 2
        evc_dict['primary_links'] = self.primary_links.as_dict()
293 2
        evc_dict['backup_links'] = self.backup_links.as_dict()
294 2
        evc_dict['current_path'] = self.current_path.as_dict()
295 2
        evc_dict['primary_path'] = self.primary_path.as_dict()
296 2
        evc_dict['backup_path'] = self.backup_path.as_dict()
297 2
        evc_dict['dynamic_backup_path'] = self.dynamic_backup_path
298
299
        # if self._requested:
300
        #     request_dict = self._requested.copy()
301
        #     request_dict['uni_a'] = request_dict['uni_a'].as_dict()
302
        #     request_dict['uni_z'] = request_dict['uni_z'].as_dict()
303
        #     request_dict['circuit_scheduler'] = self.circuit_scheduler
304
        #     evc_dict['_requested'] = request_dict
305
306 2
        evc_dict["request_time"] = self.request_time
307 2
        if isinstance(self.request_time, datetime):
308 2
            evc_dict["request_time"] = self.request_time.strftime(time_fmt)
309
310 2
        time = self.creation_time.strftime(time_fmt)
311 2
        evc_dict['creation_time'] = time
312
313 2
        evc_dict['owner'] = self.owner
314 2
        evc_dict['circuit_scheduler'] = self.circuit_scheduler
315
316 2
        evc_dict['active'] = self.is_active()
317 2
        evc_dict['enabled'] = self.is_enabled()
318 2
        evc_dict['priority'] = self.priority
319
320 2
        return evc_dict
321
322 2
    @property
323
    def id(self):  # pylint: disable=invalid-name
324
        """Return this EVC's ID."""
325 2
        return self._id
326
327
328
# pylint: disable=fixme, too-many-public-methods
329 2
class EVCDeploy(EVCBase):
330
    """Class to handle the deploy procedures."""
331
332 2
    def create(self):
333
        """Create a EVC."""
334
        pass
335
336 2
    def discover_new_path(self):
337
        """Discover a new path to satisfy this circuit and deploy."""
338 2
        return DynamicPathManager.get_best_path(self)
339
340 2
    def change_path(self):
341
        """Change EVC path."""
342
        pass
343
344 2
    def reprovision(self):
345
        """Force the EVC (re-)provisioning."""
346
        pass
347
348 2
    def is_affected_by_link(self, link):
349
        """Return True if this EVC has the given link on its current path."""
350
        return link in self.current_path
351
352 2
    def link_affected_by_interface(self, interface):
353
        """Return True if this EVC has the given link on its current path."""
354
        return self.current_path.link_affected_by_interface(interface)
355
356 2
    def is_backup_path_affected_by_link(self, link):
357
        """Return True if the backup path of this EVC uses the given link."""
358
        return link in self.backup_path
359
360
    # pylint: disable=invalid-name
361 2
    def is_primary_path_affected_by_link(self, link):
362
        """Return True if the primary path of this EVC uses the given link."""
363
        return link in self.primary_path
364
365 2
    def is_using_primary_path(self):
366
        """Verify if the current deployed path is self.primary_path."""
367
        return self.current_path == self.primary_path
368
369 2
    def is_using_backup_path(self):
370
        """Verify if the current deployed path is self.backup_path."""
371
        return self.current_path == self.backup_path
372
373 2
    def is_using_dynamic_path(self):
374
        """Verify if the current deployed path is a dynamic path."""
375
        if not self.is_using_primary_path() and \
376
           not self.is_using_backup_path() and \
377
           self.get_path_status(self.current_path) == EntityStatus.UP:
378
            return True
379
        return False
380
381 2
    def deploy_to_backup_path(self):
382
        """Deploy the backup path into the datapaths of this circuit.
383
384
        If the backup_path attribute is valid and up, this method will try to
385
        deploy this backup_path.
386
387
        If everything fails and dynamic_backup_path is True, then tries to
388
        deploy a dynamic path.
389
        """
390
        # TODO: Remove flows from current (cookies)
391 2
        if self.is_using_backup_path():
392
            # TODO: Log to say that cannot move backup to backup
393
            return True
394
395 2
        success = False
396 2
        if self.get_path_status(self.backup_path) is EntityStatus.UP:
397
            success = self.deploy_to_path(self.backup_path)
398
399 2
        if success:
400
            return True
401
402 2
        if self.dynamic_backup_path:
403
            return self.deploy_to_path()
404
405 2
        return False
406
407 2
    def deploy_to_primary_path(self):
408
        """Deploy the primary path into the datapaths of this circuit.
409
410
        If the primary_path attribute is valid and up, this method will try to
411
        deploy this primary_path.
412
        """
413
        # TODO: Remove flows from current (cookies)
414 2
        if self.is_using_primary_path():
415
            # TODO: Log to say that cannot move primary to primary
416
            return True
417
418 2
        if self.get_path_status(self.primary_path) is EntityStatus.UP:
419
            return self.deploy_to_path(self.primary_path)
420 2
        return False
421
422 2
    def deploy(self):
423
        """Deploy EVC to best path.
424
425
        Best path can be the primary path, if available. If not, the backup
426
        path, and, if it is also not available, a dynamic path.
427
        """
428 2
        success = self.deploy_to_primary_path()
429 2
        if not success:
430 2
            success = self.deploy_to_backup_path()
431
432 2
        return success
433
434 2
    @staticmethod
435
    def get_path_status(path):
436
        """Check for the current status of a path.
437
438
        If any link in this path is down, the path is considered down.
439
        """
440 2
        if not path:
441 2
            return EntityStatus.DISABLED
442
443
        for link in path:
444
            if link.status is not EntityStatus.UP:
445
                return link.status
446
        return EntityStatus.UP
447
448
#    def discover_new_path(self):
449
#        # TODO: discover a new path to satisfy this circuit and deploy
450
#        pass
451
452 2
    def remove(self):
453
        """Remove EVC path."""
454
        pass
455
456 2
    def remove_current_flows(self):
457
        """Remove all flows from current path."""
458 2
        switches = set()
459
460 2
        for link in self.current_path:
461 2
            switches.add(link.endpoint_a.switch)
462 2
            switches.add(link.endpoint_b.switch)
463
464 2
        match = {'cookie': self.get_cookie(),
465
                 'cookie_mask': 18446744073709551615}
466
467 2
        for switch in switches:
468 2
            self._send_flow_mods(switch, [match], 'delete')
469
470 2
        self.deactivate()
471
472 2
    @staticmethod
473 2
    def _choose_vlans(path=None):
474
        """Choose the VLANs to be used for the circuit."""
475 2
        for link in path:
476 2
            tag = link.get_next_available_tag()
477 2
            link.use_tag(tag)
478 2
            link.add_metadata('s_vlan', tag)
479
480 2
    @staticmethod
481 2
    def links_zipped(path=None):
482
        """Return an iterator which yields pairs of links in order."""
483 2
        if not path:
484
            return []
485 2
        return zip(path[:-1], path[1:])
486
487 2
    def should_deploy(self, path=None):
488
        """Verify if the circuit should be deployed."""
489 2
        if not path:
490 2
            log.debug("Path is empty.")
491 2
            return False
492
493 2
        if not self.is_enabled():
494 2
            log.debug(f'{self} is disabled.')
495 2
            return False
496
497 2
        if not self.is_active():
498 2
            log.debug(f'{self} will be deployed.')
499 2
            return True
500
501 2
        return False
502
503 2
    def deploy_to_path(self, path=None):
504
        """Install the flows for this circuit.
505
506
        Procedures to deploy:
507
508
        0. Remove current flows installed
509
        1. Decide if will deploy "path" or discover a new path
510
        2. Choose vlan
511
        3. Install NNI flows
512
        4. Install UNI flows
513
        5. Activate
514
        6. Update current_path
515
        7. Update links caches(primary, current, backup)
516
517
        """
518 2
        self.remove_current_flows()
519 2
        if not self.should_deploy(path):
520 2
            path = self.discover_new_path()
521 2
            if not path:
522 2
                return False
523
524 2
        self._choose_vlans(path)
525 2
        self._install_nni_flows(path)
526 2
        self._install_uni_flows(path)
527 2
        self.activate()
528 2
        self.current_path = path
529 2
        self.sync()
530 2
        log.info(f"{self} was deployed.")
531 2
        return True
532
533 2
    def _install_nni_flows(self, path=None):
534
        """Install NNI flows."""
535 2
        for incoming, outcoming in self.links_zipped(path):
536 2
            in_vlan = incoming.get_metadata('s_vlan').value
537 2
            out_vlan = outcoming.get_metadata('s_vlan').value
538
539 2
            flows = []
540
            # Flow for one direction
541 2
            flows.append(self._prepare_nni_flow(incoming.endpoint_b,
542
                                                outcoming.endpoint_a,
543
                                                in_vlan, out_vlan))
544
545
            # Flow for the other direction
546 2
            flows.append(self._prepare_nni_flow(outcoming.endpoint_a,
547
                                                incoming.endpoint_b,
548
                                                out_vlan, in_vlan))
549 2
            self._send_flow_mods(incoming.endpoint_b.switch, flows)
550
551 2
    def _install_uni_flows(self, path=None):
552
        """Install UNI flows."""
553 2
        if not path:
554
            log.info('install uni flows without path.')
555
            return
556
557
        # Determine VLANs
558 2
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
559 2
        out_vlan_a = path[0].get_metadata('s_vlan').value
560
561 2
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
562 2
        out_vlan_z = path[-1].get_metadata('s_vlan').value
563
564
        # Flows for the first UNI
565 2
        flows_a = []
566
567
        # Flow for one direction, pushing the service tag
568 2
        push_flow = self._prepare_push_flow(self.uni_a.interface,
569
                                            path[0].endpoint_a,
570
                                            in_vlan_a, out_vlan_a, in_vlan_z)
571 2
        flows_a.append(push_flow)
572
573
        # Flow for the other direction, popping the service tag
574 2
        pop_flow = self._prepare_pop_flow(path[0].endpoint_a,
575
                                          self.uni_a.interface, out_vlan_a)
576 2
        flows_a.append(pop_flow)
577
578 2
        self._send_flow_mods(self.uni_a.interface.switch, flows_a)
579
580
        # Flows for the second UNI
581 2
        flows_z = []
582
583
        # Flow for one direction, pushing the service tag
584 2
        push_flow = self._prepare_push_flow(self.uni_z.interface,
585
                                            path[-1].endpoint_b,
586
                                            in_vlan_z, out_vlan_z, in_vlan_a)
587 2
        flows_z.append(push_flow)
588
589
        # Flow for the other direction, popping the service tag
590 2
        pop_flow = self._prepare_pop_flow(path[-1].endpoint_b,
591
                                          self.uni_z.interface, out_vlan_z)
592 2
        flows_z.append(pop_flow)
593
594 2
        self._send_flow_mods(self.uni_z.interface.switch, flows_z)
595
596 2
    @staticmethod
597 2
    def _send_flow_mods(switch, flow_mods, command='flows'):
598
        """Send a flow_mod list to a specific switch.
599
600
        Args:
601
            switch(Switch): The target of flows.
602
            flow_mods(dict): Python dictionary with flow_mods.
603
            command(str): By default is 'flows'. To remove a flow is 'remove'.
604
605
        """
606 2
        endpoint = f'{settings.MANAGER_URL}/{command}/{switch.id}'
607
608 2
        data = {"flows": flow_mods}
609 2
        requests.post(endpoint, json=data)
610
611 2
    def get_cookie(self):
612
        """Return the cookie integer from evc id."""
613 2
        value = self.id[len(self.id)//2:]
614 2
        return int(value, 16)
615
616 2
    def _prepare_flow_mod(self, in_interface, out_interface):
617
        """Prepare a common flow mod."""
618 2
        default_action = {"action_type": "output",
619
                          "port": out_interface.port_number}
620
621 2
        flow_mod = {"match": {"in_port": in_interface.port_number},
622
                    "cookie": self.get_cookie(),
623
                    "actions": [default_action]}
624
625 2
        return flow_mod
626
627 2
    def _prepare_nni_flow(self,
628
                          in_interface, out_interface, in_vlan, out_vlan):
629
        """Create NNI flows."""
630 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
631 2
        flow_mod['match']['dl_vlan'] = in_vlan
632
633 2
        new_action = {"action_type": "set_vlan",
634
                      "vlan_id": out_vlan}
635 2
        flow_mod["actions"].insert(0, new_action)
636
637 2
        return flow_mod
638
639 2
    def _prepare_push_flow(self, *args):
640
        """Prepare push flow.
641
642
        Arguments:
643
            in_interface(str): Interface input.
644
            out_interface(str): Interface output.
645
            in_vlan(str): Vlan input.
646
            out_vlan(str): Vlan output.
647
            new_in_vlan(str): Interface input.
648
649
        Return:
650
            dict: An python dictionary representing a FlowMod
651
652
        """
653
        # assign all arguments
654 2
        in_interface, out_interface, in_vlan, out_vlan, new_in_vlan = args
655
656 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
657 2
        flow_mod['match']['dl_vlan'] = in_vlan
658
659 2
        new_action = {"action_type": "set_vlan",
660
                      "vlan_id": out_vlan}
661 2
        flow_mod["actions"].insert(0, new_action)
662
663 2
        new_action = {"action_type": "push_vlan",
664
                      "tag_type": "s"}
665 2
        flow_mod["actions"].insert(0, new_action)
666
667 2
        new_action = {"action_type": "set_vlan",
668
                      "vlan_id": new_in_vlan}
669 2
        flow_mod["actions"].insert(0, new_action)
670
671 2
        return flow_mod
672
673 2
    def _prepare_pop_flow(self, in_interface, out_interface, in_vlan):
674
        """Prepare pop flow."""
675 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
676 2
        flow_mod['match']['dl_vlan'] = in_vlan
677 2
        new_action = {"action_type": "pop_vlan"}
678 2
        flow_mod["actions"].insert(0, new_action)
679 2
        return flow_mod
680
681
682 2
class LinkProtection(EVCDeploy):
683
    """Class to handle link protection."""
684
685 2
    def is_affected_by_link(self, link=None):
686
        """Verify if the current path is affected by link down event."""
687
        return self.current_path.is_affected_by_link(link)
688
689 2
    def is_using_primary_path(self):
690
        """Verify if the current deployed path is self.primary_path."""
691 2
        return self.current_path == self.primary_path
692
693 2
    def is_using_backup_path(self):
694
        """Verify if the current deployed path is self.backup_path."""
695 2
        return self.current_path == self.backup_path
696
697 2
    def is_using_dynamic_path(self):
698
        """Verify if the current deployed path is dynamic."""
699 2
        if not self.is_using_primary_path() and \
700
           not self.is_using_backup_path() and \
701
           self.current_path.status is EntityStatus.UP:
702
            return True
703 2
        return False
704
705 2
    def deploy_to(self, path_name=None, path=None):
706
        """Create a deploy to path."""
707 2
        if self.current_path == path:
708 2
            log.debug(f'{path_name} is equal to current_path.')
709 2
            return True
710
711 2
        if path.status is EntityStatus.UP:
712 2
            return self.deploy_to_path(path)
713
714 2
        return False
715
716 2
    def handle_link_up(self, link):
717
        """Handle circuit when link down.
718
719
        Args:
720
            link(Link): Link affected by link.down event.
721
722
        """
723 2
        if self.is_using_primary_path():
724 2
            return True
725
726 2
        success = False
727 2
        if self.primary_path.is_affected_by_link(link):
728 2
            success = self.deploy_to('primary_path', self.primary_path)
729
730 2
        if success:
731 2
            return True
732
733
        # We tried to deploy(primary_path) without success.
734
        # And in this case is up by some how. Nothing to do.
735 2
        if self.is_using_backup_path() or self.is_using_dynamic_path():
736
            return True
737
738
        # In this case, probably the circuit is not being used and
739
        # we can move to backup
740 2
        if self.backup_path.is_affected_by_link(link):
741 2
            success = self.deploy_to('backup_path', self.backup_path)
742
743 2
        if success:
744 2
            return True
745
746
        # In this case, the circuit is not being used and we should
747
        # try a dynamic path
748 2
        if self.dynamic_backup_path:
749 2
            return self.deploy_to_path()
750
751
        return True
752
753 2
    def handle_link_down(self):
754
        """Handle circuit when link down.
755
756
        Returns:
757
            bool: True if the re-deploy was successly otherwise False.
758
759
        """
760 2
        success = False
761 2
        if self.is_using_primary_path():
762 2
            success = self.deploy_to('backup_path', self.backup_path)
763 2
        elif self.is_using_backup_path():
764 2
            success = self.deploy_to('primary_path', self.primary_path)
765
766 2
        if not success and self.dynamic_backup_path:
767 2
            success = self.deploy_to_path()
768
769 2
        if success:
770 2
            log.debug(f"{self} deployed after link down.")
771
        else:
772 2
            log.debug(f'Failed to re-deploy {self} after link down.')
773
774 2
        return success
775
776
777 2
class EVC(LinkProtection):
778
    """Class that represents a E-Line Virtual Connection."""
779
780
    pass
781