Completed
Pull Request — master (#192)
by Antonio
03:41
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 1
        for link in self:
44 1
            tag = link.get_next_available_tag()
45 1
            link.use_tag(tag)
46 1
            link.add_metadata('s_vlan', tag)
47
48 1
    def make_vlans_available(self):
49
        """Make the VLANs used in a path available when undeployed."""
50 1
        for link in self:
51 1
            link.make_tag_available(link.get_metadata('s_vlan'))
52 1
            link.remove_metadata('s_vlan')
53
54 1
    @property
55
    def status(self):
56
        """Check for the  status of a path.
57
58
        If any link in this path is down, the path is considered down.
59
        """
60 1
        if not self:
61 1
            return EntityStatus.DISABLED
62
63 1
        endpoint = '%s/%s' % (settings.TOPOLOGY_URL, 'links')
64 1
        api_reply = requests.get(endpoint)
65 1
        if api_reply.status_code != getattr(requests.codes, 'ok'):
66
            log.error('Failed to get links at %s. Returned %s',
67
                      endpoint, api_reply.status_code)
68
            return None
69 1
        links = api_reply.json()['links']
70 1
        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 path available for a circuit, if exists."""
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 1
                    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 1
        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 a new path to satisfy this circuit and deploy."""
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 1
        self.disable()
499 1
        self.sync()
500
501 1
    def remove_current_flows(self):
502
        """Remove all flows from current path."""
503 1
        switches = set()
504
505 1
        for link in self.current_path:
506 1
            switches.add(link.endpoint_a.switch)
507 1
            switches.add(link.endpoint_b.switch)
508
509 1
        match = {'cookie': self.get_cookie(),
510
                 'cookie_mask': 18446744073709551615}
511
512 1
        for switch in switches:
513 1
            self._send_flow_mods(switch, [match], 'delete')
514
515 1
        self.current_path.make_vlans_available()
516 1
        self.current_path = Path([])
517 1
        self.deactivate()
518 1
        self.sync()
519
520 1
    @staticmethod
521 1
    def links_zipped(path=None):
522
        """Return an iterator which yields pairs of links in order."""
523 1
        if not path:
524
            return []
525 1
        return zip(path[:-1], path[1:])
526
527 1
    def should_deploy(self, path=None):
528
        """Verify if the circuit should be deployed."""
529 1
        if not path:
530 1
            log.debug("Path is empty.")
531 1
            return False
532
533 1
        if not self.is_enabled():
534 1
            log.debug(f'{self} is disabled.')
535 1
            return False
536
537 1
        if not self.is_active():
538 1
            log.debug(f'{self} will be deployed.')
539 1
            return True
540
541 1
        return False
542
543 1
    def deploy_to_path(self, path=None):
544
        """Install the flows for this circuit.
545
546
        Procedures to deploy:
547
548
        0. Remove current flows installed
549
        1. Decide if will deploy "path" or discover a new path
550
        2. Choose vlan
551
        3. Install NNI flows
552
        4. Install UNI flows
553
        5. Activate
554
        6. Update current_path
555
        7. Update links caches(primary, current, backup)
556
557
        """
558 1
        self.remove_current_flows()
559 1
        use_path = path
560 1
        if self.should_deploy(use_path):
561 1
            try:
562 1
                use_path.choose_vlans()
563
            except KytosNoTagAvailableError:
564
                use_path = None
565
        else:
566 1
            for use_path in self.discover_new_paths():
567 1
                try:
568 1
                    use_path.choose_vlans()
569 1
                    break
570
                except KytosNoTagAvailableError:
571
                    pass
572
            else:
573 1
                use_path = None
574
575 1
        if use_path:
576 1
            self._install_nni_flows(use_path)
577 1
            self._install_uni_flows(use_path)
578 1
            self.activate()
579 1
            self.current_path = use_path
580 1
            self.sync()
581 1
            log.info(f"{self} was deployed.")
582 1
            return True
583 1
        return False
584
585 1
    def _install_nni_flows(self, path=None):
586
        """Install NNI flows."""
587 1
        for incoming, outcoming in self.links_zipped(path):
588 1
            in_vlan = incoming.get_metadata('s_vlan').value
589 1
            out_vlan = outcoming.get_metadata('s_vlan').value
590
591 1
            flows = []
592
            # Flow for one direction
593 1
            flows.append(self._prepare_nni_flow(incoming.endpoint_b,
594
                                                outcoming.endpoint_a,
595
                                                in_vlan, out_vlan))
596
597
            # Flow for the other direction
598 1
            flows.append(self._prepare_nni_flow(outcoming.endpoint_a,
599
                                                incoming.endpoint_b,
600
                                                out_vlan, in_vlan))
601 1
            self._send_flow_mods(incoming.endpoint_b.switch, flows)
602
603 1
    def _install_uni_flows(self, path=None):
604
        """Install UNI flows."""
605 1
        if not path:
606
            log.info('install uni flows without path.')
607
            return
608
609
        # Determine VLANs
610 1
        in_vlan_a = self.uni_a.user_tag.value if self.uni_a.user_tag else None
611 1
        out_vlan_a = path[0].get_metadata('s_vlan').value
612
613 1
        in_vlan_z = self.uni_z.user_tag.value if self.uni_z.user_tag else None
614 1
        out_vlan_z = path[-1].get_metadata('s_vlan').value
615
616
        # Flows for the first UNI
617 1
        flows_a = []
618
619
        # Flow for one direction, pushing the service tag
620 1
        push_flow = self._prepare_push_flow(self.uni_a.interface,
621
                                            path[0].endpoint_a,
622
                                            in_vlan_a, out_vlan_a, in_vlan_z)
623 1
        flows_a.append(push_flow)
624
625
        # Flow for the other direction, popping the service tag
626 1
        pop_flow = self._prepare_pop_flow(path[0].endpoint_a,
627
                                          self.uni_a.interface, out_vlan_a)
628 1
        flows_a.append(pop_flow)
629
630 1
        self._send_flow_mods(self.uni_a.interface.switch, flows_a)
631
632
        # Flows for the second UNI
633 1
        flows_z = []
634
635
        # Flow for one direction, pushing the service tag
636 1
        push_flow = self._prepare_push_flow(self.uni_z.interface,
637
                                            path[-1].endpoint_b,
638
                                            in_vlan_z, out_vlan_z, in_vlan_a)
639 1
        flows_z.append(push_flow)
640
641
        # Flow for the other direction, popping the service tag
642 1
        pop_flow = self._prepare_pop_flow(path[-1].endpoint_b,
643
                                          self.uni_z.interface, out_vlan_z)
644 1
        flows_z.append(pop_flow)
645
646 1
        self._send_flow_mods(self.uni_z.interface.switch, flows_z)
647
648 1
    @staticmethod
649 1
    def _send_flow_mods(switch, flow_mods, command='flows'):
650
        """Send a flow_mod list to a specific switch.
651
652
        Args:
653
            switch(Switch): The target of flows.
654
            flow_mods(dict): Python dictionary with flow_mods.
655
            command(str): By default is 'flows'. To remove a flow is 'remove'.
656
657
        """
658 1
        endpoint = f'{settings.MANAGER_URL}/{command}/{switch.id}'
659
660 1
        data = {"flows": flow_mods}
661 1
        requests.post(endpoint, json=data)
662
663 1
    def get_cookie(self):
664
        """Return the cookie integer from evc id."""
665 1
        value = self.id[len(self.id)//2:]
666 1
        return int(value, 16)
667
668 1
    def _prepare_flow_mod(self, in_interface, out_interface):
669
        """Prepare a common flow mod."""
670 1
        default_action = {"action_type": "output",
671
                          "port": out_interface.port_number}
672
673 1
        flow_mod = {"match": {"in_port": in_interface.port_number},
674
                    "cookie": self.get_cookie(),
675
                    "actions": [default_action]}
676
677 1
        return flow_mod
678
679 1
    def _prepare_nni_flow(self,
680
                          in_interface, out_interface, in_vlan, out_vlan):
681
        """Create NNI flows."""
682 1
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
683 1
        flow_mod['match']['dl_vlan'] = in_vlan
684
685 1
        new_action = {"action_type": "set_vlan",
686
                      "vlan_id": out_vlan}
687 1
        flow_mod["actions"].insert(0, new_action)
688
689 1
        return flow_mod
690
691 1
    def _prepare_push_flow(self, *args):
692
        """Prepare push flow.
693
694
        Arguments:
695
            in_interface(str): Interface input.
696
            out_interface(str): Interface output.
697
            in_vlan(str): Vlan input.
698
            out_vlan(str): Vlan output.
699
            new_in_vlan(str): Interface input.
700
701
        Return:
702
            dict: An python dictionary representing a FlowMod
703
704
        """
705
        # assign all arguments
706 1
        in_interface, out_interface, in_vlan, out_vlan, new_in_vlan = args
707
708 1
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
709 1
        flow_mod['match']['dl_vlan'] = in_vlan
710
711 1
        new_action = {"action_type": "set_vlan",
712
                      "vlan_id": out_vlan}
713 1
        flow_mod["actions"].insert(0, new_action)
714
715 1
        new_action = {"action_type": "push_vlan",
716
                      "tag_type": "s"}
717 1
        flow_mod["actions"].insert(0, new_action)
718
719 1
        new_action = {"action_type": "set_vlan",
720
                      "vlan_id": new_in_vlan}
721 1
        flow_mod["actions"].insert(0, new_action)
722
723 1
        return flow_mod
724
725 1
    def _prepare_pop_flow(self, in_interface, out_interface, in_vlan):
726
        """Prepare pop flow."""
727 1
        flow_mod = self._prepare_flow_mod(in_interface, out_interface)
728 1
        flow_mod['match']['dl_vlan'] = in_vlan
729 1
        new_action = {"action_type": "pop_vlan"}
730 1
        flow_mod["actions"].insert(0, new_action)
731 1
        return flow_mod
732
733
734 1
class LinkProtection(EVCDeploy):
735
    """Class to handle link protection."""
736
737 1
    def is_affected_by_link(self, link=None):
738
        """Verify if the current path is affected by link down event."""
739
        return self.current_path.is_affected_by_link(link)
740
741 1
    def is_using_primary_path(self):
742
        """Verify if the current deployed path is self.primary_path."""
743 1
        return self.current_path == self.primary_path
744
745 1
    def is_using_backup_path(self):
746
        """Verify if the current deployed path is self.backup_path."""
747 1
        return self.current_path == self.backup_path
748
749 1
    def is_using_dynamic_path(self):
750
        """Verify if the current deployed path is dynamic."""
751 1
        if self.current_path and \
752
           not self.is_using_primary_path() and \
753
           not self.is_using_backup_path() and \
754
           self.current_path.status is EntityStatus.UP:
755
            return True
756 1
        return False
757
758 1
    def deploy_to(self, path_name=None, path=None):
759
        """Create a deploy to path."""
760 1
        if self.current_path == path:
761 1
            log.debug(f'{path_name} is equal to current_path.')
762 1
            return True
763
764 1
        if path.status is EntityStatus.UP:
765 1
            return self.deploy_to_path(path)
766
767 1
        return False
768
769 1
    def handle_link_up(self, link):
770
        """Handle circuit when link down.
771
772
        Args:
773
            link(Link): Link affected by link.down event.
774
775
        """
776 1
        if self.is_using_primary_path():
777 1
            return True
778
779 1
        success = False
780 1
        if self.primary_path.is_affected_by_link(link):
781 1
            success = self.deploy_to_primary_path()
782
783 1
        if success:
784 1
            return True
785
786
        # We tried to deploy(primary_path) without success.
787
        # And in this case is up by some how. Nothing to do.
788 1
        if self.is_using_backup_path() or self.is_using_dynamic_path():
789
            return True
790
791
        # In this case, probably the circuit is not being used and
792
        # we can move to backup
793 1
        if self.backup_path.is_affected_by_link(link):
794 1
            success = self.deploy_to_backup_path()
795
796 1
        if success:
797 1
            return True
798
799
        # In this case, the circuit is not being used and we should
800
        # try a dynamic path
801
        if self.dynamic_backup_path:
802
            return self.deploy_to_path()
803
804
        return True
805
806 1
    def handle_link_down(self):
807
        """Handle circuit when link down.
808
809
        Returns:
810
            bool: True if the re-deploy was successly otherwise False.
811
812
        """
813 1
        success = False
814 1
        if self.is_using_primary_path():
815 1
            success = self.deploy_to_backup_path()
816 1
        elif self.is_using_backup_path():
817 1
            success = self.deploy_to_primary_path()
818
819 1
        if not success and self.dynamic_backup_path:
820 1
            success = self.deploy_to_path()
821
822 1
        if success:
823 1
            log.debug(f"{self} deployed after link down.")
824
        else:
825 1
            self.deactivate()
826 1
            self.current_path = Path([])
827 1
            self.sync()
828 1
            log.debug(f'Failed to re-deploy {self} after link down.')
829
830 1
        return success
831
832
833 1
class EVC(LinkProtection):
834
    """Class that represents a E-Line Virtual Connection."""
835