4 # Copyright (C) 2009 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27 from cStringIO import StringIO
29 from ganeti import constants
30 from ganeti import cli
31 from ganeti import utils
33 # _autoconf shouldn't be imported from anywhere except constants.py, but we're
34 # making an exception here because this script is only used at build time.
35 from ganeti import _autoconf
39 """Helper class to write scripts with indentation.
44 def __init__(self, fh):
49 """Increase indentation level by 1.
55 """Decrease indentation level by 1.
58 assert self._indent > 0
61 def Write(self, txt, *args):
62 """Write line to output file.
65 self._fh.write(self._indent * self.INDENT_STR)
68 self._fh.write(txt % args)
75 def WritePreamble(sw):
76 """Writes the script preamble.
78 Helper functions should be written here.
81 sw.Write("# This script is automatically generated at build time.")
82 sw.Write("# Do not modify manually.")
84 sw.Write("_ganeti_nodes() {")
87 node_list_path = os.path.join(constants.DATA_DIR, "ssconf_node_list")
88 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(node_list_path))
93 sw.Write("_ganeti_instances() {")
96 instance_list_path = os.path.join(constants.DATA_DIR,
97 "ssconf_instance_list")
98 sw.Write("cat %s 2>/dev/null || :", utils.ShellQuote(instance_list_path))
103 sw.Write("_ganeti_jobs() {")
106 # FIXME: this is really going into the internals of the job queue
107 sw.Write(("local jlist=$( shopt -s nullglob &&"
108 " cd %s 2>/dev/null && echo job-* || : )"),
109 utils.ShellQuote(constants.QUEUE_DIR))
110 sw.Write('echo "${jlist//job-/}"')
115 sw.Write("_ganeti_os() {")
118 # FIXME: Make querying the master for all OSes cheap
119 for path in constants.OS_SEARCH_PATH:
120 sw.Write("( shopt -s nullglob && cd %s 2>/dev/null && echo * || : )",
121 utils.ShellQuote(path))
126 # Params: <offset> <options with values> <options without values>
127 # Result variable: $first_arg_idx
128 sw.Write("_ganeti_find_first_arg() {")
131 sw.Write("local w i")
133 sw.Write("first_arg_idx=")
134 sw.Write("for (( i=$1; i < COMP_CWORD; ++i )); do")
137 sw.Write("w=${COMP_WORDS[$i]}")
140 sw.Write("""if [[ -n "$2" && "$w" == @($2) ]]; then let ++i""")
143 sw.Write("""elif [[ -n "$3" && "$w" == @($3) ]]; then :""")
145 # Ah, we found the first argument
146 sw.Write("else first_arg_idx=$i; break;")
155 # Params: <list of options separated by space>
156 # Input variable: $first_arg_idx
157 # Result variables: $arg_idx, $choices
158 sw.Write("_ganeti_list_options() {")
161 sw.Write("""if [[ -z "$first_arg_idx" ]]; then""")
164 sw.Write("arg_idx=0")
165 # Show options only if the current word starts with a dash
166 sw.Write("""if [[ "$cur" == -* ]]; then""")
169 sw.Write("choices=$1")
178 # Calculate position of current argument
179 sw.Write("arg_idx=$(( COMP_CWORD - first_arg_idx ))")
185 # Params: <long options with equal sign> <all options>
186 # Result variable: $optcur
187 sw.Write("_ganeti_checkopt() {")
190 sw.Write("""if [[ -n "$1" && "$cur" == @($1) ]]; then""")
193 sw.Write("optcur=\"${cur#--*=}\"")
197 sw.Write("""elif [[ -n "$2" && "$prev" == @($2) ]]; then""")
200 sw.Write("optcur=\"$cur\"")
212 def WriteCompReply(sw, args, cur="\"$cur\""):
213 sw.Write("""COMPREPLY=( $(compgen %s -- %s) )""", args, cur)
217 class CompletionWriter:
218 """Command completion writer class.
221 def __init__(self, arg_offset, opts, args):
222 self.arg_offset = arg_offset
227 opt.all_names = sorted(opt._short_opts + opt._long_opts)
229 def _FindFirstArgument(self, sw):
233 for opt in self.opts:
234 if opt.takes_value():
236 for i in opt.all_names:
237 if i.startswith("--"):
238 ignore.append("%s=*" % utils.ShellQuote(i))
239 skip_one.append(utils.ShellQuote(i))
241 ignore.extend([utils.ShellQuote(i) for i in opt.all_names])
243 ignore = sorted(utils.UniqueSequence(ignore))
244 skip_one = sorted(utils.UniqueSequence(skip_one))
246 if ignore or skip_one:
247 # Try to locate first argument
248 sw.Write("_ganeti_find_first_arg %s %s %s",
250 utils.ShellQuote("|".join(skip_one)),
251 utils.ShellQuote("|".join(ignore)))
253 # When there are no options the first argument is always at position
255 sw.Write("first_arg_idx=%s", self.arg_offset + 1)
257 def _CompleteOptionValues(self, sw):
259 # "values" -> [optname1, optname2, ...]
262 for opt in self.opts:
263 if not opt.takes_value():
266 # Only static choices implemented so far (e.g. no node list)
267 suggest = getattr(opt, "completion_suggest", None)
270 suggest = opt.choices
273 suggest_text = " ".join(sorted(suggest))
277 values.setdefault(suggest_text, []).extend(opt.all_names)
279 # Don't write any code if there are no option values
287 for (suggest, allnames) in values.iteritems():
288 longnames = [i for i in allnames if i.startswith("--")]
295 sw.Write("%s _ganeti_checkopt %s %s; then", condcmd,
296 utils.ShellQuote("|".join(["%s=*" % i for i in longnames])),
297 utils.ShellQuote("|".join(allnames)))
300 WriteCompReply(sw, "-W %s" % utils.ShellQuote(suggest), cur=cur)
311 def _CompleteArguments(self, sw):
312 if not (self.opts or self.args):
315 all_option_names = []
316 for opt in self.opts:
317 all_option_names.extend(opt.all_names)
318 all_option_names.sort()
320 # List options if no argument has been specified yet
321 sw.Write("_ganeti_list_options %s",
322 utils.ShellQuote(" ".join(all_option_names)))
325 last_idx = len(self.args) - 1
327 varlen_arg_idx = None
330 # Write some debug comments
331 for idx, arg in enumerate(self.args):
332 sw.Write("# %s: %r", idx, arg)
334 sw.Write("compgenargs=")
336 for idx, arg in enumerate(self.args):
337 assert arg.min is not None and arg.min >= 0
338 assert not (idx < last_idx and arg.max is None)
340 if arg.min != arg.max or arg.max is None:
341 if varlen_arg_idx is not None:
342 raise Exception("Only one argument can have a variable length")
347 if isinstance(arg, cli.ArgUnknown):
349 elif isinstance(arg, cli.ArgSuggest):
350 choices = utils.ShellQuote(" ".join(arg.choices))
351 elif isinstance(arg, cli.ArgInstance):
352 choices = "$(_ganeti_instances)"
353 elif isinstance(arg, cli.ArgNode):
354 choices = "$(_ganeti_nodes)"
355 elif isinstance(arg, cli.ArgJobId):
356 choices = "$(_ganeti_jobs)"
357 elif isinstance(arg, cli.ArgFile):
359 compgenargs.append("-f")
360 elif isinstance(arg, cli.ArgCommand):
362 compgenargs.append("-c")
363 elif isinstance(arg, cli.ArgHost):
365 compgenargs.append("-A hostname")
367 raise Exception("Unknown argument type %r" % arg)
369 if arg.min == 1 and arg.max == 1:
370 cmpcode = """"$arg_idx" == %d""" % (last_arg_end)
371 elif arg.min <= arg.max:
372 cmpcode = (""""$arg_idx" -ge %d && "$arg_idx" -lt %d""" %
373 (last_arg_end, last_arg_end + arg.max))
374 elif arg.max is None:
375 cmpcode = """"$arg_idx" -ge %d""" % (last_arg_end)
377 raise Exception("Unable to generate argument position condition")
379 last_arg_end += arg.min
381 if choices or compgenargs:
387 sw.Write("""%s [[ %s ]]; then""", condcmd, cmpcode)
391 sw.Write("""choices="$choices "%s""", choices)
393 sw.Write("compgenargs=%s", utils.ShellQuote(" ".join(compgenargs)))
403 WriteCompReply(sw, """-W "$choices" $compgenargs""")
405 # $compgenargs exists only if there are arguments
406 WriteCompReply(sw, '-W "$choices"')
408 def WriteTo(self, sw):
409 self._FindFirstArgument(sw)
410 self._CompleteOptionValues(sw)
411 self._CompleteArguments(sw)
414 def WriteCompletion(sw, scriptname, funcname,
416 opts=None, args=None):
417 """Writes the completion code for one command.
419 @type sw: ShellWriter
420 @param sw: Script writer
421 @type scriptname: string
422 @param scriptname: Name of command line program
423 @type funcname: string
424 @param funcname: Shell function name
426 @param commands: List of all subcommands in this program
429 sw.Write("%s() {", funcname)
433 ' cur="${COMP_WORDS[COMP_CWORD]}"'
434 ' prev="${COMP_WORDS[COMP_CWORD-1]}"'
435 ' i first_arg_idx choices compgenargs arg_idx optcur')
437 # Useful for debugging:
438 #sw.Write("echo cur=\"$cur\" prev=\"$prev\"")
439 #sw.Write("set | grep ^COMP_")
441 sw.Write("COMPREPLY=()")
443 if opts is not None and args is not None:
445 CompletionWriter(0, opts, args).WriteTo(sw)
448 sw.Write("""if [[ "$COMP_CWORD" == 1 ]]; then""")
451 # Complete the command name
454 utils.ShellQuote(" ".join(sorted(commands.keys())))))
459 # We're doing options and arguments to commands
460 sw.Write("""case "${COMP_WORDS[1]}" in""")
461 for cmd, (_, argdef, optdef, _, _) in commands.iteritems():
462 if not (argdef or optdef):
465 # TODO: Group by arguments and options
466 sw.Write("%s)", utils.ShellQuote(cmd))
469 CompletionWriter(1, optdef, argdef).WriteTo(sw)
479 sw.Write("complete -F %s -o filenames %s",
480 utils.ShellQuote(funcname),
481 utils.ShellQuote(scriptname))
484 def GetFunctionName(name):
485 return "_" + re.sub(r"[^a-z0-9]+", "_", name.lower())
488 def LoadModule(filename):
489 """Loads an external module by filename.
492 (name, ext) = os.path.splitext(filename)
494 fh = open(filename, "U")
496 return imp.load_module(name, fh, filename, (ext, "U", imp.PY_SOURCE))
501 def GetCommands(filename, module):
502 """Returns the commands defined in a module.
504 Aliases are also added as commands.
508 commands = getattr(module, "commands")
509 except AttributeError, err:
510 raise Exception("Script %s doesn't have 'commands' attribute" %
514 aliases = getattr(module, "aliases", {})
516 commands = commands.copy()
517 for name, target in aliases.iteritems():
518 commands[name] = commands[target]
525 sw = ShellWriter(buf)
530 for scriptname in _autoconf.GNT_SCRIPTS:
531 filename = "scripts/%s" % scriptname
533 WriteCompletion(sw, scriptname,
534 GetFunctionName(scriptname),
535 commands=GetCommands(filename, LoadModule(filename)))
538 burnin = LoadModule("tools/burnin")
539 WriteCompletion(sw, "%s/burnin" % constants.TOOLSDIR, "_ganeti_burnin",
540 opts=burnin.OPTIONS, args=burnin.ARGUMENTS)
545 if __name__ == "__main__":