Debian Codegraph @

lib/ClusterShell/CLI/OptionParser.py

raw symbols SCIP
1 #
2 # Copyright (C) 2010-2015 CEA/DAM
3 #
4 # This file is part of ClusterShell.
5 #
6 # ClusterShell is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU Lesser General Public
8 # License as published by the Free Software Foundation; either
9 # version 2.1 of the License, or (at your option) any later version.
10 #
11 # ClusterShell is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # Lesser General Public License for more details.
15 #
16 # You should have received a copy of the GNU Lesser General Public
17 # License along with ClusterShell; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
20 """
21 Common ClusterShell CLI OptionParser
22
23 With few exceptions, ClusterShell command-lines share most option
24 arguments. This module provides a common OptionParser class.
25 """
26
27 from copy import copy
28 import optparse
29
30 from ClusterShell import __version__
31 from ClusterShell.Engine.Factory import PreferredEngine
32 from ClusterShell.CLI.Display import THREE_CHOICES
33
34
35 def check_autostep(option, opt, value):
36 """type-checker function for autostep"""
37 try:
38 if '%' in value:
39 return float(value[:-1]) / 100.0
40 return int(value)
41 except ValueError:
42 if value == 'auto':
43 return value
44 error_fmt = "option %s: invalid value: %r, should be node count, " \
45 "node percentage or 'auto'"
46 raise optparse.OptionValueError(error_fmt % (opt, value))
47
48 def check_safestring(option, opt, value):
49 """type-checker function for safestring"""
50 try:
51 safestr = str(value)
52 # check if the string is not empty and not an option
53 if not safestr or safestr.startswith('-'):
54 raise ValueError()
55 return safestr
56 except ValueError:
57 raise optparse.OptionValueError(
58 "option %s: invalid value: %r" % (opt, value))
59
60
61 class Option(optparse.Option):
62 """This Option subclass adds a new safestring type."""
63 TYPES = optparse.Option.TYPES + ("autostep", "safestring",)
64 TYPE_CHECKER = copy(optparse.Option.TYPE_CHECKER)
65 TYPE_CHECKER["autostep"] = check_autostep
66 TYPE_CHECKER["safestring"] = check_safestring
67
68 class OptionParser(optparse.OptionParser):
69 """Derived OptionParser for all CLIs"""
70
71 def __init__(self, usage, **kwargs):
72 """Initialize ClusterShell CLI OptionParser"""
73 optparse.OptionParser.__init__(self, usage,
74 version="%%prog %s" % __version__,
75 option_class=Option,
76 **kwargs)
77
78 # Set parsing to stop on the first non-option
79 self.disable_interspersed_args()
80
81 # Always install groupsource support
82 self.add_option("-s", "--groupsource", action="store",
83 type="safestring", dest="groupsource",
84 help="optional groups.conf(5) group source to use")
85
86 def install_clush_config_options(self):
87 """Install config options for clush"""
88 # config file override (--conf)
89 self.add_option("--conf", action="store", metavar='FILE',
90 help="use alternate config file for clush.conf(5)")
91 # config file option overrides (-O)
92 self.add_option("-O", "--option", action="append", metavar="KEY=VALUE",
93 dest="option", default=[],
94 help="override any key=value clush.conf(5) options")
95
96 def install_groupsconf_option(self):
97 """Install an alternate groups.conf file option"""
98 self.add_option("--groupsconf", action="store", metavar='FILE',
99 help="use alternate config file for groups.conf(5)")
100
101 def install_nodes_options(self):
102 """Install nodes selection options"""
103 optgrp = optparse.OptionGroup(self, "Selecting target nodes")
104 optgrp.add_option("-w", action="append", type="safestring",
105 dest="nodes", help="nodes where to run the command")
106 optgrp.add_option("-x", action="append", type="safestring",
107 dest="exclude", metavar="NODES",
108 help="exclude nodes from the node list")
109 optgrp.add_option("-a", "--all", action="store_true", dest="nodes_all",
110 help="run command on all nodes")
111 optgrp.add_option("-g", "--group", action="append", type="safestring",
112 dest="group", help="run command on a group of nodes")
113 optgrp.add_option("-X", action="append", dest="exgroup",
114 metavar="GROUP", type="safestring",
115 help="exclude nodes from this group")
116 optgrp.add_option("-E", "--engine", action="store", dest="engine",
117 choices=["auto"] + list(PreferredEngine.engines),
118 default="auto", help=optparse.SUPPRESS_HELP)
119 optgrp.add_option("--hostfile", "--machinefile", action="append",
120 dest="hostfile", default=[], metavar='FILE',
121 help="path to file containing a list of target hosts")
122 optgrp.add_option("--topology", action="store", dest="topofile",
123 default=None, metavar='FILE',
124 help="topology configuration file to use for tree "
125 "mode")
126 optgrp.add_option("--pick", action="store", dest="pick",
127 metavar="N", type="int",
128 help="pick N node(s) at random in nodeset")
129 self.add_option_group(optgrp)
130
131 def install_display_options(self,
132 debug_option=True,
133 verbose_options=False,
134 separator_option=False,
135 dshbak_compat=False,
136 msgtree_mode=False):
137 """Install options needed by Display class"""
138 optgrp = optparse.OptionGroup(self, "Output behaviour")
139 if verbose_options:
140 optgrp.add_option("-q", "--quiet", action="store_true",
141 dest="quiet", help="be quiet, print essential output only")
142 optgrp.add_option("-v", "--verbose", action="store_true",
143 dest="verbose", help="be verbose, print informative messages")
144 if debug_option:
145 optgrp.add_option("-d", "--debug", action="store_true",
146 dest="debug",
147 help="output more messages for debugging purpose")
148 optgrp.add_option("-G", "--groupbase", action="store_true",
149 dest="groupbase", default=False,
150 help="do not display group source prefix")
151 optgrp.add_option("-L", action="store_true", dest="line_mode",
152 help="disable header block and order output by nodes")
153 optgrp.add_option("-N", action="store_false", dest="label",
154 default=True, help="disable labeling of command output")
155 if dshbak_compat:
156 optgrp.add_option("-b", "-c", "--dshbak", action="store_true",
157 dest="gather", help="gather nodes with same output")
158 else:
159 optgrp.add_option("-P", "--progress", action="store_true",
160 dest="progress", help="show progress during command execution")
161 optgrp.add_option("-b", "--dshbak", action="store_true",
162 dest="gather", help="gather nodes with same output")
163 optgrp.add_option("-B", action="store_true", dest="gatherall",
164 default=False, help="like -b but including standard error")
165 optgrp.add_option("-r", "--regroup", action="store_true",
166 dest="regroup", default=False,
167 help="fold nodeset using node groups")
168 optgrp.add_option("--axis", action="store", dest="axis",
169 metavar="RANGESET",
170 help="fold along these axis only "
171 "(axis 1..n for nD nodeset)")
172
173 if separator_option:
174 optgrp.add_option("-S", "--separator", action="store",
175 dest="separator", default=':',
176 help="node / line content separator string "
177 "(default: ':')")
178 else:
179 optgrp.add_option("-S", "--maxrc", action="store_true", dest="maxrc",
180 help="return the largest of command return codes")
181
182 if msgtree_mode:
183 # clubak specific
184 optgrp.add_option("-F", "--fast", action="store_true",
185 dest="fast_mode",
186 help="faster but memory hungry mode")
187 optgrp.add_option("-T", "--tree", action="store_true",
188 dest="trace_mode",
189 help="message tree trace mode")
190 optgrp.add_option("--interpret-keys", action="store",
191 dest="interpret_keys", choices=THREE_CHOICES,
192 default=THREE_CHOICES[-1], help="whether to "
193 "interpret keys (never, always or auto)")
194
195 optgrp.add_option("--color", action="store", dest="whencolor",
196 choices=THREE_CHOICES, help="whether to use ANSI "
197 "colors (never, always or auto)")
198 optgrp.add_option("--diff", action="store_true", dest="diff",
199 help="show diff between gathered outputs")
200 optgrp.add_option("--outdir", action="store", dest="outdir", help="output directory for stdout files (OPTIONAL)")
201 optgrp.add_option("--errdir", action="store", dest="errdir", help="output directory for stderr files (OPTIONAL)")
202 self.add_option_group(optgrp)
203
204 def _copy_callback(self, option, opt_str, value, parser):
205 """special callback method for copy and rcopy toggles"""
206 # enable interspersed args again
207 self.enable_interspersed_args()
208 # set True to dest option attribute
209 setattr(parser.values, option.dest, True)
210
211 def install_filecopy_options(self):
212 """Install file copying specific options"""
213 optgrp = optparse.OptionGroup(self, "File copying")
214 optgrp.add_option("-c", "--copy", action="callback", dest="copy",
215 callback=self._copy_callback,
216 help="copy local file or directory to remote nodes")
217 optgrp.add_option("--rcopy", action="callback", dest="rcopy",
218 callback=self._copy_callback,
219 help="copy file or directory from remote nodes")
220 optgrp.add_option("--dest", action="store", dest="dest_path",
221 help="destination file or directory on the nodes")
222 optgrp.add_option("-p", action="store_true", dest="preserve_flag",
223 help="preserve modification times and modes")
224 self.add_option_group(optgrp)
225
226
227 def install_connector_options(self):
228 """Install engine/connector (ssh, ...) options"""
229 optgrp = optparse.OptionGroup(self, "Connection options")
230 optgrp.add_option("-f", "--fanout", action="store", dest="fanout",
231 help="use a specified fanout", type="int")
232 #help="queueing delay for traffic grooming"
233 optgrp.add_option("--grooming", action="store", dest="grooming_delay",
234 help=optparse.SUPPRESS_HELP, type="float")
235 optgrp.add_option("-l", "--user", action="store", type="safestring",
236 dest="user", help="execute remote command as user")
237 optgrp.add_option("-o", "--options", action="store", dest="options",
238 help="can be used to give ssh options")
239 optgrp.add_option("-t", "--connect_timeout", action="store",
240 dest="connect_timeout",
241 help="limit time to connect to a node", type="float")
242 optgrp.add_option("-u", "--command_timeout", action="store",
243 dest="command_timeout",
244 help="limit time for command to run on the node",
245 type="float")
246 optgrp.add_option("-m", "--mode", action="store", dest="mode",
247 help="run mode; define MODEs in <confdir>/*.conf")
248 optgrp.add_option("-R", "--worker", action="store", dest="worker",
249 help="worker name to use for command execution "
250 "('exec', 'rsh', 'ssh', etc. default is 'ssh')")
251 optgrp.add_option("--remote", action="store", dest="remote",
252 choices=('yes', 'no'),
253 help="whether to enable remote execution: in tree "
254 "mode, 'yes' forces connections to the leaf "
255 "nodes for execution, 'no' establishes "
256 "connections up to the leaf parent nodes for "
257 "execution (default is 'yes')")
258 self.add_option_group(optgrp)
259
260 def install_nodeset_commands(self):
261 """Install nodeset commands"""
262 optgrp = optparse.OptionGroup(self, "Commands")
263 optgrp.add_option("-c", "--count", action="store_true", dest="count",
264 default=False,
265 help="show number of nodes in nodeset(s)")
266 optgrp.add_option("-e", "--expand", action="store_true", dest="expand",
267 default=False,
268 help="expand nodeset(s) to separate nodes")
269 optgrp.add_option("-f", "--fold", action="store_true", dest="fold",
270 default=False, help="fold nodeset(s) (or separate "
271 "nodes) into one nodeset")
272 optgrp.add_option("-l", "--list", action="count", dest="list",
273 default=False, help="list node groups from one "
274 "source (see -s GROUPSOURCE)")
275 optgrp.add_option("-L", "--list-all", action="count", dest="listall",
276 default=False,
277 help="list node groups from all group sources")
278 optgrp.add_option("-r", "--regroup", action="store_true",
279 dest="regroup", default=False,
280 help="fold nodes using node groups (see -s "
281 "GROUPSOURCE)")
282 optgrp.add_option("--index", action="store", dest="index",
283 metavar="NODE", type="string",
284 help="output the index of NODE in the nodeset")
285 optgrp.add_option("--list-sources", "--groupsources",
286 action="store_true", dest="groupsources",
287 default=False,
288 help="list all active group sources (see "
289 "groups.conf(5))")
290 # special hidden command for bash completion scripts
291 optgrp.add_option("--completion", action="store_true",
292 dest="completion",
293 default=False, help=optparse.SUPPRESS_HELP)
294 self.add_option_group(optgrp)
295
296 def install_nodeset_operations(self):
297 """Install nodeset operations"""
298 optgrp = optparse.OptionGroup(self, "Operations")
299 optgrp.add_option("-x", "--exclude", action="append", dest="sub_nodes",
300 default=[], type="string",
301 help="exclude specified nodeset")
302 optgrp.add_option("-i", "--intersection", action="append",
303 dest="and_nodes", default=[], type="string",
304 help="calculate nodesets intersection")
305 optgrp.add_option("-X", "--xor", action="append", dest="xor_nodes",
306 default=[], type="string",
307 help="calculate symmetric difference between "
308 "nodesets")
309 self.add_option_group(optgrp)
310
311 def install_nodeset_options(self):
312 """Install nodeset options"""
313 optgrp = optparse.OptionGroup(self, "Options")
314 optgrp.add_option("-a", "--all", action="store_true", dest="all",
315 help="call external node groups support to "
316 "display all nodes")
317 optgrp.add_option("--autostep", action="store", dest="autostep",
318 help="enable a-b/step style syntax when folding, "
319 "value is min node count threshold (eg. '4', "
320 "'50%' or 'auto')",
321 type="autostep")
322 optgrp.add_option("-d", "--debug", action="store_true", dest="debug",
323 help="output more messages for debugging purpose")
324 optgrp.add_option("-q", "--quiet", action="store_true", dest="quiet",
325 help="be quiet, print essential output only")
326 optgrp.add_option("-R", "--rangeset", action="store_true",
327 dest="rangeset", help="switch to RangeSet instead "
328 "of NodeSet. Useful when working on numerical "
329 "cluster ranges, eg. 1,5,18-31")
330 optgrp.add_option("-G", "--groupbase", action="store_true",
331 dest="groupbase", help="hide group source prefix "
332 "(always \"@groupname\")")
333 optgrp.add_option("-S", "--separator", action="store", dest="separator",
334 default=' ', help="separator string to use when "
335 "expanding nodesets (default: ' ')")
336 optgrp.add_option("-O", "--output-format", action="store",
337 dest="output_format", metavar='FORMAT', default='%s',
338 help="output format (default: '%s')")
339 optgrp.add_option("-I", "--slice", action="store",
340 dest="slice_rangeset",
341 help="return sliced off result", type="string")
342 optgrp.add_option("--split", action="store", dest="maxsplit",
343 help="split result into a number of subsets",
344 type="int")
345 optgrp.add_option("--contiguous", action="store_true",
346 dest="contiguous", help="split result into "
347 "contiguous subsets")
348 optgrp.add_option("--axis", action="store", dest="axis",
349 metavar="RANGESET", help="fold along these axis only "
350 "(axis 1..n for nD nodeset)")
351 optgrp.add_option("--pick", action="store", dest="pick",
352 metavar="N", type="int",
353 help="pick N node(s) at random in nodeset")
354 self.add_option_group(optgrp)