Test Failed
Pull Request — master (#220)
by Antonio
01:52
created

build.models   F

Complexity

Total Complexity 164

Size/Duplication

Total Lines 905
Duplicated Lines 0 %

Test Coverage

Coverage 79.22%

Importance

Changes 0
Metric Value
eloc 512
dl 0
loc 905
ccs 366
cts 462
cp 0.7922
rs 2
c 0
b 0
f 0
wmc 164

59 Methods

Rating   Name   Duplication   Size   Complexity  
A Path.__eq__() 0 5 3
A Path.link_affected_by_interface() 0 8 4
A Path.make_vlans_available() 0 5 2
A Path.is_affected_by_link() 0 5 2
A Path.choose_vlans() 0 6 2
A EVCBase.sync() 0 4 1
A DynamicPathManager.get_best_path() 0 7 2
A EVCBase.__eq__() 0 10 4
A EVCBase.__init__() 0 86 3
B Path.status() 0 27 7
A DynamicPathManager.get_best_paths() 0 5 2
A DynamicPathManager.get_paths() 0 14 2
A Path.as_dict() 0 3 1
B EVCBase._validate() 0 24 6
A DynamicPathManager.set_controller() 0 4 1
A EVCBase.__repr__() 0 3 1
A DynamicPathManager.create_path() 0 17 5
A DynamicPathManager._clear_path() 0 4 1
C EVCBase.update() 0 37 9
B EVCDeploy._prepare_push_flow() 0 44 5
A EVCDeploy.remove_current_flows() 0 20 3
A EVCDeploy._prepare_nni_flow() 0 11 1
A EVCDeploy.discover_new_paths() 0 3 1
A EVCDeploy.change_path() 0 2 1
A LinkProtection.deploy_to() 0 10 3
A LinkProtection.is_using_dynamic_path() 0 8 5
A LinkProtection.is_using_primary_path() 0 3 1
A EVCDeploy.remove() 0 5 1
A LinkProtection.is_affected_by_link() 0 3 1
A EVCDeploy.is_primary_path_affected_by_link() 0 3 1
A EVCDeploy._install_uni_flows() 0 44 4
A EVCBase.id() 0 4 1
A EVCDeploy.is_backup_path_affected_by_link() 0 3 1
A EVCDeploy.link_affected_by_interface() 0 3 1
A EVCDeploy.should_deploy() 0 15 4
A EVCDeploy.create() 0 2 1
A EVCDeploy.is_using_backup_path() 0 3 1
A EVCDeploy.deploy() 0 14 3
A EVCDeploy.reprovision() 0 2 1
A EVCBase.archive() 0 3 1
B EVCDeploy._install_direct_uni_flows() 0 33 7
A EVCDeploy.deploy_to_backup_path() 0 25 5
B EVCDeploy.deploy_to_path() 0 45 8
A EVCDeploy._prepare_flow_mod() 0 10 1
A EVCDeploy.get_path_status() 0 13 4
A EVCDeploy.is_using_dynamic_path() 0 8 5
A EVCDeploy.deploy_to_primary_path() 0 14 3
A EVCDeploy._send_flow_mods() 0 14 1
C LinkProtection.handle_link_up() 0 36 9
A EVCDeploy.is_using_primary_path() 0 3 1
A EVCDeploy.get_cookie() 0 3 1
A EVCDeploy.is_affected_by_link() 0 3 1
B LinkProtection.handle_link_down() 0 25 6
A EVCDeploy._prepare_pop_flow() 0 7 1
A EVCDeploy.links_zipped() 0 6 2
A LinkProtection.is_using_backup_path() 0 3 1
A EVCBase.share_uni() 0 6 3
A EVCDeploy._install_nni_flows() 0 17 2
A EVCBase.as_dict() 0 48 4

How to fix   Complexity   

Complexity

Complex classes like build.models often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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