Passed
Pull Request — master (#188)
by Antonio
02:35
created

build.models.EVCBase.update()   C

Complexity

Conditions 9

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 13.4798

Importance

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