Test Failed
Pull Request — master (#123)
by Antonio
04:43 queued 58s
created

build.models.Path.choose_vlans()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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