Test Failed
Push — master ( e67027...40cb77 )
by Antonio
03:50
created

build.models.EVCDeploy.deploy_to_path()   C

Complexity

Conditions 9

Size

Total Lines 48
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9.0608

Importance

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