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