Passed
Pull Request — master (#131)
by Antonio
04:28
created

build.models.EVCDeploy.schedule_deploy()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.2963

Importance

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