Debian Codegraph @

lib/ClusterShell/MsgTree.py

raw symbols SCIP
1 #
2 # Copyright (C) 2007-2016 CEA/DAM
3 # Copyright (C) 2016-2017 Stephane Thiell <[email protected]>
4 #
5 # This file is part of ClusterShell.
6 #
7 # ClusterShell is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # ClusterShell is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with ClusterShell; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
21 """
22 MsgTree
23
24 ClusterShell message tree module. The purpose of MsgTree is to provide a
25 shared message tree for storing message lines received from ClusterShell
26 Workers (for example, from remote cluster commands). It should be
27 efficient, in term of algorithm and memory consumption, especially when
28 remote messages are the same.
29 """
30
31 try:
32 from itertools import filterfalse
33 except ImportError: # Python 2 compat
34 from itertools import ifilterfalse as filterfalse
35
36 import sys
37
38
39 # MsgTree behavior modes
40 MODE_DEFER = 0
41 MODE_SHIFT = 1
42 MODE_TRACE = 2
43
44
45 class MsgTreeElem(object):
46 """
47 Class representing an element of the MsgTree and its associated
48 message. Object of this class are returned by the various MsgTree
49 methods like messages() or walk(). The object can then be used as
50 an iterator over the message lines or casted into a bytes buffer.
51 """
52 def __init__(self, msgline=None, parent=None, trace=False):
53 """
54 Initialize message tree element.
55 """
56 # structure
57 self.parent = parent
58 self.children = {}
59 if trace: # special behavior for trace mode
60 self._shift = self._shift_trace
61 else:
62 self._shift = self._shift_notrace
63 # content
64 self.msgline = msgline
65 self.keys = None
66
67 def __len__(self):
68 """Length of whole message buffer."""
69 return len(bytes(self))
70
71 def __eq__(self, other):
72 """Comparison method compares whole message buffers."""
73 return bytes(self) == bytes(other)
74
75 def _add_key(self, key):
76 """Add a key to this tree element."""
77 if self.keys is None:
78 self.keys = set([key])
79 else:
80 self.keys.add(key)
81
82 def _shift_notrace(self, key, target_elem):
83 """Shift one of our key to specified target element."""
84 if self.keys and len(self.keys) == 1:
85 shifting = self.keys
86 self.keys = None
87 else:
88 shifting = set([key])
89 if self.keys:
90 self.keys.difference_update(shifting)
91
92 if not target_elem.keys:
93 target_elem.keys = shifting
94 else:
95 target_elem.keys.update(shifting)
96
97 return target_elem
98
99 def _shift_trace(self, key, target_elem):
100 """Shift one of our key to specified target element (trace
101 mode: keep backtrace of keys)."""
102 if not target_elem.keys:
103 target_elem.keys = set([key])
104 else:
105 target_elem.keys.add(key)
106 return target_elem
107
108 def __getitem__(self, i):
109 return list(self.lines())[i]
110
111 def __iter__(self):
112 """Iterate over message lines up to this element."""
113 bottomtop = []
114 if self.msgline is not None:
115 bottomtop.append(self.msgline)
116 parent = self.parent
117 while parent.msgline is not None:
118 bottomtop.append(parent.msgline)
119 parent = parent.parent
120 return reversed(bottomtop)
121
122 def lines(self):
123 """Get an iterator over all message lines up to this element."""
124 return iter(self)
125
126 splitlines = lines
127
128 def message(self):
129 """
130 Get the whole message buffer (from this tree element) as bytes.
131 """
132 return b'\n'.join(self.lines())
133
134 __bytes__ = message
135
136 def __str__(self):
137 """
138 Get the whole message buffer (from this tree element) as a string.
139
140 DEPRECATED: use message() or cast to bytes instead.
141 """
142 if sys.version_info >= (3, 0):
143 raise TypeError('cannot get string from %s, use bytes instead' %
144 self.__class__.__name__)
145 else:
146 # in Python 2, str and bytes are actually the same type
147 return self.message()
148
149 def append(self, msgline, key=None):
150 """
151 A new message is coming, append it to the tree element with
152 optional associated source key. Called by MsgTree.add().
153 Return corresponding MsgTreeElem (possibly newly created).
154 """
155 # get/create child element
156 elem = self.children.get(msgline)
157 if elem is None:
158 elem = self.__class__(msgline, self,
159 self._shift == self._shift_trace)
160 self.children[msgline] = elem
161
162 # if no key is given, MsgTree is in MODE_DEFER
163 # shift down the given key otherwise
164 # Note: replace with ternary operator in py2.5+
165 if key is None:
166 return elem
167 else:
168 return self._shift(key, elem)
169
170
171 class MsgTree(object):
172 """
173 MsgTree maps key objects to multi-lines messages.
174
175 MsgTree is a mutable object. Keys are almost arbitrary values (must
176 be hashable). Message lines are organized as a tree internally.
177 MsgTree provides low memory consumption especially on a cluster when
178 all nodes return similar messages. Also, the gathering of messages is
179 done automatically.
180 """
181
182 def __init__(self, mode=MODE_DEFER):
183 """MsgTree initializer
184
185 The *mode* parameter should be set to one of the following constant:
186
187 MODE_DEFER: all messages are processed immediately, saving memory from
188 duplicate message lines, but keys are associated to tree elements
189 usually later when tree is first "walked", saving useless state
190 updates and CPU time. Once the tree is "walked" for the first time, its
191 mode changes to MODE_SHIFT to keep track of further tree updates.
192 This is the default mode.
193
194 MODE_SHIFT: all keys and messages are processed immediately, it is more
195 CPU time consuming as MsgTree full state is updated at each add() call.
196
197 MODE_TRACE: all keys and messages and processed immediately, and keys
198 are kept for each message element of the tree. The special method
199 walk_trace() is then available to walk all elements of the tree.
200 """
201 self.mode = mode
202 # root element of MsgTree
203 self._root = MsgTreeElem(trace=(mode == MODE_TRACE))
204 # dict of keys to MsgTreeElem
205 self._keys = {}
206
207 def clear(self):
208 """Remove all items from the MsgTree."""
209 self._root = MsgTreeElem(trace=(self.mode == MODE_TRACE))
210 self._keys.clear()
211
212 def __len__(self):
213 """Return the number of keys contained in the MsgTree."""
214 return len(self._keys)
215
216 def __getitem__(self, key):
217 """Return the message of MsgTree with specified key. Raises a
218 KeyError if key is not in the MsgTree."""
219 return self._keys[key]
220
221 def get(self, key, default=None):
222 """
223 Return the message for key if key is in the MsgTree, else default.
224 If default is not given, it defaults to None, so that this method
225 never raises a KeyError.
226 """
227 return self._keys.get(key, default)
228
229 def add(self, key, msgline):
230 """
231 Add a message line (in bytes) associated with the given key to the
232 MsgTree.
233 """
234 # try to get current element in MsgTree for the given key,
235 # defaulting to the root element
236 e_msg = self._keys.get(key, self._root)
237 if self.mode >= MODE_SHIFT:
238 key_shift = key
239 else:
240 key_shift = None
241 # add child msg and update keys dict
242 self._keys[key] = e_msg.append(msgline, key_shift)
243
244 def _update_keys(self):
245 """Update keys associated to tree elements (MODE_DEFER)."""
246 for key, e_msg in self._keys.items():
247 assert key is not None and e_msg is not None
248 e_msg._add_key(key)
249 # MODE_DEFER is no longer valid as keys are now assigned to MsgTreeElems
250 self.mode = MODE_SHIFT
251
252 def keys(self):
253 """Return an iterator over MsgTree's keys."""
254 return iter(self._keys.keys())
255
256 __iter__ = keys
257
258 def messages(self, match=None):
259 """Return an iterator over MsgTree's messages."""
260 return (item[0] for item in self.walk(match))
261
262 def items(self, match=None, mapper=None):
263 """
264 Return (key, message) for each key of the MsgTree.
265 """
266 if mapper is None:
267 mapper = lambda k: k
268 for key, elem in self._keys.items():
269 if match is None or match(key):
270 yield mapper(key), elem
271
272 def _depth(self):
273 """
274 Return the depth of the MsgTree, ie. the max number of lines
275 per message. Added for debugging.
276 """
277 depth = 0
278 # stack of (element, depth) tuples used to walk the tree
279 estack = [(self._root, depth)]
280
281 while estack:
282 elem, edepth = estack.pop()
283 if len(elem.children) > 0:
284 estack += [(v, edepth + 1) for v in elem.children.values()]
285 depth = max(depth, edepth)
286
287 return depth
288
289 def walk(self, match=None, mapper=None):
290 """
291 Walk the tree. Optionally filter keys on match parameter,
292 and optionally map resulting keys with mapper function.
293 Return an iterator over (message, keys) tuples for each
294 different message in the tree.
295 """
296 if self.mode == MODE_DEFER:
297 self._update_keys()
298 # stack of elements used to walk the tree (depth-first)
299 estack = [self._root]
300 while estack:
301 elem = estack.pop()
302 children = elem.children
303 if len(children) > 0:
304 estack += children.values()
305 if elem.keys: # has some keys
306 mkeys = list(filter(match, elem.keys))
307 if len(mkeys):
308 if mapper is not None:
309 keys = [mapper(key) for key in mkeys]
310 else:
311 keys = mkeys
312 yield elem, keys
313
314 def walk_trace(self, match=None, mapper=None):
315 """
316 Walk the tree in trace mode. Optionally filter keys on match
317 parameter, and optionally map resulting keys with mapper
318 function.
319 Return an iterator over 4-length tuples (msgline, keys, depth,
320 num_children).
321 """
322 assert self.mode == MODE_TRACE, \
323 "walk_trace() is only callable in trace mode"
324 # stack of (element, depth) tuples used to walk the tree
325 estack = [(self._root, 0)]
326 while estack:
327 elem, edepth = estack.pop()
328 children = elem.children
329 nchildren = len(children)
330 if nchildren > 0:
331 estack += [(v, edepth + 1) for v in children.values()]
332 if elem.keys:
333 mkeys = list(filter(match, elem.keys))
334 if len(mkeys):
335 if mapper is not None:
336 keys = [mapper(key) for key in mkeys]
337 else:
338 keys = mkeys
339 yield elem.msgline, keys, edepth, nchildren
340
341 def remove(self, match=None):
342 """
343 Modify the tree by removing any matching key references from the
344 messages tree.
345
346 Example of use:
347 >>> msgtree.remove(lambda k: k > 3)
348 """
349 # do not walk tree in MODE_DEFER as no key is associated
350 if self.mode != MODE_DEFER:
351 estack = [self._root]
352 # walk the tree to keep only matching keys
353 while estack:
354 elem = estack.pop()
355 if len(elem.children) > 0:
356 estack += elem.children.values()
357 if elem.keys: # has some keys
358 elem.keys = set(filterfalse(match, elem.keys))
359
360 # remove key(s) from known keys dict
361 for key in list(filter(match, self._keys.keys())):
362 del self._keys[key]