Debian Codegraph @

lib/ClusterShell/Topology.py

raw symbols SCIP
1 #
2 # Copyright (C) 2010-2016 CEA/DAM
3 # Copyright (C) 2010-2011 Henri Doreau <[email protected]>
4 # Copyright (C) 2015-2017 Stephane Thiell <[email protected]>
5 #
6 # This file is part of ClusterShell.
7 #
8 # ClusterShell is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU Lesser General Public
10 # License as published by the Free Software Foundation; either
11 # version 2.1 of the License, or (at your option) any later version.
12 #
13 # ClusterShell is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # Lesser General Public License for more details.
17 #
18 # You should have received a copy of the GNU Lesser General Public
19 # License along with ClusterShell; if not, write to the Free Software
20 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21
22 """
23 ClusterShell topology module
24
25 This module contains the network topology parser and its related
26 classes. These classes are used to build a topology tree of nodegroups
27 according to the configuration file.
28
29 This file must be written using the following syntax:
30
31 # for now only [routes] tree is taken in account:
32 [routes]
33 admin: first_level_gateways[0-10]
34 first_level_gateways[0-10]: second_level_gateways[0-100]
35 second_level_gateways[0-100]: nodes[0-2000]
36 ...
37 """
38
39 try:
40 import configparser
41 except ImportError:
42 # Python 2 compat
43 import ConfigParser as configparser
44
45 import logging
46 import warnings
47
48 from ClusterShell.NodeSet import NodeSet
49
50
51 LOGGER = logging.getLogger(__name__)
52
53
54 class TopologyError(Exception):
55 """topology parser error to report invalid configurations or parsing
56 errors
57 """
58
59
60 class TopologyNodeGroup(object):
61 """Base element for in-memory representation of the propagation tree.
62 Contains a nodeset, with parent-children relationships with other
63 instances.
64 """
65 def __init__(self, nodeset=None):
66 """initialize a new TopologyNodeGroup instance."""
67 # Base nodeset
68 self.nodeset = nodeset
69 # Parent TopologyNodeGroup (TNG) instance
70 self.parent = None
71 # List of children TNG instances
72 self._children = []
73 self._children_len = 0
74 # provided for convenience
75 self._children_ns = None
76
77 def printable_subtree(self, prefix=''):
78 """recursive method that returns a printable version the subtree from
79 the current node with a nice presentation
80 """
81 res = ''
82 # For now, it is ok to use a recursive method here as we consider that
83 # tree depth is relatively small.
84 if self.parent is None:
85 # root
86 res = '%s\n' % str(self.nodeset)
87 elif self.parent.parent is None:
88 # first level
89 if not self._is_last():
90 res = '|- %s\n' % str(self.nodeset)
91 else:
92 res = '`- %s\n' % str(self.nodeset)
93 else:
94 # deepest levels...
95 if not self.parent._is_last():
96 prefix += '| '
97 else:
98 # fix last line
99 prefix += ' '
100 if not self._is_last():
101 res = '%s|- %s\n' % (prefix, str(self.nodeset))
102 else:
103 res = '%s`- %s\n' % (prefix, str(self.nodeset))
104 # perform recursive calls to print out every node
105 for child in self._children:
106 res += child.printable_subtree(prefix)
107 return res
108
109 def add_child(self, child):
110 """add a child to the children list and define the current instance as
111 its parent
112 """
113 assert isinstance(child, TopologyNodeGroup)
114 assert len(child.nodeset) > 0, "empty nodeset in child"
115
116 if child in self._children:
117 return
118 child.parent = self
119 self._children.append(child)
120 if self._children_ns is None:
121 self._children_ns = NodeSet()
122 self._children_ns.add(child.nodeset)
123
124 def clear_child(self, child, strict=False):
125 """remove a child"""
126 try:
127 self._children.remove(child)
128 self._children_ns.difference_update(child.nodeset)
129 if len(self._children_ns) == 0:
130 self._children_ns = None
131 except ValueError:
132 if strict:
133 raise
134
135 def clear_children(self):
136 """delete all children"""
137 self._children = []
138 self._children_ns = None
139
140 def children(self):
141 """get the children list"""
142 return self._children
143
144 def children_ns(self):
145 """return the children as a nodeset"""
146 return self._children_ns
147
148 def children_len(self):
149 """returns the number of children as the sum of the size of the
150 children's nodeset
151 """
152 if self._children_ns is None:
153 return 0
154 else:
155 return len(self._children_ns)
156
157 def _is_last(self):
158 """used to display the subtree: we won't prefix the line the same way
159 if the current instance is the last child of the children list of its
160 parent.
161 """
162 return self.parent._children[-1::][0] == self
163
164 def __str__(self):
165 """printable representation of the nodegroup"""
166 return '<TopologyNodeGroup (%s)>' % str(self.nodeset)
167
168
169 class TopologyTree(object):
170 """represent a simplified network topology as a tree of machines to use to
171 connect to other ones
172 """
173 class TreeIterator(object):
174 """efficient tool for tree-traversal"""
175 def __init__(self, tree):
176 """we do simply manage a stack with the remaining nodes"""
177 self._stack = [tree.root]
178
179 def __next__(self): # Python 3
180 """return the next node in the stack or raise a StopIteration
181 exception if the stack is empty
182 """
183 if len(self._stack) > 0 and self._stack[0] is not None:
184 node = self._stack.pop()
185 self._stack += node.children()
186 return node
187 else:
188 raise StopIteration()
189
190 next = __next__ # Python 2
191
192 def __init__(self):
193 """initialize a new TopologyTree instance."""
194 self.root = None
195 self.groups = []
196
197 def load(self, rootnode):
198 """load topology tree"""
199 self.root = rootnode
200
201 stack = [rootnode]
202 while len(stack) > 0:
203 curr = stack.pop()
204 self.groups.append(curr)
205 if curr.children_len() > 0:
206 stack += curr.children()
207
208 def __iter__(self):
209 """provide an iterator on the tree's elements"""
210 return TopologyTree.TreeIterator(self)
211
212 def __str__(self):
213 """printable representation of the tree"""
214 if self.root is None:
215 return '<TopologyTree instance (empty)>'
216 return self.root.printable_subtree()
217
218 def find_nodegroup(self, node):
219 """Find TopologyNodeGroup from given node (helper to find new root)"""
220 for group in self.groups:
221 if node in group.nodeset:
222 return group
223 raise TopologyError('TopologyNodeGroup not found for node %s' % node)
224
225 def inner_node_count(self):
226 """helper to get inner node count (root and gateway nodes)"""
227 return sum(len(group.nodeset) for group in self.groups
228 if group.children_len() > 0)
229
230 def leaf_node_count(self):
231 """helper to get leaf node count"""
232 return sum(len(group.nodeset) for group in self.groups
233 if group.children_len() == 0)
234
235
236 class TopologyRoute(object):
237 """A single route between two nodesets"""
238 def __init__(self, src_ns, dst_ns):
239 """both src_ns and dst_ns are expected to be non-empty NodeSet
240 instances
241 """
242 self.src = src_ns
243 self.dst = dst_ns
244 if len(src_ns & dst_ns) != 0:
245 raise TopologyError(
246 'Source and destination nodesets overlap')
247
248 def dest(self, nodeset=None):
249 """get the route's destination. The optional argument serves for
250 convenience and provides a way to use the method for a subset of the
251 whole source nodeset
252 """
253 if nodeset is None or nodeset in self.src:
254 return self.dst
255 else:
256 return None
257
258 def __str__(self):
259 """printable representation"""
260 return '%s -> %s' % (str(self.src), str(self.dst))
261
262
263 class TopologyRoutingTable(object):
264 """This class provides a convenient way to store and manage topology
265 routes
266 """
267 def __init__(self):
268 """Initialize a new TopologyRoutingTable instance."""
269 self._routes = []
270 self.aggregated_src = NodeSet()
271 self.aggregated_dst = NodeSet()
272
273 def add_route(self, route):
274 """add a new route to the table. The route argument is expected to be a
275 TopologyRoute instance
276 """
277 if self._introduce_circular_reference(route):
278 raise TopologyError(
279 'Loop detected! Cannot add route %s' % str(route))
280 if self._introduce_convergent_paths(route):
281 raise TopologyError(
282 'Convergent path detected! Cannot add route %s' % str(route))
283
284 self._routes.append(route)
285
286 self.aggregated_src.add(route.src)
287 self.aggregated_dst.add(route.dst)
288
289 def connected(self, src_ns):
290 """find out and return the aggregation of directly connected children
291 from src_ns.
292 Argument src_ns is expected to be a NodeSet instance. Result is
293 returned as a NodeSet instance
294 """
295 next_hop = NodeSet.fromlist(dst for dst in [route.dest(src_ns)
296 for route in self._routes]
297 if dst is not None)
298 if len(next_hop) == 0:
299 return None
300 return next_hop
301
302 def __str__(self):
303 """printable representation"""
304 return '\n'.join([str(route) for route in self._routes])
305
306 def __iter__(self):
307 """return an iterator over the list of routes"""
308 return iter(self._routes)
309
310 def _introduce_circular_reference(self, route):
311 """check whether the last added route adds a topology loop or not"""
312 current_ns = route.dst
313 # iterate over the destinations until we find None or we come back on
314 # the src
315 while True:
316 _dest = self.connected(current_ns)
317 if _dest is None or len(_dest) == 0:
318 return False
319 if len(_dest & route.src) != 0:
320 return True
321 current_ns = _dest
322
323 def _introduce_convergent_paths(self, route):
324 """check for undesired convergent paths"""
325 for known_route in self._routes:
326 # source cannot be a superset of an already known destination
327 if route.src > known_route.dst:
328 return True
329 # same thing...
330 if route.dst < known_route.src:
331 return True
332 # two different nodegroups cannot point to the same one
333 if len(route.dst & known_route.dst) != 0 \
334 and route.src != known_route.src:
335 return True
336 return False
337
338
339 class TopologyGraph(object):
340 """represent a complete network topology by storing every "can reach"
341 relations between nodes.
342 """
343 def __init__(self):
344 """initialize a new TopologyGraph instance."""
345 self._routing = TopologyRoutingTable()
346 self._nodegroups = {}
347 self._root = ''
348
349 def add_route(self, src_ns, dst_ns):
350 """add a new route from src nodeset to dst nodeset. The destination
351 nodeset must not overlap with already known destination nodesets
352 (otherwise a TopologyError is raised)
353 """
354 assert isinstance(src_ns, NodeSet)
355 assert isinstance(dst_ns, NodeSet)
356
357 self._routing.add_route(TopologyRoute(src_ns, dst_ns))
358
359 def dest(self, from_nodeset):
360 """return the aggregation of the destinations for a given nodeset"""
361 return self._routing.connected(from_nodeset)
362
363 def to_tree(self, root):
364 """convert the routing table to a topology tree of nodegroups"""
365 # convert the routing table into a table of linked TopologyNodeGroup's
366 self._routes_to_tng()
367 # ensure this is a valid pseudo-tree
368 self._validate(root)
369 tree = TopologyTree()
370 tree.load(self._nodegroups[self._root])
371 return tree
372
373 def __str__(self):
374 """printable representation of the graph"""
375 res = '<TopologyGraph>\n'
376 res += '\n'.join(['%s: %s' % (str(k), str(v))
377 for k, v in self._nodegroups.items()])
378 return res
379
380 def _routes_to_tng(self):
381 """convert the routing table into a graph of TopologyNodeGroup
382 instances. Loops are not very expensive here as the number of routes
383 will always be much lower than the number of nodes.
384 """
385 # instantiate nodegroups as biggest groups of nodes sharing both parent
386 # and destination
387 aggregated_src = self._routing.aggregated_src
388 for route in self._routing:
389 self._nodegroups[str(route.src)] = TopologyNodeGroup(route.src)
390 # create a nodegroup for the destination if it is a leaf group.
391 # Otherwise, it will be created as src for another route
392 leaf = route.dst - aggregated_src
393 if len(leaf) > 0:
394 self._nodegroups[str(leaf)] = TopologyNodeGroup(leaf)
395
396 # add the parent <--> children relationships
397 for group in self._nodegroups.values():
398 dst_ns = self._routing.connected(group.nodeset)
399 if dst_ns is not None:
400 for child in self._nodegroups.values():
401 if child.nodeset in dst_ns:
402 group.add_child(child)
403
404 def _validate(self, root):
405 """ensure that the graph is valid for conversion to tree"""
406 if len(self._nodegroups) == 0:
407 raise TopologyError("No route found in topology definition!")
408
409 # ensure that every node is reachable
410 src_all = self._routing.aggregated_src
411 dst_all = self._routing.aggregated_dst
412
413 res = [(k, v) for k, v in self._nodegroups.items() if root in v.nodeset]
414 if len(res) > 0:
415 kgroup, group = res[0]
416 del self._nodegroups[kgroup]
417 self._nodegroups[root] = group
418 else:
419 raise TopologyError('"%s" is not a valid root node!' % root)
420
421 self._root = root
422
423
424 class TopologyParser(configparser.ConfigParser):
425 """This class offers a way to interpret network topologies supplied under
426 the form :
427
428 # Comment
429 <these machines> : <can reach these ones>
430 """
431 def __init__(self, filename=None):
432 """instance wide variables initialization"""
433 configparser.ConfigParser.__init__(self)
434 self.optionxform = str # case sensitive parser
435
436 self._topology = {}
437 self.graph = None
438 self._tree = None
439
440 if filename:
441 self.load(filename)
442
443 def load(self, filename):
444 """read a given topology configuration file and store the results in
445 self._routes. Then build a propagation tree.
446 """
447 try:
448 self.read(filename)
449 if self.has_section("routes"):
450 self._topology = self.items("routes")
451 else:
452 # compat routes section [deprecated since v1.7]
453 warnings.warn("topology: [Main] section is deprecated since "
454 "v1.7, use [routes] instead", DeprecationWarning)
455 self._topology = self.items("Main")
456 except configparser.Error:
457 raise TopologyError(
458 'Invalid configuration file: %s' % filename)
459 self._build_graph()
460
461 def _build_graph(self):
462 """build a network topology graph according to the information we got
463 from the configuration file.
464 """
465 self.graph = TopologyGraph()
466 for src, dst in self._topology:
467 # GH#527: router and destination node sets may use NodeSet groups
468 # but we ignore any empty sets
469 src_ns = NodeSet(src)
470 if not src_ns:
471 LOGGER.debug('Failed to resolve router node set: %s', src)
472 dst_ns = NodeSet(dst)
473 if not dst_ns:
474 LOGGER.debug('Failed to resolve destination node set "%s" for' \
475 'router node set %s', dst, src_ns)
476 if src_ns and dst_ns:
477 self.graph.add_route(src_ns, dst_ns)
478
479 def tree(self, root, force_rebuild=False):
480 """Return a previously generated propagation tree or build it if
481 required. As rebuilding tree can be quite expensive, once built,
482 the propagation tree is cached. you can force a re-generation
483 using the optional `force_rebuild' parameter.
484 """
485 if self._tree is None or force_rebuild:
486 self._tree = self.graph.to_tree(root)
487 return self._tree