Passed
Push — master ( f94a12...3874eb )
by Beraldo
03:09 queued 11s
created

build.models.EVCDeploy.links_zipped()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 0
Metric Value
cc 2
eloc 5
nop 1
dl 0
loc 6
ccs 4
cts 5
cp 0.8
crap 2.032
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 interfaces."""
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
                if 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
335 2
    def discover_new_path(self):
336
        """Discover a new path to satisfy this circuit and deploy."""
337 2
        return DynamicPathManager.get_best_path(self)
338
339 2
    def change_path(self):
340
        """Change EVC path."""
341
342 2
    def reprovision(self):
343
        """Force the EVC (re-)provisioning."""
344
345 2
    def is_affected_by_link(self, link):
346
        """Return True if this EVC has the given link on its current path."""
347
        return link in self.current_path
348
349 2
    def link_affected_by_interface(self, interface):
350
        """Return True if this EVC has the given link on its current path."""
351
        return self.current_path.link_affected_by_interface(interface)
352
353 2
    def is_backup_path_affected_by_link(self, link):
354
        """Return True if the backup path of this EVC uses the given link."""
355
        return link in self.backup_path
356
357
    # pylint: disable=invalid-name
358 2
    def is_primary_path_affected_by_link(self, link):
359
        """Return True if the primary path of this EVC uses the given link."""
360
        return link in self.primary_path
361
362 2
    def is_using_primary_path(self):
363
        """Verify if the current deployed path is self.primary_path."""
364
        return self.current_path == self.primary_path
365
366 2
    def is_using_backup_path(self):
367
        """Verify if the current deployed path is self.backup_path."""
368
        return self.current_path == self.backup_path
369
370 2
    def is_using_dynamic_path(self):
371
        """Verify if the current deployed path is a dynamic path."""
372
        if not self.is_using_primary_path() and \
373
           not self.is_using_backup_path() and \
374
           self.get_path_status(self.current_path) == EntityStatus.UP:
375
            return True
376
        return False
377
378 2
    def deploy_to_backup_path(self):
379
        """Deploy the backup path into the datapaths of this circuit.
380
381
        If the backup_path attribute is valid and up, this method will try to
382
        deploy this backup_path.
383
384
        If everything fails and dynamic_backup_path is True, then tries to
385
        deploy a dynamic path.
386
        """
387
        # TODO: Remove flows from current (cookies)
388 2
        if self.is_using_backup_path():
389
            # TODO: Log to say that cannot move backup to backup
390
            return True
391
392 2
        success = False
393 2
        if self.get_path_status(self.backup_path) is EntityStatus.UP:
394
            success = self.deploy_to_path(self.backup_path)
395
396 2
        if success:
397
            return True
398
399 2
        if self.dynamic_backup_path:
400
            return self.deploy_to_path()
401
402 2
        return False
403
404 2
    def deploy_to_primary_path(self):
405
        """Deploy the primary path into the datapaths of this circuit.
406
407
        If the primary_path attribute is valid and up, this method will try to
408
        deploy this primary_path.
409
        """
410
        # TODO: Remove flows from current (cookies)
411 2
        if self.is_using_primary_path():
412
            # TODO: Log to say that cannot move primary to primary
413
            return True
414
415 2
        if self.get_path_status(self.primary_path) is EntityStatus.UP:
416
            return self.deploy_to_path(self.primary_path)
417 2
        return False
418
419 2
    def deploy(self):
420
        """Deploy EVC to best path.
421
422
        Best path can be the primary path, if available. If not, the backup
423
        path, and, if it is also not available, a dynamic path.
424
        """
425 2
        success = self.deploy_to_primary_path()
426 2
        if not success:
427 2
            success = self.deploy_to_backup_path()
428
429 2
        return success
430
431 2
    @staticmethod
432
    def get_path_status(path):
433
        """Check for the current status of a path.
434
435
        If any link in this path is down, the path is considered down.
436
        """
437 2
        if not path:
438 2
            return EntityStatus.DISABLED
439
440
        for link in path:
441
            if link.status is not EntityStatus.UP:
442
                return link.status
443
        return EntityStatus.UP
444
445
#    def discover_new_path(self):
446
#        # TODO: discover a new path to satisfy this circuit and deploy
447
448 2
    def remove(self):
449
        """Remove EVC path."""
450
451 2
    def remove_current_flows(self):
452
        """Remove all flows from current path."""
453 2
        switches = set()
454
455 2
        for link in self.current_path:
456 2
            switches.add(link.endpoint_a.switch)
457 2
            switches.add(link.endpoint_b.switch)
458
459 2
        match = {'cookie': self.get_cookie(),
460
                 'cookie_mask': 18446744073709551615}
461
462 2
        for switch in switches:
463 2
            self._send_flow_mods(switch, [match], 'delete')
464
465 2
        self.deactivate()
466
467 2
    @staticmethod
468 2
    def _choose_vlans(path=None):
469
        """Choose the VLANs to be used for the circuit."""
470 2
        for link in path:
471 2
            tag = link.get_next_available_tag()
472 2
            link.use_tag(tag)
473 2
            link.add_metadata('s_vlan', tag)
474
475 2
    @staticmethod
476 2
    def links_zipped(path=None):
477
        """Return an iterator which yields pairs of links in order."""
478 2
        if not path:
479
            return []
480 2
        return zip(path[:-1], path[1:])
481
482 2
    def should_deploy(self, path=None):
483
        """Verify if the circuit should be deployed."""
484 2
        if not path:
485 2
            log.debug("Path is empty.")
486 2
            return False
487
488 2
        if not self.is_enabled():
489 2
            log.debug(f'{self} is disabled.')
490 2
            return False
491
492 2
        if not self.is_active():
493 2
            log.debug(f'{self} will be deployed.')
494 2
            return True
495
496 2
        return False
497
498 2
    def deploy_to_path(self, path=None):
499
        """Install the flows for this circuit.
500
501
        Procedures to deploy:
502
503
        0. Remove current flows installed
504
        1. Decide if will deploy "path" or discover a new path
505
        2. Choose vlan
506
        3. Install NNI flows
507
        4. Install UNI flows
508
        5. Activate
509
        6. Update current_path
510
        7. Update links caches(primary, current, backup)
511
512
        """
513 2
        self.remove_current_flows()
514 2
        if not self.should_deploy(path):
515 2
            path = self.discover_new_path()
516 2
            if not path:
517 2
                return False
518
519 2
        self._choose_vlans(path)
520 2
        self._install_nni_flows(path)
521 2
        self._install_uni_flows(path)
522 2
        self.activate()
523 2
        self.current_path = path
524 2
        self.sync()
525 2
        log.info(f"{self} was deployed.")
526 2
        return True
527
528 2
    def _install_nni_flows(self, path=None):
529
        """Install NNI flows."""
530 2
        for incoming, outcoming in self.links_zipped(path):
531 2
            in_vlan = incoming.get_metadata('s_vlan').value
532 2
            out_vlan = outcoming.get_metadata('s_vlan').value
533
534 2
            flows = []
535
            # Flow for one direction
536 2
            flows.append(self._prepare_nni_flow(incoming.endpoint_b,
537
                                                outcoming.endpoint_a,
538
                                                in_vlan, out_vlan))
539
540
            # Flow for the other direction
541 2
            flows.append(self._prepare_nni_flow(outcoming.endpoint_a,
542
                                                incoming.endpoint_b,
543
                                                out_vlan, in_vlan))
544 2
            self._send_flow_mods(incoming.endpoint_b.switch, flows)
545
546 2
    def _install_uni_flows(self, path=None):
547
        """Install UNI flows."""
548 2
        if not path:
549
            log.info('install uni flows without path.')
550
            return
551
552
        # Determine VLANs
553 2
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
554 2
        out_vlan_a = path[0].get_metadata('s_vlan').value
555
556 2
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
557 2
        out_vlan_z = path[-1].get_metadata('s_vlan').value
558
559
        # Flows for the first UNI
560 2
        flows_a = []
561
562
        # Flow for one direction, pushing the service tag
563 2
        push_flow = self._prepare_push_flow(self.uni_a.interface,
564
                                            path[0].endpoint_a,
565
                                            in_vlan_a, out_vlan_a, in_vlan_z)
566 2
        flows_a.append(push_flow)
567
568
        # Flow for the other direction, popping the service tag
569 2
        pop_flow = self._prepare_pop_flow(path[0].endpoint_a,
570
                                          self.uni_a.interface, out_vlan_a)
571 2
        flows_a.append(pop_flow)
572
573 2
        self._send_flow_mods(self.uni_a.interface.switch, flows_a)
574
575
        # Flows for the second UNI
576 2
        flows_z = []
577
578
        # Flow for one direction, pushing the service tag
579 2
        push_flow = self._prepare_push_flow(self.uni_z.interface,
580
                                            path[-1].endpoint_b,
581
                                            in_vlan_z, out_vlan_z, in_vlan_a)
582 2
        flows_z.append(push_flow)
583
584
        # Flow for the other direction, popping the service tag
585 2
        pop_flow = self._prepare_pop_flow(path[-1].endpoint_b,
586
                                          self.uni_z.interface, out_vlan_z)
587 2
        flows_z.append(pop_flow)
588
589 2
        self._send_flow_mods(self.uni_z.interface.switch, flows_z)
590
591 2
    @staticmethod
592 2
    def _send_flow_mods(switch, flow_mods, command='flows'):
593
        """Send a flow_mod list to a specific switch.
594
595
        Args:
596
            switch(Switch): The target of flows.
597
            flow_mods(dict): Python dictionary with flow_mods.
598
            command(str): By default is 'flows'. To remove a flow is 'remove'.
599
600
        """
601 2
        endpoint = f'{settings.MANAGER_URL}/{command}/{switch.id}'
602
603 2
        data = {"flows": flow_mods}
604 2
        requests.post(endpoint, json=data)
605
606 2
    def get_cookie(self):
607
        """Return the cookie integer from evc id."""
608 2
        value = self.id[len(self.id)//2:]
609 2
        return int(value, 16)
610
611 2
    def _prepare_flow_mod(self, in_interface, out_interface):
612
        """Prepare a common flow mod."""
613 2
        default_action = {"action_type": "output",
614
                          "port": out_interface.port_number}
615
616 2
        flow_mod = {"match": {"in_port": in_interface.port_number},
617
                    "cookie": self.get_cookie(),
618
                    "actions": [default_action]}
619
620 2
        return flow_mod
621
622 2
    def _prepare_nni_flow(self,
623
                          in_interface, out_interface, in_vlan, out_vlan):
624
        """Create NNI flows."""
625 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
626 2
        flow_mod['match']['dl_vlan'] = in_vlan
627
628 2
        new_action = {"action_type": "set_vlan",
629
                      "vlan_id": out_vlan}
630 2
        flow_mod["actions"].insert(0, new_action)
631
632 2
        return flow_mod
633
634 2
    def _prepare_push_flow(self, *args):
635
        """Prepare push flow.
636
637
        Arguments:
638
            in_interface(str): Interface input.
639
            out_interface(str): Interface output.
640
            in_vlan(str): Vlan input.
641
            out_vlan(str): Vlan output.
642
            new_in_vlan(str): Interface input.
643
644
        Return:
645
            dict: An python dictionary representing a FlowMod
646
647
        """
648
        # assign all arguments
649 2
        in_interface, out_interface, in_vlan, out_vlan, new_in_vlan = args
650
651 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
652 2
        flow_mod['match']['dl_vlan'] = in_vlan
653
654 2
        new_action = {"action_type": "set_vlan",
655
                      "vlan_id": out_vlan}
656 2
        flow_mod["actions"].insert(0, new_action)
657
658 2
        new_action = {"action_type": "push_vlan",
659
                      "tag_type": "s"}
660 2
        flow_mod["actions"].insert(0, new_action)
661
662 2
        new_action = {"action_type": "set_vlan",
663
                      "vlan_id": new_in_vlan}
664 2
        flow_mod["actions"].insert(0, new_action)
665
666 2
        return flow_mod
667
668 2
    def _prepare_pop_flow(self, in_interface, out_interface, in_vlan):
669
        """Prepare pop flow."""
670 2
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
671 2
        flow_mod['match']['dl_vlan'] = in_vlan
672 2
        new_action = {"action_type": "pop_vlan"}
673 2
        flow_mod["actions"].insert(0, new_action)
674 2
        return flow_mod
675
676
677 2
class LinkProtection(EVCDeploy):
678
    """Class to handle link protection."""
679
680 2
    def is_affected_by_link(self, link=None):
681
        """Verify if the current path is affected by link down event."""
682
        return self.current_path.is_affected_by_link(link)
683
684 2
    def is_using_primary_path(self):
685
        """Verify if the current deployed path is self.primary_path."""
686 2
        return self.current_path == self.primary_path
687
688 2
    def is_using_backup_path(self):
689
        """Verify if the current deployed path is self.backup_path."""
690 2
        return self.current_path == self.backup_path
691
692 2
    def is_using_dynamic_path(self):
693
        """Verify if the current deployed path is dynamic."""
694 2
        if not self.is_using_primary_path() and \
695
           not self.is_using_backup_path() and \
696
           self.current_path.status is EntityStatus.UP:
697
            return True
698 2
        return False
699
700 2
    def deploy_to(self, path_name=None, path=None):
701
        """Create a deploy to path."""
702 2
        if self.current_path == path:
703 2
            log.debug(f'{path_name} is equal to current_path.')
704 2
            return True
705
706 2
        if path.status is EntityStatus.UP:
707 2
            return self.deploy_to_path(path)
708
709 2
        return False
710
711 2
    def handle_link_up(self, link):
712
        """Handle circuit when link down.
713
714
        Args:
715
            link(Link): Link affected by link.down event.
716
717
        """
718 2
        if self.is_using_primary_path():
719 2
            return True
720
721 2
        success = False
722 2
        if self.primary_path.is_affected_by_link(link):
723 2
            success = self.deploy_to('primary_path', self.primary_path)
724
725 2
        if success:
726 2
            return True
727
728
        # We tried to deploy(primary_path) without success.
729
        # And in this case is up by some how. Nothing to do.
730 2
        if self.is_using_backup_path() or self.is_using_dynamic_path():
731
            return True
732
733
        # In this case, probably the circuit is not being used and
734
        # we can move to backup
735 2
        if self.backup_path.is_affected_by_link(link):
736 2
            success = self.deploy_to('backup_path', self.backup_path)
737
738 2
        if success:
739 2
            return True
740
741
        # In this case, the circuit is not being used and we should
742
        # try a dynamic path
743 2
        if self.dynamic_backup_path:
744 2
            return self.deploy_to_path()
745
746
        return True
747
748 2
    def handle_link_down(self):
749
        """Handle circuit when link down.
750
751
        Returns:
752
            bool: True if the re-deploy was successly otherwise False.
753
754
        """
755 2
        success = False
756 2
        if self.is_using_primary_path():
757 2
            success = self.deploy_to('backup_path', self.backup_path)
758 2
        elif self.is_using_backup_path():
759 2
            success = self.deploy_to('primary_path', self.primary_path)
760
761 2
        if not success and self.dynamic_backup_path:
762 2
            success = self.deploy_to_path()
763
764 2
        if success:
765 2
            log.debug(f"{self} deployed after link down.")
766
        else:
767 2
            log.debug(f'Failed to re-deploy {self} after link down.')
768
769 2
        return success
770
771
772 2
class EVC(LinkProtection):
773
    """Class that represents a E-Line Virtual Connection."""
774