Test Failed
Pull Request — master (#125)
by Antonio
05:08
created

build.models.Path.status()   B

Complexity

Conditions 6

Size

Total Lines 24
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 6.0702

Importance

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