kytos /
pathfinder
| 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_function = 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_function(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_functions = {} |
|
| 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
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
|
|||
| 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
|
|||
| 45 | |||
| 46 | 1 | self._filter_functions["ownership"] = Filter( |
|
| 47 | str, filter_eeq("ownership")) |
||
| 48 | 1 | self._filter_functions["bandwidth"] = Filter( |
|
| 49 | (int, float), filter_geq("bandwidth")) |
||
| 50 | 1 | self._filter_functions["priority"] = Filter( |
|
| 51 | (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 | 1 | self._path_function = nx.all_shortest_paths |
|
| 59 | |||
| 60 | 1 | def clear(self): |
|
| 61 | """Remove all nodes and links registered.""" |
||
| 62 | 1 | self.graph.clear() |
|
| 63 | |||
| 64 | 1 | def update_topology(self, topology): |
|
| 65 | """Update all nodes and links inside the graph.""" |
||
| 66 | 1 | self.graph.clear() |
|
| 67 | 1 | self.update_nodes(topology.switches) |
|
| 68 | 1 | self.update_links(topology.links) |
|
| 69 | |||
| 70 | 1 | def update_nodes(self, nodes): |
|
| 71 | """Update all nodes inside the graph.""" |
||
| 72 | 1 | for node in nodes.values(): |
|
| 73 | 1 | 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 | 1 | self.graph.add_edge(node.id, interface.id) |
|
| 79 | |||
| 80 | except AttributeError: |
||
| 81 | pass |
||
| 82 | |||
| 83 | 1 | def update_links(self, links): |
|
| 84 | """Update all links inside the graph.""" |
||
| 85 | 1 | keys = [] |
|
| 86 | 1 | for link in links.values(): |
|
| 87 | 1 | if link.is_active(): |
|
| 88 | 1 | self.graph.add_edge(link.endpoint_a.id, link.endpoint_b.id) |
|
| 89 | 1 | for key, value in link.metadata.items(): |
|
| 90 | 1 | keys.append(key) |
|
| 91 | 1 | endpoint_a = link.endpoint_a.id |
|
| 92 | 1 | endpoint_b = link.endpoint_b.id |
|
| 93 | 1 | self.graph[endpoint_a][endpoint_b][key] = value |
|
| 94 | |||
| 95 | 1 | def get_metadata_from_link(self, endpoint_a, endpoint_b): |
|
| 96 | """Return the metadata of a link.""" |
||
| 97 | 1 | return self.graph.edges[endpoint_a, endpoint_b] |
|
| 98 | |||
| 99 | 1 | @staticmethod |
|
| 100 | def _remove_switch_hops(circuit): |
||
| 101 | """Remove switch hops from a circuit hops list.""" |
||
| 102 | 1 | for hop in circuit['hops']: |
|
| 103 | 1 | if len(hop.split(':')) == 8: |
|
| 104 | 1 | circuit['hops'].remove(hop) |
|
| 105 | |||
| 106 | 1 | def shortest_paths(self, source, destination, parameter=None): |
|
| 107 | """Calculate the shortest paths and return them.""" |
||
| 108 | 1 | try: |
|
| 109 | 1 | paths = list(self._path_function(self.graph, |
|
| 110 | source, destination, parameter)) |
||
| 111 | except (NodeNotFound, NetworkXNoPath): |
||
| 112 | return [] |
||
| 113 | 1 | return paths |
|
| 114 | |||
| 115 | 1 | def constrained_flexible_paths(self, source, destination, |
|
| 116 | maximum_misses=None, **metrics): |
||
| 117 | """Calculate the constrained shortest paths with flexibility.""" |
||
| 118 | 1 | base = metrics.get("base", {}) |
|
| 119 | 1 | flexible = metrics.get("flexible", {}) |
|
| 120 | # Retrieve subgraph with edges that meet base requirements. |
||
| 121 | 1 | default_edge_list = list(self._filter_edges( |
|
| 122 | self.graph.edges(data=True), **base)) |
||
| 123 | 1 | length = len(flexible) |
|
| 124 | 1 | if maximum_misses is None: |
|
| 125 | 1 | maximum_misses = length |
|
| 126 | 1 | maximum_misses = min(length, max(0, maximum_misses)) |
|
| 127 | 1 | results = [] |
|
| 128 | 1 | paths = [] |
|
| 129 | 1 | 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 | 1 | while (paths == [] and i in range(0, maximum_misses+1)): |
|
| 134 | 1 | for combo in combinations(flexible.items(), length-i): |
|
| 135 | 1 | additional = dict(combo) |
|
| 136 | 1 | paths = self._constrained_shortest_paths( |
|
| 137 | source, destination, ((u, v) for u, v, d in |
||
|
0 ignored issues
–
show
|
|||
| 138 | self._filter_edges(default_edge_list, |
||
| 139 | **additional))) |
||
| 140 | 1 | if paths != []: |
|
| 141 | 1 | results.append( |
|
| 142 | {"paths": paths, "metrics": {**base, **additional}}) |
||
| 143 | 1 | i = i + 1 |
|
| 144 | 1 | return results |
|
| 145 | |||
| 146 | 1 | def _constrained_shortest_paths(self, source, destination, edges): |
|
| 147 | 1 | paths = [] |
|
| 148 | 1 | try: |
|
| 149 | 1 | paths = list(self._path_function(self.graph.edge_subgraph(edges), |
|
| 150 | source, destination)) |
||
| 151 | 1 | except NetworkXNoPath: |
|
| 152 | 1 | pass |
|
| 153 | 1 | except NodeNotFound: |
|
| 154 | 1 | if source == destination: |
|
| 155 | 1 | if source in self.graph.nodes: |
|
| 156 | 1 | paths = [[source]] |
|
| 157 | 1 | return paths |
|
| 158 | |||
| 159 | 1 | def _filter_edges(self, edges, **metrics): |
|
| 160 | 1 | for metric, value in metrics.items(): |
|
| 161 | 1 | filter_ = self._filter_functions.get(metric, None) |
|
| 162 | 1 | if filter_ is not None: |
|
| 163 | 1 | try: |
|
| 164 | 1 | edges = filter_.run(value, edges) |
|
| 165 | 1 | except TypeError as err: |
|
| 166 | 1 | raise TypeError(f"Error in {metric} value: {err}") |
|
| 167 | return edges |
||
| 168 |