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