Test Failed
Pull Request — master (#187)
by Antonio
02:26
created

build.models.EVCDeploy._install_direct_uni_flows()   B

Complexity

Conditions 7

Size

Total Lines 27
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 7.2269

Importance

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