Passed
Pull Request — master (#180)
by Antonio
02:26
created

build.models.Path.status()   B

Complexity

Conditions 7

Size

Total Lines 27
Code Lines 22

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7.392

Importance

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