Completed
Pull Request — master (#58)
by
unknown
02:17
created

KytosGraph.constrained_flexible_paths()   B

Complexity

Conditions 6

Size

Total Lines 30
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 19
CRAP Score 6

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