Passed
Pull Request — master (#123)
by Antonio
04:53
created

build.models.Path.choose_vlans()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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