Test Failed
Push — master ( 09ad2e...701a71 )
by Antonio
04:22 queued 11s
created

build.models.DynamicPathManager.get_best_path()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3.6875

Importance

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