Passed
Pull Request — master (#371)
by Vinicius
14:40 queued 10:44
created

DynamicPathManager.get_disjoint_paths()   C

Complexity

Conditions 9

Size

Total Lines 65
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 9

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 65
ccs 20
cts 20
cp 1
rs 6.6666
c 0
b 0
f 0
cc 9
nop 4
crap 9

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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