Test Failed
Pull Request — master (#58)
by
unknown
02:13
created

KytosGraph.constrained_flexible_paths()   B

Complexity

Conditions 6

Size

Total Lines 30
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 25
nop 5
dl 0
loc 30
rs 8.3466
c 0
b 0
f 0
ccs 0
cts 0
cp 0
crap 42
1
"""Module Graph of kytos/pathfinder Kytos Network Application."""
2
3 1
from itertools import combinations
4
5 1
from kytos.core import log
6 1
7 1
try:
8
    import networkx as nx
9
    from networkx.exception import NodeNotFound, NetworkXNoPath
10
except ImportError:
11
    PACKAGE = 'networkx>=2.2'
12
    log.error(f"Package {PACKAGE} not found. Please 'pip install {PACKAGE}'")
13 1
14
15
class Filter:
16 1
    """Class responsible for removing items with disqualifying values."""
17 1
18
    def __init__(self, filter_type, filter_function):
19 1
        self._filter_type = filter_type
20
        self._filter_function = filter_function
21 1
22
    def run(self, value, items):
23 1
        """Filter out items. Filter chosen is picked at runtime."""
24
        if isinstance(value, self._filter_type):
25 1
            return filter(self._filter_function(value), items)
26 1
27 1
        raise TypeError(f"Expected type: {self._filter_type}")
28
29 1
30
class KytosGraph:
31 1
    """Class responsible for the graph generation."""
32 1
33 1
    def __init__(self):
34
        self.graph = nx.Graph()
35 1
        self._filter_functions = {}
36 1
37 1
        def filter_leq(metric):  # Lower values are better
38
            return lambda x: (lambda y: y[2].get(metric, x) <= x)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable x does not seem to be defined.
Loading history...
39
40
        def filter_geq(metric):  # Higher values are better
41
            return lambda x: (lambda y: y[2].get(metric, x) >= x)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable x does not seem to be defined.
Loading history...
42 1
43
        def filter_eeq(metric):  # Equivalence
44 1
            return lambda x: (lambda y: y[2].get(metric, x) == x)
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable x does not seem to be defined.
Loading history...
45 1
46 1
        self._filter_functions["ownership"] = Filter(
47 1
            str, filter_eeq("ownership"))
48 1
        self._filter_functions["bandwidth"] = Filter(
49 1
            (int, float), filter_geq("bandwidth"))
50 1
        self._filter_functions["priority"] = Filter(
51 1
            (int, float), filter_geq("priority"))
52 1
        self._filter_functions["reliability"] = Filter(
53
            (int, float), filter_geq("reliability"))
54 1
        self._filter_functions["utilization"] = Filter(
55
            (int, float), filter_leq("utilization"))
56 1
        self._filter_functions["delay"] = Filter(
57
            (int, float), filter_leq("delay"))
58
        self._path_function = nx.all_shortest_paths
59
60
    def clear(self):
61
        """Remove all nodes and links registered."""
62 1
        self.graph.clear()
63 1
64 1
    def update_topology(self, topology):
65 1
        """Update all nodes and links inside the graph."""
66
        self.graph.clear()
67 1
        self.update_nodes(topology.switches)
68
        self.update_links(topology.links)
69
70 1
    def update_nodes(self, nodes):
71 1
        """Update all nodes inside the graph."""
72 1
        for node in nodes.values():
73
            try:
74 1
                self.graph.add_node(node.id)
75
76 1
                for interface in node.interfaces.values():
77 1
                    self.graph.add_node(interface.id)
78
                    self.graph.add_edge(node.id, interface.id)
79
80
            except AttributeError:
81
                pass
82 1
83
    def update_links(self, links):
84
        """Update all links inside the graph."""
85
        keys = []
86
        for link in links.values():
87
            if link.is_active():
88
                self.graph.add_edge(link.endpoint_a.id, link.endpoint_b.id)
89
                for key, value in link.metadata.items():
90
                    keys.append(key)
91
                    endpoint_a = link.endpoint_a.id
92
                    endpoint_b = link.endpoint_b.id
93
                    self.graph[endpoint_a][endpoint_b][key] = value
94
95
    def get_metadata_from_link(self, endpoint_a, endpoint_b):
96
        """Return the metadata of a link."""
97
        return self.graph.edges[endpoint_a, endpoint_b]
98
99
    @staticmethod
100
    def _remove_switch_hops(circuit):
101
        """Remove switch hops from a circuit hops list."""
102
        for hop in circuit['hops']:
103
            if len(hop.split(':')) == 8:
104
                circuit['hops'].remove(hop)
105
106
    def shortest_paths(self, source, destination, parameter=None):
107
        """Calculate the shortest paths and return them."""
108
        try:
109
            paths = list(self._path_function(self.graph,
110
                                             source, destination, parameter))
111
        except (NodeNotFound, NetworkXNoPath):
112
            return []
113
        return paths
114
115
    def constrained_flexible_paths(self, source, destination,
116
                                   maximum_misses=None, **metrics):
117
        """Calculate the constrained shortest paths with flexibility."""
118
        base = metrics.get("base", {})
119
        flexible = metrics.get("flexible", {})
120
        # Retrieve subgraph with edges that meet base requirements.
121
        default_edge_list = list(self._filter_edges(
122
            self.graph.edges(data=True), **base))
123
        length = len(flexible)
124
        if maximum_misses is None:
125
            maximum_misses = length
126
        maximum_misses = min(length, max(0, maximum_misses))
127
        results = []
128
        paths = []
129
        i = 0
130
        # Create "sub-subgraphs" from original subgraph by trimming edges
131
        # that miss flexible requirement combinations. Search for a shortest
132
        # path in each of these graphs, until at least one is found.
133
        while (paths == [] and i in range(0, maximum_misses+1)):
134
            for combo in combinations(flexible.items(), length-i):
135
                additional = dict(combo)
136
                paths = self._constrained_shortest_paths(
137
                    source, destination, ((u, v) for u, v, d in
0 ignored issues
show
introduced by
The variable u does not seem to be defined for all execution paths.
Loading history...
introduced by
The variable v does not seem to be defined for all execution paths.
Loading history...
138
                                          self._filter_edges(default_edge_list,
139
                                                             **additional)))
140
                if paths != []:
141
                    results.append(
142
                        {"paths": paths, "metrics": {**base, **additional}})
143
            i = i + 1
144
        return results
145
146
    def _constrained_shortest_paths(self, source, destination, edges):
147
        paths = []
148
        try:
149
            paths = list(self._path_function(self.graph.edge_subgraph(edges),
150
                                             source, destination))
151
        except NetworkXNoPath:
152
            pass
153
        except NodeNotFound:
154
            if source == destination:
155
                if source in self.graph.nodes:
156
                    paths = [[source]]
157
        return paths
158
159
    def _filter_edges(self, edges, **metrics):
160
        for metric, value in metrics.items():
161
            filter_ = self._filter_functions.get(metric, None)
162
            if filter_ is not None:
163
                try:
164
                    edges = filter_.run(value, edges)
165
                except TypeError as err:
166
                    raise TypeError(f"Error in {metric} filter: {err}")
167
        return edges
168