Test Failed
Push — master ( 087782...9ad0e5 )
by Antonio
03:03 queued 11s
created

build.models.EVCBase.archive()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.125

Importance

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