Passed
Push — master ( edc14b...5b6648 )
by Vinicius
03:38 queued 14s
created

DynamicPathManager.set_controller()   A

Complexity

Conditions 1

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
"""Classes related to paths"""
2 1
import requests
3
4 1
from kytos.core import log
5 1
from kytos.core.common import EntityStatus, GenericEntity
6 1
from kytos.core.link import Link
7 1
from napps.kytos.mef_eline import settings
8 1
from napps.kytos.mef_eline.exceptions import InvalidPath
9
10
11 1
class Path(list, GenericEntity):
12
    """Class to represent a Path."""
13
14 1
    def __eq__(self, other=None):
15
        """Compare paths."""
16 1
        if not other or not isinstance(other, Path):
17 1
            return False
18 1
        return super().__eq__(other)
19
20 1
    def is_affected_by_link(self, link=None):
21
        """Verify if the current path is affected by link."""
22 1
        if not link:
23 1
            return False
24 1
        return link in self
25
26 1
    def link_affected_by_interface(self, interface=None):
27
        """Return the link using this interface, if any, or None otherwise."""
28 1
        if not interface:
29 1
            return None
30 1
        for link in self:
31 1
            if interface in (link.endpoint_a, link.endpoint_b):
32 1
                return link
33
        return None
34
35 1
    def choose_vlans(self):
36
        """Choose the VLANs to be used for the circuit."""
37 1
        for link in self:
38 1
            tag = link.get_next_available_tag()
39 1
            link.add_metadata("s_vlan", tag)
40
41 1
    def make_vlans_available(self):
42
        """Make the VLANs used in a path available when undeployed."""
43 1
        for link in self:
44 1
            link.make_tag_available(link.get_metadata("s_vlan"))
45 1
            link.remove_metadata("s_vlan")
46
47 1
    def is_valid(self, switch_a, switch_z, is_scheduled=False):
48
        """Check if this is a valid path."""
49 1
        if not self:
50 1
            return True
51 1
        previous = visited = {switch_a}
52 1
        for link in self:
53 1
            current = {link.endpoint_a.switch, link.endpoint_b.switch} \
54
                      - previous
55 1
            if len(current) != 1:
56 1
                raise InvalidPath(
57
                    f"Previous switch {previous} is not connected to "
58
                    f"current link with switches {current}."
59
                )
60 1
            if current & visited:
61 1
                raise InvalidPath(
62
                    f"Loop detected in path, switch {current} was visited"
63
                    f" more than once."
64
                )
65 1
            if is_scheduled is False and (
66
                link.endpoint_a.link is None
67
                or link.endpoint_a.link != link
68
                or link.endpoint_b.link is None
69
                or link.endpoint_b.link != link
70
            ):
71
                raise InvalidPath(f"Link {link} is not available.")
72 1
            previous = current
73 1
            visited |= current
74 1
        if previous & {switch_z}:
75 1
            return True
76
        raise InvalidPath("Last link does not contain uni_z switch")
77
78 1
    @property
79 1
    def status(self):
80
        """Check for the  status of a path.
81
82
        If any link in this path is down, the path is considered down.
83
        """
84 1
        if not self:
85 1
            return EntityStatus.DISABLED
86
87 1
        endpoint = f"{settings.TOPOLOGY_URL}/links"
88 1
        api_reply = requests.get(endpoint)
89 1
        if api_reply.status_code != getattr(requests.codes, "ok"):
90
            log.error(
91
                "Failed to get links at %s. Returned %s",
92
                endpoint,
93
                api_reply.status_code,
94
            )
95
            return None
96 1
        links = api_reply.json()["links"]
97 1
        return_status = EntityStatus.UP
98 1
        for path_link in self:
99 1
            try:
100 1
                link = links[path_link.id]
101
            except KeyError:
102
                return EntityStatus.DISABLED
103 1
            if link["enabled"] is False:
104 1
                return EntityStatus.DISABLED
105 1
            if link["active"] is False:
106 1
                return_status = EntityStatus.DOWN
107 1
        return return_status
108
109 1
    def as_dict(self):
110
        """Return list comprehension of links as_dict."""
111 1
        return [link.as_dict() for link in self if link]
112
113
114 1
class DynamicPathManager:
115
    """Class to handle and create paths."""
116
117 1
    controller = None
118
119 1
    @classmethod
120 1
    def set_controller(cls, controller=None):
121
        """Set the controller to discovery news paths."""
122 1
        cls.controller = controller
123
124 1
    @staticmethod
125 1
    def get_paths(circuit, max_paths=2, **kwargs):
126
        """Get a valid path for the circuit from the Pathfinder."""
127 1
        endpoint = settings.PATHFINDER_URL
128 1
        spf_attribute = kwargs.get("spf_attribute") or settings.SPF_ATTRIBUTE
129 1
        request_data = {
130
            "source": circuit.uni_a.interface.id,
131
            "destination": circuit.uni_z.interface.id,
132
            "spf_max_paths": max_paths,
133
            "spf_attribute": spf_attribute
134
        }
135 1
        request_data.update(kwargs)
136 1
        api_reply = requests.post(endpoint, json=request_data)
137
138 1
        if api_reply.status_code != getattr(requests.codes, "ok"):
139 1
            log.error(
140
                "Failed to get paths at %s. Returned %s",
141
                endpoint,
142
                api_reply.text,
143
            )
144 1
            return None
145 1
        reply_data = api_reply.json()
146 1
        return reply_data.get("paths")
147
148 1
    @staticmethod
149 1
    def _clear_path(path):
150
        """Remove switches from a path, returning only interfaces."""
151 1
        return [endpoint for endpoint in path if len(endpoint) > 23]
152
153 1
    @classmethod
154 1
    def get_best_path(cls, circuit):
155
        """Return the best path available for a circuit, if exists."""
156 1
        paths = cls.get_paths(circuit)
157 1
        if paths:
158 1
            return cls.create_path(cls.get_paths(circuit)[0]["hops"])
159 1
        return None
160
161 1
    @classmethod
162 1
    def get_best_paths(cls, circuit, **kwargs):
163
        """Return the best paths available for a circuit, if they exist."""
164 1
        for path in cls.get_paths(circuit, **kwargs):
165 1
            yield cls.create_path(path["hops"])
166
167 1
    @classmethod
168 1
    def get_disjoint_paths(
169
        cls, circuit, unwanted_path, cutoff=settings.DISJOINT_PATH_CUTOFF
170
    ):
171
        """Computes the maximum disjoint paths from the unwanted_path for a EVC
172
173
        Maximum disjoint paths from the unwanted_path are the paths from the
174
        source node to the target node that share the minimum number os links
175
        contained in unwanted_path. In other words, unwanted_path is the path
176
        we want to avoid: we want the maximum possible disjoint path from it.
177
        The disjointness of a path in regards to unwanted_path is calculated
178
        by the complementary percentage of shared links between them. As an
179
        example, if the unwanted_path has 3 links, a given path P1 has 1 link
180
        shared with unwanted_path, and a given path P2 has 2 links shared with
181
        unwanted_path, then the disjointness of P1 is 0.67 and the disjointness
182
        of P2 is 0.33. In this example, P1 is preferable over P2 because it
183
        offers a better disjoint path. When two paths have the same
184
        disjointness they are ordered by 'cost' attributed as returned from
185
        Pathfinder. When the disjointness of a path is equal to 0 (i.e., it
186
        shares all the links with unwanted_path), that particular path is not
187
        considered a candidate.
188
189
        Parameters:
190
        -----------
191
192
        circuit : EVC
193
            The EVC providing source node (uni_a) and target node (uni_z)
194
195
        unwanted_path : Path
196
            The Path which we want to avoid.
197
198
        cutoff: int
199
            Maximum number of paths to consider when calculating the disjoint
200
            paths (number of paths to request from pathfinder)
201
202
        Returns:
203
        --------
204
        paths : generator
205
            Generator of unwanted_path disjoint paths. If unwanted_path is
206
            not provided or empty, we return an empty list.
207
        """
208 1
        unwanted_links = [
209
            (link.endpoint_a.id, link.endpoint_b.id) for link in unwanted_path
210
        ]
211 1
        if not unwanted_links:
212 1
            return None
213
214 1
        paths = cls.get_paths(circuit, max_paths=cutoff,
215
                              **circuit.secondary_constraints)
216 1
        for path in paths:
217 1
            head = path["hops"][:-1]
218 1
            tail = path["hops"][1:]
219 1
            shared_edges = 0
220 1
            for (endpoint_a, endpoint_b) in unwanted_links:
221 1
                if ((endpoint_a, endpoint_b) in zip(head, tail)) or (
222
                    (endpoint_b, endpoint_a) in zip(head, tail)
223
                ):
224 1
                    shared_edges += 1
225 1
            path["disjointness"] = 1 - shared_edges / len(unwanted_links)
226 1
        paths = sorted(paths, key=lambda x: (-x['disjointness'], x['cost']))
227 1
        for path in paths:
228 1
            if path["disjointness"] == 0:
229 1
                continue
230 1
            yield cls.create_path(path["hops"])
231 1
        return None
232
233 1
    @classmethod
234 1
    def create_path(cls, path):
235
        """Return the path containing only the interfaces."""
236 1
        new_path = Path()
237 1
        clean_path = cls._clear_path(path)
238
239 1
        if len(clean_path) % 2:
240 1
            return None
241
242 1
        for link in zip(clean_path[1:-1:2], clean_path[2::2]):
243 1
            interface_a = cls.controller.get_interface_by_id(link[0])
244 1
            interface_b = cls.controller.get_interface_by_id(link[1])
245 1
            if interface_a is None or interface_b is None:
246 1
                return None
247 1
            new_path.append(Link(interface_a, interface_b))
248
249
        return new_path
250