Passed
Pull Request — master (#116)
by Antonio
05:06
created

build.models.EVCDeploy.remove()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

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