Passed
Pull Request — master (#192)
by Antonio
02:24
created

build.models.DynamicPathManager.get_best_paths()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 3.1852

Importance

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