build.models.EVCDeploy._install_direct_uni_flows()   B
last analyzed

Complexity

Conditions 7

Size

Total Lines 35
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 48.6673

Importance

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