Passed
Pull Request — master (#180)
by Antonio
03:58 queued 10s
created

build.models.Path.status()   B

Complexity

Conditions 7

Size

Total Lines 27
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.392

Importance

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