Test Failed
Push — master ( 0d7af6...292dca )
by Beraldo
04:07 queued 01:46
created

build.models.EVCBase._validate()   B

Complexity

Conditions 6

Size

Total Lines 24
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6.0208

Importance

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