Debian Codegraph @

lib/ClusterShell/CLI/Nodeset.py

raw symbols SCIP
1 #
2 # Copyright (C) 2008-2016 CEA/DAM
3 # Copyright (C) 2015-2018 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 compute advanced nodeset operations
23
24 The nodeset command is an utility command provided with the
25 ClusterShell library which implements some features of the NodeSet
26 and RangeSet classes.
27 """
28
29 from __future__ import print_function
30
31 import logging
32 import math
33 import random
34 import sys
35
36 from ClusterShell.CLI.Error import GENERIC_ERRORS, handle_generic_error
37 from ClusterShell.CLI.OptionParser import OptionParser
38 from ClusterShell.CLI.Utils import parse_fold_axis
39
40 from ClusterShell.NodeSet import NodeSet, RangeSet, std_group_resolver
41 from ClusterShell.NodeSet import grouplist, set_std_group_resolver_config
42 from ClusterShell.NodeUtils import GroupSourceNoUpcall
43
44
45 def process_stdin(xsetop, xsetcls, autostep):
46 """Process standard input and operate on xset."""
47 # Build temporary set (stdin accumulator)
48 tmpset = xsetcls(autostep=autostep)
49 for line in sys.stdin: # read lines of text stream (not bytes)
50 # Support multi-lines and multi-nodesets per line
51 line = line[0:line.find('#')].strip()
52 for elem in line.split():
53 # Do explicit object creation for RangeSet
54 tmpset.update(xsetcls(elem, autostep=autostep))
55 # Perform operation on xset
56 if tmpset:
57 xsetop(tmpset)
58
59 def compute_nodeset(xset, args, autostep):
60 """Apply operations and operands from args on xset, an initial
61 RangeSet or NodeSet."""
62 class_set = xset.__class__
63 # Process operations from command arguments.
64 # The special argument string "-" indicates to read stdin.
65 # We also take care of multiline shell arguments (#394).
66 while args:
67 arg = args.pop(0)
68 if arg in ("-i", "--intersection"):
69 val = args.pop(0)
70 if val == '-':
71 process_stdin(xset.intersection_update, class_set, autostep)
72 else:
73 xset.intersection_update(class_set.fromlist(val.splitlines(),
74 autostep=autostep))
75 elif arg in ("-x", "--exclude"):
76 val = args.pop(0)
77 if val == '-':
78 process_stdin(xset.difference_update, class_set, autostep)
79 else:
80 xset.difference_update(class_set.fromlist(val.splitlines(),
81 autostep=autostep))
82 elif arg in ("-X", "--xor"):
83 val = args.pop(0)
84 if val == '-':
85 process_stdin(xset.symmetric_difference_update, class_set,
86 autostep)
87 else:
88 xset.symmetric_difference_update(
89 class_set.fromlist(val.splitlines(), autostep=autostep))
90 elif arg == '-':
91 process_stdin(xset.update, xset.__class__, autostep)
92 else:
93 xset.update(class_set.fromlist(arg.splitlines(), autostep=autostep))
94
95 return xset
96
97 def print_source_groups(source, level, xset, opts):
98 """
99 Print groups from a source, a level of verbosity and an optional
100 nodeset acting as a filter.
101 """
102 # list groups of some specified nodes?
103 if opts.all or xset or opts.and_nodes or opts.sub_nodes or opts.xor_nodes:
104 # When some node sets are provided as argument, the list command
105 # retrieves node groups these nodes belong to, thanks to the
106 # groups() method.
107 # Note: stdin support is enabled when '-' is found.
108 groups = xset.groups(source, opts.groupbase)
109 # sort by group name
110 for group, (gnodes, inodes) in sorted(groups.items()):
111 if level == 1:
112 print(group)
113 elif level == 2:
114 print("%s %s" % (group, inodes))
115 else:
116 print("%s %s %d/%d" % (group, inodes, len(inodes),
117 len(gnodes)))
118 else:
119 # "raw" group list when no argument at all
120 for group in grouplist(source):
121 if source and not opts.groupbase:
122 nsgroup = "@%s:%s" % (source, group)
123 else:
124 nsgroup = "@%s" % group
125 if level == 1:
126 print(nsgroup)
127 else:
128 nodes = NodeSet(nsgroup)
129 if level == 2:
130 print("%s %s" % (nsgroup, nodes))
131 else:
132 print("%s %s %d" % (nsgroup, nodes, len(nodes)))
133
134 def command_list(options, xset, group_resolver):
135 """List command handler (-l/-ll/-lll/-L/-LL/-LLL)."""
136 list_level = options.list + options.listall + options.completion
137 if options.listall:
138 # useful: sources[0] is always the default or selected source
139 sources = group_resolver.sources()
140 # do not print the name of the current group source (either the default
141 # or the one specified by -s)
142 if sources:
143 sources[0] = None
144 else:
145 sources = [options.groupsource]
146
147 for source in sources:
148 try:
149 print_source_groups(source, list_level, xset, options)
150 except GroupSourceNoUpcall as exc:
151 if not options.listall:
152 raise
153 # missing list upcall is not fatal with -L
154 msgfmt = "Warning: No %s upcall defined for group source %s"
155 print(msgfmt % (exc, source), file=sys.stderr)
156
157 def nodeset():
158 """script subroutine"""
159 class_set = NodeSet
160 usage = "%prog [COMMAND] [OPTIONS] [ns1 [-ixX] ns2|...]"
161
162 parser = OptionParser(usage)
163 parser.install_groupsconf_option()
164 parser.install_nodeset_commands()
165 parser.install_nodeset_operations()
166 parser.install_nodeset_options()
167 (options, args) = parser.parse_args()
168
169 set_std_group_resolver_config(options.groupsconf)
170 group_resolver = std_group_resolver()
171
172 if options.debug:
173 logging.basicConfig(level=logging.DEBUG)
174
175 # Check for command presence
176 cmdcount = int(options.count) + int(options.expand) + \
177 int(options.fold) + int(bool(options.list)) + \
178 int(bool(options.listall)) + int(options.regroup) + \
179 int(options.groupsources) + int(options.completion) + \
180 int(options.index is not None)
181 if not cmdcount:
182 parser.error("No command specified.")
183 elif cmdcount > 1:
184 parser.error("Multiple commands not allowed.")
185
186 if options.rangeset:
187 class_set = RangeSet
188
189 if options.all or options.regroup:
190 if class_set != NodeSet:
191 parser.error("-a/-r only supported in NodeSet mode")
192
193 if options.maxsplit is not None and options.contiguous:
194 parser.error("incompatible splitting options (split, contiguous)")
195
196 if options.maxsplit is None:
197 options.maxsplit = 1
198
199 if options.axis and (not options.fold or options.rangeset):
200 parser.error("--axis option is only supported when folding nodeset")
201
202 if options.index is not None and options.pick:
203 parser.error("--index cannot be combined with --pick")
204
205 if options.groupsource and not options.quiet and class_set == RangeSet:
206 print("WARNING: option group source \"%s\" ignored"
207 % options.groupsource, file=sys.stderr)
208
209 # We want -s <groupsource> to act as a substitution of default groupsource
210 # (ie. it's not necessary to prefix group names by this group source).
211 if options.groupsource:
212 group_resolver.default_source_name = options.groupsource
213
214 # The groupsources command simply lists group sources.
215 if options.groupsources:
216 if options.quiet:
217 dispdefault = "" # don't show (default) if quiet is set
218 else:
219 dispdefault = " (default)"
220 for src in group_resolver.sources():
221 print("%s%s" % (src, dispdefault))
222 dispdefault = ""
223 return
224
225 autostep = options.autostep
226
227 # Do not use autostep for computation when a percentage or the special
228 # value 'auto' is specified. Real autostep value is set post-process.
229 if isinstance(autostep, float) or autostep == 'auto':
230 autostep = None
231
232 # Instantiate RangeSet or NodeSet object
233 xset = class_set(autostep=autostep)
234
235 if options.all:
236 # Include all nodes from external node groups support.
237 xset.update(NodeSet.fromall()) # uses default_source when set
238
239 if not args and not options.all and not (options.list or
240 options.listall or
241 options.completion):
242 # No need to specify '-' to read stdin in these cases
243 process_stdin(xset.update, xset.__class__, autostep)
244
245 if not xset and (options.and_nodes or options.sub_nodes or
246 options.xor_nodes) and not options.quiet:
247 print('WARNING: empty left operand for set operation', file=sys.stderr)
248
249 # Apply first operations (before first non-option)
250 for nodes in options.and_nodes:
251 if nodes == '-':
252 process_stdin(xset.intersection_update, xset.__class__, autostep)
253 else:
254 xset.intersection_update(class_set(nodes, autostep=autostep))
255 for nodes in options.sub_nodes:
256 if nodes == '-':
257 process_stdin(xset.difference_update, xset.__class__, autostep)
258 else:
259 xset.difference_update(class_set(nodes, autostep=autostep))
260 for nodes in options.xor_nodes:
261 if nodes == '-':
262 process_stdin(xset.symmetric_difference_update, xset.__class__,
263 autostep)
264 else:
265 xset.symmetric_difference_update(class_set(nodes,
266 autostep=autostep))
267
268 # Finish xset computing from args
269 compute_nodeset(xset, args, autostep)
270
271 # The list command has a special handling
272 if options.list > 0 or options.listall > 0:
273 return command_list(options, xset, group_resolver)
274 elif options.completion: # --completion is used for bash completion
275 # list group source prefixes unless source is already specified
276 if not options.groupsource:
277 for src in group_resolver.sources():
278 print("@%s:" % src)
279 # list groups in group source (similar to list)
280 command_list(options, None, group_resolver)
281 # then list nodes from the groups passed as argument, if any
282 if not xset:
283 return
284 options.expand = True
285
286 # Interpret special characters (may raise SyntaxError)
287 separator = eval('\'\'\'%s\'\'\'' % options.separator,
288 {"__builtins__":None}, {})
289
290 if options.slice_rangeset:
291 _xset = class_set()
292 for sli in RangeSet(options.slice_rangeset).slices():
293 _xset.update(xset[sli])
294 xset = _xset
295
296 if options.autostep == 'auto':
297 # Simple implementation of --autostep=auto
298 # if we have at least 3 nodes, all index should be foldable as a-b/n
299 xset.autostep = max(3, len(xset))
300 elif isinstance(options.autostep, float):
301 # at least % of nodes should be foldable as a-b/n
302 autofactor = float(options.autostep)
303 xset.autostep = int(math.ceil(float(len(xset)) * autofactor))
304
305 # user-specified nD-nodeset fold axis
306 if options.axis:
307 xset.fold_axis = parse_fold_axis(options.axis)
308
309 if options.pick and options.pick < len(xset):
310 # convert to string for sample as nsiter() is slower for big
311 # nodesets; and we assume options.pick will remain small-ish
312 keep = random.sample(list(xset), options.pick)
313 # explicit class_set creation and str() conversion for RangeSet
314 keep = class_set(','.join([str(x) for x in keep]))
315 xset.intersection_update(keep)
316
317 fmt = options.output_format # default to '%s'
318
319 # --index outputs the position of a node in the set (reverse of -I/--slice)
320 if options.index is not None:
321 print(fmt % xset.index(options.index))
322 return
323
324 # Display result according to command choice
325 if options.expand:
326 xsubres = lambda x: separator.join((fmt % s for s in x.striter()))
327 elif options.fold:
328 # Special case when folding using NodeSet and format is set (#277)
329 if class_set is NodeSet and fmt != '%s':
330 # Create a new set after format has been applied to each node
331 xset = class_set._fromlist1((fmt % xnodestr for xnodestr in xset),
332 autostep=xset.autostep)
333 xsubres = lambda x: x
334 else:
335 xsubres = lambda x: fmt % x
336 elif options.regroup:
337 xsubres = lambda x: fmt % x.regroup(options.groupsource,
338 noprefix=options.groupbase)
339 else:
340 xsubres = lambda x: fmt % len(x)
341
342 if not xset or options.maxsplit <= 1 and not options.contiguous:
343 print(xsubres(xset))
344 else:
345 if options.contiguous:
346 xiterator = xset.contiguous()
347 else:
348 xiterator = xset.split(options.maxsplit)
349 for xsubset in xiterator:
350 print(xsubres(xsubset))
351
352 def main():
353 """main script function"""
354 try:
355 nodeset()
356 except (AssertionError, IndexError, ValueError) as ex:
357 print("ERROR: %s" % ex, file=sys.stderr)
358 sys.exit(1)
359 except SyntaxError:
360 print("ERROR: invalid separator", file=sys.stderr)
361 sys.exit(1)
362 except GENERIC_ERRORS as ex:
363 sys.exit(handle_generic_error(ex))
364
365 sys.exit(0)
366
367
368 if __name__ == '__main__':
369 main()