Test Failed
Pull Request — master (#131)
by Antonio
04:57
created

build.models.EVCDeploy.schedule_remove()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 4
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Classes used in the main application."""
2 2
from datetime import datetime
3 2
from uuid import uuid4
4
5 2
import requests
6
7 2
from kytos.core import log
8 2
from kytos.core.common import EntityStatus, GenericEntity
9 2
from kytos.core.helpers import get_time, now
10 2
from kytos.core.interface import UNI
11 2
from kytos.core.link import Link
12 2
from napps.kytos.mef_eline import settings
13 2
from napps.kytos.mef_eline.storehouse import StoreHouse
14
15
16 2
class Path(list, GenericEntity):
17
    """Class to represent a Path."""
18
19 2
    def __eq__(self, other=None):
20
        """Compare paths."""
21 2
        if not other or not isinstance(other, Path):
22 2
            return False
23 2
        return super().__eq__(other)
24
25 2
    def is_affected_by_link(self, link=None):
26
        """Verify if the current path is affected by link."""
27 2
        if not link:
28
            return False
29 2
        return link in self
30
31 2
    def link_affected_by_interface(self, interface=None):
32
        """Return the link using this interface, if any, or None otherwise."""
33
        if not interface:
34
            return None
35
        for link in self:
36
            if interface in (link.endpoint_a, link.endpoint_b):
37
                return link
38
        return None
39
40 2
    def choose_vlans(self):
41
        """Choose the VLANs to be used for the circuit."""
42 2
        for link in self:
43 2
            tag = link.get_next_available_tag()
44 2
            link.use_tag(tag)
45 2
            link.add_metadata('s_vlan', tag)
46
47 2
    def make_vlans_available(self):
48
        """Make the VLANs used in a path available when undeployed."""
49 2
        for link in self:
50 2
            link.make_tag_available(link.get_metadata('s_vlan'))
51 2
            link.remove_metadata('s_vlan')
52
53 2
    @property
54
    def status(self):
55
        """Check for the  status of a path.
56
57
        If any link in this path is down, the path is considered down.
58
        """
59 2
        if not self:
60 2
            return EntityStatus.DISABLED
61
62 2
        endpoint = '%s/%s' % (settings.TOPOLOGY_URL, 'links')
63 2
        api_reply = requests.get(endpoint)
64 2
        if api_reply.status_code != getattr(requests.codes, 'ok'):
65
            log.error('Failed to get links at %s. Returned %s',
66
                      endpoint, api_reply.status_code)
67
            return None
68 2
        links = api_reply.json()['links']
69 2
        for path_link in self:
70 2
            try:
71 2
                link = links[path_link.id]
72
            except KeyError:
73
                return EntityStatus.DOWN
74 2
            if link['active'] is False:
75 2
                return EntityStatus.DOWN
76 2
        return EntityStatus.UP
77
78 2
    def as_dict(self):
79
        """Return list comprehension of links as_dict."""
80 2
        return [link.as_dict() for link in self if link]
81
82
83 2
class DynamicPathManager:
84
    """Class to handle and create paths."""
85
86 2
    controller = None
87
88 2
    @classmethod
89 2
    def set_controller(cls, controller=None):
90
        """Set the controller to discovery news paths."""
91 2
        cls.controller = controller
92
93 2
    @staticmethod
94
    def get_paths(circuit):
95
        """Get a valid path for the circuit from the Pathfinder."""
96
        endpoint = settings.PATHFINDER_URL
97
        request_data = {"source": circuit.uni_a.interface.id,
98
                        "destination": circuit.uni_z.interface.id}
99
        api_reply = requests.post(endpoint, json=request_data)
100
101
        if api_reply.status_code != getattr(requests.codes, 'ok'):
102
            log.error("Failed to get paths at %s. Returned %s",
103
                      endpoint, api_reply.status_code)
104
            return None
105
        reply_data = api_reply.json()
106
        return reply_data.get('paths')
107
108 2
    @staticmethod
109
    def _clear_path(path):
110
        """Remove switches from a path, returning only interfaces."""
111
        return [endpoint for endpoint in path if len(endpoint) > 23]
112
113 2
    @classmethod
114
    def get_best_path(cls, circuit):
115
        """Return the best path available for a circuit, if exists."""
116
        paths = cls.get_paths(circuit)
117
        if paths:
118
            return cls.create_path(cls.get_paths(circuit)[0]['hops'])
119
        return None
120
121 2
    @classmethod
122
    def create_path(cls, path):
123
        """Return the path containing only the interfaces."""
124
        new_path = Path()
125
        clean_path = cls._clear_path(path)
126
127
        if len(clean_path) % 2:
128
            return None
129
130
        for link in zip(clean_path[1:-1:2], clean_path[2::2]):
131
            interface_a = cls.controller.get_interface_by_id(link[0])
132
            interface_b = cls.controller.get_interface_by_id(link[1])
133
            if interface_a is None or interface_b is None:
134
                return None
135
            new_path.append(Link(interface_a, interface_b))
136
137
        return new_path
138
139
140 2
class EVCBase(GenericEntity):
141
    """Class to represent a circuit."""
142
143 2
    unique_attributes = ['name', 'uni_a', 'uni_z']
144
145 2
    def __init__(self, controller, **kwargs):
146
        """Create an EVC instance with the provided parameters.
147
148
        Args:
149
            id(str): EVC identifier. Whether it's None an ID will be genereted.
150
            name: represents an EVC name.(Required)
151
            uni_a (UNI): Endpoint A for User Network Interface.(Required)
152
            uni_z (UNI): Endpoint Z for User Network Interface.(Required)
153
            start_date(datetime|str): Date when the EVC was registred.
154
                                      Default is now().
155
            end_date(datetime|str): Final date that the EVC will be fineshed.
156
                                    Default is None.
157
            bandwidth(int): Bandwidth used by EVC instance. Default is 0.
158
            primary_links(list): Primary links used by evc. Default is []
159
            backup_links(list): Backups links used by evc. Default is []
160
            current_path(list): Circuit being used at the moment if this is an
161
                                active circuit. Default is [].
162
            primary_path(list): primary circuit offered to user IF one or more
163
                                links were provided. Default is [].
164
            backup_path(list): backup circuit offered to the user IF one or
165
                               more links were provided. Default is [].
166
            dynamic_backup_path(bool): Enable computer backup path dynamically.
167
                                       Dafault is False.
168
            creation_time(datetime|str): datetime when the circuit should be
169
                                         activated. default is now().
170
            enabled(Boolean): attribute to indicate the 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
        self.schedule_active = kwargs.get('schedule_active', False)
206 2
        if not self.circuit_scheduler:
207 2
            self.schedule_active = True
208 2
209
        self.current_links_cache = set()
210 2
        self.primary_links_cache = set()
211
        self.backup_links_cache = set()
212 2
213 2
        self._storehouse = StoreHouse(controller)
214
215 2
        if kwargs.get('active', False):
216
            self.activate()
217 2
        else:
218 2
            self.deactivate()
219
220 2
        if kwargs.get('enabled', False):
221
            self.enable()
222
        else:
223
            self.disable()
224 2
225
        # datetime of user request for a EVC (or datetime when object was
226 2
        # created)
227
        self.request_time = kwargs.get('request_time', now())
228 2
        # dict with the user original request (input)
229
        self._requested = kwargs
230 2
231
    def sync(self):
232 2
        """Sync this EVC in the storehouse."""
233
        self._storehouse.save_evc(self)
234
235
    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 2
            ValueError: message with error detail.
243 2
244 2
        """
245
        for attribute, value in kwargs.items():
246
            if attribute in self.unique_attributes:
247
                raise ValueError(f'{attribute} can\'t be be updated.')
248
            if hasattr(self, attribute):
249
                setattr(self, attribute, value)
250
            else:
251 2
                raise ValueError(f'The attribute "{attribute}" is invalid.')
252
        self.sync()
253 2
254
    def __repr__(self):
255 2
        """Repr method."""
256
        return f"EVC({self._id}, {self.name})"
257
258
    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 2
            ValueError: message with error detail.
266
267 2
        """
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 2
273
            if 'uni' in attribute:
274
                uni = kwargs.get(attribute)
275 2
                if not isinstance(uni, UNI):
276 2
                    raise ValueError(f'{attribute} is an invalid UNI.')
277 2
278 2
                if not uni.is_valid():
279
                    tag = uni.user_tag.value
280 2
                    message = f'VLAN tag {tag} is not available in {attribute}'
281
                    raise ValueError(message)
282 2
283
    def __eq__(self, other):
284
        """Override the default implementation."""
285 2
        if not isinstance(other, EVC):
286 2
            return False
287 2
288 2
        attrs_to_compare = ['name', 'uni_a', 'uni_z', 'owner', 'bandwidth']
289 2
        for attribute in attrs_to_compare:
290
            if getattr(other, attribute) != getattr(self, attribute):
291 2
                return False
292
        return True
293 2
294
    def as_dict(self):
295
        """Return a dictionary representing an EVC object."""
296
        evc_dict = {"id": self.id, "name": self.name,
297 2
                    "uni_a": self.uni_a.as_dict(),
298
                    "uni_z": self.uni_z.as_dict()}
299 2
300 2
        time_fmt = "%Y-%m-%dT%H:%M:%S"
301 2
302
        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 2
306
        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 2
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
        evc_dict['primary_path'] = self.primary_path.as_dict()
315
        evc_dict['backup_path'] = self.backup_path.as_dict()
316
        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 2
        #     request_dict['circuit_scheduler'] = self.circuit_scheduler
323 2
        #     evc_dict['_requested'] = request_dict
324 2
325
        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
        evc_dict['owner'] = self.owner
333 2
        evc_dict['circuit_scheduler'] = [sc.as_dict()
334 2
                                         for sc in self.circuit_scheduler]
335 2
336
        evc_dict['active'] = self.is_active()
337 2
        evc_dict['enabled'] = self.is_enabled()
338
        evc_dict['priority'] = self.priority
339 2
        evc_dict['schedule_active'] = self.schedule_active
340
341
        return evc_dict
342 2
343
    @property
344
    def id(self):  # pylint: disable=invalid-name
345
        """Return this EVC's ID."""
346 2
        return self._id
347
348
349 2
# pylint: disable=fixme, too-many-public-methods
350
class EVCDeploy(EVCBase):
351
    """Class to handle the deploy procedures."""
352 2
353
    def create(self):
354 2
        """Create a EVC."""
355
356 2
    def discover_new_path(self):
357
        """Discover a new path to satisfy this circuit and deploy."""
358
        return DynamicPathManager.get_best_path(self)
359 2
360
    def change_path(self):
361
        """Change EVC path."""
362 2
363
    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
    def is_backup_path_affected_by_link(self, link):
375 2
        """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
    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 2
           self.current_path.status == EntityStatus.UP:
397
            return True
398
        return False
399
400
    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 2
        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 2
            # TODO: Log to say that cannot move backup to backup
412 2
            return True
413
414 2
        success = False
415 2
        if self.backup_path.status is EntityStatus.UP:
416
            success = self.deploy_to_path(self.backup_path)
417 2
418 2
        if success:
419
            return True
420 2
421
        if self.dynamic_backup_path:
422 2
            return self.deploy_to_path()
423
424
        return False
425
426
    def deploy_to_primary_path(self):
427
        """Deploy the primary path into the datapaths of this circuit.
428
429 2
        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 2
            # TODO: Log to say that cannot move primary to primary
435 2
            return True
436
437 2
        if self.primary_path.status is EntityStatus.UP:
438
            return self.deploy_to_path(self.primary_path)
439
        return False
440
441
    def schedule_deploy(self):
442
        """Set called by schedule and call deploy."""
443 2
        self.schedule_active = True
444 2
        self.deploy()
445 2
446 2
    def schedule_remove(self):
447
        """Set called by schedule and call remove."""
448 2
        self.schedule_active = False
449
        self.remove()
450 2
451
    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
        log.info('Starting deployment of %s' % self)
458
        self.activate()
459
        success = self.deploy_to_primary_path()
460
        if not success:
461
            success = self.deploy_to_backup_path()
462
463
        return success
464
465
    @staticmethod
466
    def get_path_status(path):
467 2
        """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 2
        if not path:
472
            return EntityStatus.DISABLED
473 2
474
        for link in path:
475 2
            if link.status is not EntityStatus.UP:
476 2
                return link.status
477 2
        return EntityStatus.UP
478
479 2
#    def discover_new_path(self):
480
#        # TODO: discover a new path to satisfy this circuit and deploy
481
482 2
    def remove(self):
483 2
        """Remove EVC path and disable it."""
484
        self.remove_current_flows()
485 2
486 2
    def remove_current_flows(self):
487 2
        """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
            switches.add(link.endpoint_b.switch)
493 2
494
        match = {'cookie': self.get_cookie(),
495 2
                 'cookie_mask': 18446744073709551615}
496
497 2
        for switch in switches:
498
            self._send_flow_mods(switch, [match], 'delete')
499 2
500 2
        self.current_path.make_vlans_available()
501 2
        self.current_path = Path([])
502
        self.deactivate()
503 2
        self.sync()
504 2
505 2
    @staticmethod
506
    def links_zipped(path=None):
507 2
        """Return an iterator which yields pairs of links in order."""
508 2
        if not path:
509 2
            return []
510
        return zip(path[:-1], path[1:])
511 2
512
    def should_deploy(self, path=None):
513 2
        """Verify if the circuit should be deployed."""
514
        if not path:
515
            log.debug("Path is empty.")
516
            return False
517
518
        if not self.is_enabled():
519
            log.debug(f'{self} is disabled.')
520
            return False
521
522
        if not self.is_active():
523
            log.debug(f'{self} will be deployed.')
524
            return True
525
526
        return False
527
528 2
    def deploy_to_path(self, path=None):
529 2
        """Install the flows for this circuit.
530 2
531 2
        Procedures to deploy:
532 2
533
        0. Remove current flows installed
534 2
        1. Decide if will deploy "path" or discover a new path
535 2
        2. Choose vlan
536 2
        3. Install NNI flows
537 2
        4. Install UNI flows
538 2
        5. Activate
539 2
        6. Update current_path
540 2
        7. Update links caches(primary, current, backup)
541 2
542
        """
543 2
        self.remove_current_flows()
544
        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
        self._install_nni_flows(path)
551 2
        self._install_uni_flows(path)
552
        self.activate()
553
        self.current_path = path
554
        self.sync()
555
        log.info(f"{self} was deployed.")
556 2
        return True
557
558
    def _install_nni_flows(self, path=None):
559 2
        """Install NNI flows."""
560
        for incoming, outcoming in self.links_zipped(path):
561 2
            in_vlan = incoming.get_metadata('s_vlan').value
562
            out_vlan = outcoming.get_metadata('s_vlan').value
563 2
564
            flows = []
565
            # Flow for one direction
566
            flows.append(self._prepare_nni_flow(incoming.endpoint_b,
567
                                                outcoming.endpoint_a,
568 2
                                                in_vlan, out_vlan))
569 2
570
            # Flow for the other direction
571 2
            flows.append(self._prepare_nni_flow(outcoming.endpoint_a,
572 2
                                                incoming.endpoint_b,
573
                                                out_vlan, in_vlan))
574
            self._send_flow_mods(incoming.endpoint_b.switch, flows)
575 2
576
    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 2
582
        # Determine VLANs
583
        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
        out_vlan_z = path[-1].get_metadata('s_vlan').value
588 2
589
        # Flows for the first UNI
590
        flows_a = []
591 2
592
        # Flow for one direction, pushing the service tag
593
        push_flow = self._prepare_push_flow(self.uni_a.interface,
594 2
                                            path[0].endpoint_a,
595
                                            in_vlan_a, out_vlan_a, in_vlan_z)
596
        flows_a.append(push_flow)
597 2
598
        # Flow for the other direction, popping the service tag
599
        pop_flow = self._prepare_pop_flow(path[0].endpoint_a,
600 2
                                          self.uni_a.interface, out_vlan_a)
601
        flows_a.append(pop_flow)
602 2
603
        self._send_flow_mods(self.uni_a.interface.switch, flows_a)
604 2
605
        # Flows for the second UNI
606 2
        flows_z = []
607 2
608
        # Flow for one direction, pushing the service tag
609
        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
        flows_z.append(push_flow)
613
614
        # Flow for the other direction, popping the service tag
615
        pop_flow = self._prepare_pop_flow(path[-1].endpoint_b,
616 2
                                          self.uni_z.interface, out_vlan_z)
617
        flows_z.append(pop_flow)
618 2
619 2
        self._send_flow_mods(self.uni_z.interface.switch, flows_z)
620
621 2
    @staticmethod
622
    def _send_flow_mods(switch, flow_mods, command='flows'):
623 2
        """Send a flow_mod list to a specific switch.
624 2
625
        Args:
626 2
            switch(Switch): The target of flows.
627
            flow_mods(dict): Python dictionary with flow_mods.
628 2
            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
        data = {"flows": flow_mods}
634
        requests.post(endpoint, json=data)
635 2
636
    def get_cookie(self):
637 2
        """Return the cookie integer from evc id."""
638
        value = self.id[len(self.id)//2:]
639
        return int(value, 16)
640 2
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 2
646
        flow_mod = {"match": {"in_port": in_interface.port_number},
647 2
                    "cookie": self.get_cookie(),
648
                    "actions": [default_action]}
649 2
650
        return flow_mod
651
652
    def _prepare_nni_flow(self,
653
                          in_interface, out_interface, in_vlan, out_vlan):
654
        """Create NNI flows."""
655
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
656
        flow_mod['match']['dl_vlan'] = in_vlan
657
658
        new_action = {"action_type": "set_vlan",
659
                      "vlan_id": out_vlan}
660
        flow_mod["actions"].insert(0, new_action)
661
662
        return flow_mod
663
664 2
    def _prepare_push_flow(self, *args):
665
        """Prepare push flow.
666 2
667 2
        Arguments:
668
            in_interface(str): Interface input.
669 2
            out_interface(str): Interface output.
670
            in_vlan(str): Vlan input.
671 2
            out_vlan(str): Vlan output.
672
            new_in_vlan(str): Interface input.
673 2
674
        Return:
675 2
            dict: An python dictionary representing a FlowMod
676
677 2
        """
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
        flow_mod['match']['dl_vlan'] = in_vlan
683 2
684
        new_action = {"action_type": "set_vlan",
685 2
                      "vlan_id": out_vlan}
686 2
        flow_mod["actions"].insert(0, new_action)
687 2
688 2
        new_action = {"action_type": "push_vlan",
689 2
                      "tag_type": "s"}
690
        flow_mod["actions"].insert(0, new_action)
691
692 2
        new_action = {"action_type": "set_vlan",
693
                      "vlan_id": new_in_vlan}
694
        flow_mod["actions"].insert(0, new_action)
695 2
696
        return flow_mod
697
698
    def _prepare_pop_flow(self, in_interface, out_interface, in_vlan):
699 2
        """Prepare pop flow."""
700
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
701 2
        flow_mod['match']['dl_vlan'] = in_vlan
702
        new_action = {"action_type": "pop_vlan"}
703 2
        flow_mod["actions"].insert(0, new_action)
704
        return flow_mod
705 2
706
707 2
class LinkProtection(EVCDeploy):
708
    """Class to handle link protection."""
709 2
710
    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 2
        """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 2
        """Verify if the current deployed path is dynamic."""
724
        if self.current_path and \
725 2
           not self.is_using_primary_path() and \
726
           not self.is_using_backup_path() and \
727 2
           self.current_path.status is EntityStatus.UP:
728
            return True
729
        return False
730
731
    def deploy_to(self, path_name=None, path=None):
732
        """Create a deploy to path."""
733
        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 2
740
        return False
741 2
742 2
    def handle_link_up(self, link):
743
        """Handle circuit when link down.
744
745
        Args:
746 2
            link(Link): Link affected by link.down event.
747
748
        """
749
        if self.is_using_primary_path():
750
            return True
751 2
752 2
        success = False
753
        if self.primary_path.is_affected_by_link(link):
754 2
            success = self.deploy_to_primary_path()
755 2
756
        if success:
757
            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
        if self.is_using_backup_path() or self.is_using_dynamic_path():
762
            return True
763
764 2
        # In this case, probably the circuit is not being used and
765
        # we can move to backup
766
        if self.backup_path.is_affected_by_link(link):
767
            success = self.deploy_to_backup_path()
768
769
        if success:
770
            return True
771 2
772 2
        # In this case, the circuit is not being used and we should
773 2
        # try a dynamic path
774 2
        if self.dynamic_backup_path:
775 2
            return self.deploy_to_path()
776
777 2
        return True
778 2
779
    def handle_link_down(self):
780 2
        """Handle circuit when link down.
781 2
782
        Returns:
783 2
            bool: True if the re-deploy was successly otherwise False.
784
785 2
        """
786
        success = False
787
        if self.is_using_primary_path():
788 2
            success = self.deploy_to('backup_path', self.backup_path)
789
        elif self.is_using_backup_path():
790
            success = self.deploy_to('primary_path', self.primary_path)
791
792
        if not success and self.dynamic_backup_path:
793
            success = self.deploy_to_path()
794
795
        if success:
796
            log.debug(f"{self} deployed after link down.")
797
        else:
798
            log.debug(f'Failed to re-deploy {self} after link down.')
799
800
        return success
801
802
803
class EVC(LinkProtection):
804
    """Class that represents a E-Line Virtual Connection."""
805