Test Failed
Pull Request — master (#123)
by Antonio
03:22
created

build.models.Path.choose_vlans()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 2

Importance

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