Update client os lists to name+variant format
[ganeti-local] / scripts / gnt-instance
index d0a0c80..062e02b 100755 (executable)
@@ -31,7 +31,6 @@ import time
 from cStringIO import StringIO
 
 from ganeti.cli import *
-from ganeti import cli
 from ganeti import opcodes
 from ganeti import constants
 from ganeti import utils
@@ -175,6 +174,36 @@ def _EnsureInstancesExist(client, names):
       raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name)
 
 
+def GenericManyOps(operation, fn):
+  """Generic multi-instance operations.
+
+  The will return a wrapper that processes the options and arguments
+  given, and uses the passed function to build the opcode needed for
+  the specific operation. Thus all the generic loop/confirmation code
+  is abstracted into this function.
+
+  """
+  def realfn(opts, args):
+    if opts.multi_mode is None:
+      opts.multi_mode = _SHUTDOWN_INSTANCES
+    cl = GetClient()
+    inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
+    if not inames:
+      raise errors.OpPrereqError("Selection filter does not match"
+                                 " any instances")
+    multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
+    if not (opts.force_multi or not multi_on
+            or _ConfirmOperation(inames, operation)):
+      return 1
+    jex = JobExecutor(verbose=multi_on, cl=cl)
+    for name in inames:
+      op = fn(name, opts)
+      jex.QueueJob(name, op)
+    jex.WaitOrShow(not opts.submit_only)
+    return 0
+  return realfn
+
+
 def ListInstances(opts, args):
   """List instances and their properties.
 
@@ -226,7 +255,7 @@ def ListInstances(opts, args):
       "nic.count": "NICs", "nic.ips": "NIC_IPs",
       "nic.modes": "NIC_modes", "nic.links": "NIC_links",
       "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
-      "ctime": "CTime", "mtime": "MTime",
+      "ctime": "CTime", "mtime": "MTime", "uuid": "UUID",
       }
   else:
     headers = None
@@ -282,94 +311,10 @@ def ListInstances(opts, args):
 def AddInstance(opts, args):
   """Add an instance to the cluster.
 
-  @param opts: the command line options selected by the user
-  @type args: list
-  @param args: should contain only one element, the new instance name
-  @rtype: int
-  @return: the desired exit code
+  This is just a wrapper over GenericInstanceCreate.
 
   """
-  instance = args[0]
-
-  (pnode, snode) = SplitNodeOption(opts.node)
-
-  hypervisor = None
-  hvparams = {}
-  if opts.hypervisor:
-    hypervisor, hvparams = opts.hypervisor
-
-  if opts.nics:
-    try:
-      nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
-    except ValueError, err:
-      raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
-    nics = [{}] * nic_max
-    for nidx, ndict in opts.nics:
-      nidx = int(nidx)
-      if not isinstance(ndict, dict):
-        msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
-        raise errors.OpPrereqError(msg)
-      nics[nidx] = ndict
-  elif opts.no_nics:
-    # no nics
-    nics = []
-  else:
-    # default of one nic, all auto
-    nics = [{}]
-
-  if opts.disk_template == constants.DT_DISKLESS:
-    if opts.disks or opts.sd_size is not None:
-      raise errors.OpPrereqError("Diskless instance but disk"
-                                 " information passed")
-    disks = []
-  else:
-    if not opts.disks and not opts.sd_size:
-      raise errors.OpPrereqError("No disk information specified")
-    if opts.disks and opts.sd_size is not None:
-      raise errors.OpPrereqError("Please use either the '--disk' or"
-                                 " '-s' option")
-    if opts.sd_size is not None:
-      opts.disks = [(0, {"size": opts.sd_size})]
-    try:
-      disk_max = max(int(didx[0])+1 for didx in opts.disks)
-    except ValueError, err:
-      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
-    disks = [{}] * disk_max
-    for didx, ddict in opts.disks:
-      didx = int(didx)
-      if not isinstance(ddict, dict):
-        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
-        raise errors.OpPrereqError(msg)
-      elif "size" not in ddict:
-        raise errors.OpPrereqError("Missing size for disk %d" % didx)
-      try:
-        ddict["size"] = utils.ParseUnit(ddict["size"])
-      except ValueError, err:
-        raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
-                                   (didx, err))
-      disks[didx] = ddict
-
-  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
-  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
-
-  op = opcodes.OpCreateInstance(instance_name=instance,
-                                disks=disks,
-                                disk_template=opts.disk_template,
-                                nics=nics,
-                                mode=constants.INSTANCE_CREATE,
-                                os_type=opts.os, pnode=pnode,
-                                snode=snode,
-                                start=opts.start, ip_check=opts.ip_check,
-                                wait_for_sync=opts.wait_for_sync,
-                                hypervisor=hypervisor,
-                                hvparams=hvparams,
-                                beparams=opts.beparams,
-                                iallocator=opts.iallocator,
-                                file_storage_dir=opts.file_storage_dir,
-                                file_driver=opts.file_driver,
-                                )
-
-  SubmitOrSend(op, opts)
+  return GenericInstanceCreate(constants.INSTANCE_CREATE, opts, args)
   return 0
 
 
@@ -443,9 +388,7 @@ def BatchCreate(opts, args):
 
   json_filename = args[0]
   try:
-    fd = open(json_filename, 'r')
-    instance_data = simplejson.load(fd)
-    fd.close()
+    instance_data = simplejson.loads(utils.ReadFile(json_filename))
   except Exception, err:
     ToStderr("Can't parse the instance definition file: %s" % str(err))
     return 1
@@ -538,7 +481,8 @@ def ReinstallInstance(opts, args):
 
   # second, if requested, ask for an OS
   if opts.select_os is True:
-    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
+    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid", "variants"],
+                              names=[])
     result = SubmitOpCode(op)
 
     if not result:
@@ -548,10 +492,12 @@ def ReinstallInstance(opts, args):
     ToStdout("Available OS templates:")
     number = 0
     choices = []
-    for entry in result:
-      ToStdout("%3s: %s", number, entry[0])
-      choices.append(("%s" % number, entry[0], entry[0]))
-      number = number + 1
+    for (name, valid, variants) in result:
+      if valid:
+        for entry in CalculateOSNames(name, variants):
+          ToStdout("%3s: %s", number, entry)
+          choices.append(("%s" % number, entry, entry))
+          number += 1
 
     choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
     selected = AskUser("Enter OS template number (or x to abort):",
@@ -731,109 +677,55 @@ def GrowDisk(opts, args):
   return 0
 
 
-def StartupInstance(opts, args):
+def _StartupInstance(name, opts):
   """Startup instances.
 
-  Depending on the options given, this will start one or more
-  instances.
+  This returns the opcode to start an instance, and its decorator will
+  wrap this into a loop starting all desired instances.
 
+  @param name: the name of the instance to act on
   @param opts: the command line options selected by the user
-  @type args: list
-  @param args: the instance or node names based on which we
-      create the final selection (in conjunction with the
-      opts argument)
-  @rtype: int
-  @return: the desired exit code
+  @return: the opcode needed for the operation
 
   """
-  cl = GetClient()
-  if opts.multi_mode is None:
-    opts.multi_mode = _SHUTDOWN_INSTANCES
-  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
-  if not inames:
-    raise errors.OpPrereqError("Selection filter does not match any instances")
-  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
-  if not (opts.force_multi or not multi_on
-          or _ConfirmOperation(inames, "startup")):
-    return 1
-  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
-  for name in inames:
-    op = opcodes.OpStartupInstance(instance_name=name,
-                                   force=opts.force)
-    # do not add these parameters to the opcode unless they're defined
-    if opts.hvparams:
-      op.hvparams = opts.hvparams
-    if opts.beparams:
-      op.beparams = opts.beparams
-    jex.QueueJob(name, op)
-  jex.WaitOrShow(not opts.submit_only)
-  return 0
+  op = opcodes.OpStartupInstance(instance_name=name,
+                                 force=opts.force)
+  # do not add these parameters to the opcode unless they're defined
+  if opts.hvparams:
+    op.hvparams = opts.hvparams
+  if opts.beparams:
+    op.beparams = opts.beparams
+  return op
 
 
-def RebootInstance(opts, args):
+def _RebootInstance(name, opts):
   """Reboot instance(s).
 
-  Depending on the parameters given, this will reboot one or more
-  instances.
+  This returns the opcode to reboot an instance, and its decorator
+  will wrap this into a loop rebooting all desired instances.
 
+  @param name: the name of the instance to act on
   @param opts: the command line options selected by the user
-  @type args: list
-  @param args: the instance or node names based on which we
-      create the final selection (in conjunction with the
-      opts argument)
-  @rtype: int
-  @return: the desired exit code
+  @return: the opcode needed for the operation
 
   """
-  cl = GetClient()
-  if opts.multi_mode is None:
-    opts.multi_mode = _SHUTDOWN_INSTANCES
-  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
-  if not inames:
-    raise errors.OpPrereqError("Selection filter does not match any instances")
-  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
-  if not (opts.force_multi or not multi_on
-          or _ConfirmOperation(inames, "reboot")):
-    return 1
-  jex = JobExecutor(verbose=multi_on, cl=cl)
-  for name in inames:
-    op = opcodes.OpRebootInstance(instance_name=name,
+  return opcodes.OpRebootInstance(instance_name=name,
                                   reboot_type=opts.reboot_type,
                                   ignore_secondaries=opts.ignore_secondaries)
-    jex.QueueJob(name, op)
-  jex.WaitOrShow(not opts.submit_only)
-  return 0
 
 
-def ShutdownInstance(opts, args):
+def _ShutdownInstance(name, opts):
   """Shutdown an instance.
 
+  This returns the opcode to shutdown an instance, and its decorator
+  will wrap this into a loop shutting down all desired instances.
+
+  @param name: the name of the instance to act on
   @param opts: the command line options selected by the user
-  @type args: list
-  @param args: the instance or node names based on which we
-      create the final selection (in conjunction with the
-      opts argument)
-  @rtype: int
-  @return: the desired exit code
+  @return: the opcode needed for the operation
 
   """
-  cl = GetClient()
-  if opts.multi_mode is None:
-    opts.multi_mode = _SHUTDOWN_INSTANCES
-  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
-  if not inames:
-    raise errors.OpPrereqError("Selection filter does not match any instances")
-  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
-  if not (opts.force_multi or not multi_on
-          or _ConfirmOperation(inames, "shutdown")):
-    return 1
-
-  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
-  for name in inames:
-    op = opcodes.OpShutdownInstance(instance_name=name)
-    jex.QueueJob(name, op)
-  jex.WaitOrShow(not opts.submit_only)
-  return 0
+  return opcodes.OpShutdownInstance(instance_name=name)
 
 
 def ReplaceDisks(opts, args):
@@ -847,7 +739,7 @@ def ReplaceDisks(opts, args):
 
   """
   instance_name = args[0]
-  new_2ndary = opts.new_secondary
+  new_2ndary = opts.dst_node
   iallocator = opts.iallocator
   if opts.disks is None:
     disks = []
@@ -973,7 +865,7 @@ def MoveInstance(opts, args):
       return 1
 
   op = opcodes.OpMoveInstance(instance_name=instance_name,
-                              target_node=opts.target_node)
+                              target_node=opts.node)
   SubmitOrSend(op, opts, cl=cl)
   return 0
 
@@ -1199,6 +1091,7 @@ def ShowInstanceConfig(opts, args):
   for instance_name in result:
     instance = result[instance_name]
     buf.write("Instance name: %s\n" % instance["name"])
+    buf.write("UUID: %s\n" % instance["uuid"])
     buf.write("Serial number: %s\n" % instance["serial_no"])
     buf.write("Creation time: %s\n" % utils.FormatTime(instance["ctime"]))
     buf.write("Modification time: %s\n" % utils.FormatTime(instance["mtime"]))
@@ -1248,7 +1141,7 @@ def ShowInstanceConfig(opts, args):
     buf.write("    - memory: %dMiB\n" %
               instance["be_actual"][constants.BE_MEMORY])
     buf.write("    - NICs:\n")
-    for idx, (mac, ip, mode, link) in enumerate(instance["nics"]):
+    for idx, (ip, mac, mode, link) in enumerate(instance["nics"]):
       buf.write("      - nic/%d: MAC: %s, IP: %s, mode: %s, link: %s\n" %
                 (idx, mac, ip, mode, link))
     buf.write("  Disks:\n")
@@ -1273,7 +1166,7 @@ def SetInstanceParams(opts, args):
 
   """
   if not (opts.nics or opts.disks or
-          opts.hypervisor or opts.beparams):
+          opts.hvparams or opts.beparams):
     ToStderr("Please give at least one of the parameters.")
     return 1
 
@@ -1285,12 +1178,12 @@ def SetInstanceParams(opts, args):
   utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES,
                       allowed_values=[constants.VALUE_DEFAULT])
 
-  for param in opts.hypervisor:
-    if isinstance(opts.hypervisor[param], basestring):
-      if opts.hypervisor[param].lower() == "default":
-        opts.hypervisor[param] = constants.VALUE_DEFAULT
+  for param in opts.hvparams:
+    if isinstance(opts.hvparams[param], basestring):
+      if opts.hvparams[param].lower() == "default":
+        opts.hvparams[param] = constants.VALUE_DEFAULT
 
-  utils.ForceDictType(opts.hypervisor, constants.HVS_PARAMETER_TYPES,
+  utils.ForceDictType(opts.hvparams, constants.HVS_PARAMETER_TYPES,
                       allowed_values=[constants.VALUE_DEFAULT])
 
   for idx, (nic_op, nic_dict) in enumerate(opts.nics):
@@ -1314,7 +1207,7 @@ def SetInstanceParams(opts, args):
   op = opcodes.OpSetInstanceParams(instance_name=args[0],
                                    nics=opts.nics,
                                    disks=opts.disks,
-                                   hvparams=opts.hypervisor,
+                                   hvparams=opts.hvparams,
                                    beparams=opts.beparams,
                                    force=opts.force)
 
@@ -1330,13 +1223,6 @@ def SetInstanceParams(opts, args):
   return 0
 
 
-# options used in more than one cmd
-node_opt = cli_option("-n", "--node", dest="node", help="Target node",
-                      metavar="<node>")
-
-os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
-                    metavar="<os>")
-
 # multi-instance selection options
 m_force_multi = cli_option("--force-multiple", dest="force_multi",
                            help="Do not ask for confirmation when more than"
@@ -1366,291 +1252,135 @@ m_inst_opt = cli_option("--instance", dest="multi_mode",
 
 # this is defined separately due to readability only
 add_opts = [
-  DEBUG_OPT,
-  cli_option("-n", "--node", dest="node",
-             help="Target node and optional secondary node",
-             metavar="<pnode>[:<snode>]"),
-  os_opt,
-  cli_option("-B", "--backend", dest="beparams",
-             type="keyval", default={},
-             help="Backend parameters"),
-  cli_option("-t", "--disk-template", dest="disk_template",
-             help="Custom disk setup (diskless, file, plain or drbd)",
-             default=None, metavar="TEMPL",
-             choices=list(constants.DISK_TEMPLATES)),
-  cli_option("-s", "--os-size", dest="sd_size", help="Disk size for a"
-             " single-disk configuration, when not using the --disk option,"
-             " in MiB unless a suffix is used",
-             default=None, type="unit", metavar="<size>"),
-  cli_option("--disk", help="Disk information",
-             default=[], dest="disks",
-             action="append",
-             type="identkeyval"),
-  cli_option("--net", help="NIC information",
-             default=[], dest="nics",
-             action="append",
-             type="identkeyval"),
-  cli_option("--no-nics", default=False, action="store_true",
-             help="Do not create any network cards for the instance"),
-  cli_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
-             action="store_false", help="Don't wait for sync (DANGEROUS!)"),
-  cli_option("--no-start", dest="start", default=True,
-             action="store_false", help="Don't start the instance after"
-             " creation"),
-  cli_option("--no-ip-check", dest="ip_check", default=True,
-             action="store_false", help="Don't check that the instance's IP"
-             " is alive (only valid with --no-start)"),
-  cli_option("--file-storage-dir", dest="file_storage_dir",
-             help="Relative path under default cluster-wide file storage dir"
-             " to store file-based disks", default=None,
-             metavar="<DIR>"),
-  cli_option("--file-driver", dest="file_driver", help="Driver to use"
-             " for image files", default="loop", metavar="<DRIVER>",
-             choices=list(constants.FILE_DRIVER)),
-  cli_option("-I", "--iallocator", metavar="<NAME>",
-             help="Select nodes for the instance automatically using the"
-             " <NAME> iallocator plugin", default=None, type="string"),
-  cli_option("-H", "--hypervisor", dest="hypervisor",
-             help="Hypervisor and hypervisor options, in the format"
-             " hypervisor:option=value,option=value,...", default=None,
-             type="identkeyval"),
+  BACKEND_OPT,
+  DISK_OPT,
+  DISK_TEMPLATE_OPT,
+  FILESTORE_DIR_OPT,
+  FILESTORE_DRIVER_OPT,
+  HYPERVISOR_OPT,
+  IALLOCATOR_OPT,
+  NET_OPT,
+  NODE_PLACEMENT_OPT,
+  NOIPCHECK_OPT,
+  NONICS_OPT,
+  NOSTART_OPT,
+  NWSYNC_OPT,
+  OS_OPT,
+  OS_SIZE_OPT,
   SUBMIT_OPT,
   ]
 
 commands = {
-  'add': (AddInstance, [ArgHost(min=1, max=1)], add_opts,
-          "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
-          "Creates and adds a new instance to the cluster"),
-  'batch-create': (BatchCreate, [ArgFile(min=1, max=1)],
-                   [DEBUG_OPT],
-                   "<instances_file.json>",
-                   "Create a bunch of instances based on specs in the file."),
-  'console': (ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
-              [DEBUG_OPT,
-               cli_option("--show-cmd", dest="show_command",
-                          action="store_true", default=False,
-                          help=("Show command instead of executing it"))],
-              "[--show-cmd] <instance>",
-              "Opens a console on the specified instance"),
-  'failover': (FailoverInstance, ARGS_ONE_INSTANCE,
-               [DEBUG_OPT, FORCE_OPT,
-                cli_option("--ignore-consistency", dest="ignore_consistency",
-                           action="store_true", default=False,
-                           help="Ignore the consistency of the disks on"
-                           " the secondary"),
-                SUBMIT_OPT,
-                ],
-               "[-f] <instance>",
-               "Stops the instance and starts it on the backup node, using"
-               " the remote mirror (only for instances of type drbd)"),
-  'migrate': (MigrateInstance, ARGS_ONE_INSTANCE,
-               [DEBUG_OPT, FORCE_OPT,
-                cli_option("--non-live", dest="live",
-                           default=True, action="store_false",
-                           help="Do a non-live migration (this usually means"
-                           " freeze the instance, save the state,"
-                           " transfer and only then resume running on the"
-                           " secondary node)"),
-                cli_option("--cleanup", dest="cleanup",
-                           default=False, action="store_true",
-                           help="Instead of performing the migration, try to"
-                           " recover from a failed cleanup. This is safe"
-                           " to run even if the instance is healthy, but it"
-                           " will create extra replication traffic and "
-                           " disrupt briefly the replication (like during the"
-                           " migration"),
-                ],
-               "[-f] <instance>",
-               "Migrate instance to its secondary node"
-               " (only for instances of type drbd)"),
-  'move': (MoveInstance, ARGS_ONE_INSTANCE,
-           [DEBUG_OPT, FORCE_OPT, SUBMIT_OPT,
-            cli_option("-n", "--new-node", dest="target_node",
-                       help="Destinattion node", metavar="NODE",
-                       default=None),
-            ],
-           "[-f] <instance>",
-           "Move instance to an arbitrary node"
-           " (only for instances of type file and lv)"),
-  'info': (ShowInstanceConfig, ARGS_MANY_INSTANCES,
-           [DEBUG_OPT,
-            cli_option("-s", "--static", dest="static",
-                       action="store_true", default=False,
-                       help="Only show configuration data, not runtime data"),
-            cli_option("--all", dest="show_all",
-                       default=False, action="store_true",
-                       help="Show info on all instances on the cluster."
-                       " This can take a long time to run, use wisely."),
-            ], "[-s] {--all | <instance>...}",
-           "Show information on the specified instance(s)"),
-  'list': (ListInstances, ARGS_MANY_INSTANCES,
-           [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
-           "[<instance>...]",
-           "Lists the instances and their status. The available fields are"
-           " (see the man page for details): status, oper_state, oper_ram,"
-           " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
-           " ip, mac, mode, link, sda_size, sdb_size, vcpus, serial_no,"
-           " hypervisor."
-           " The default field"
-           " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
-           ),
-  'reinstall': (ReinstallInstance, [ArgInstance(min=1)],
-                [DEBUG_OPT, FORCE_OPT, os_opt,
-                 m_force_multi,
-                 m_node_opt, m_pri_node_opt, m_sec_node_opt,
-                 m_clust_opt, m_inst_opt,
-                 cli_option("--select-os", dest="select_os",
-                            action="store_true", default=False,
-                            help="Interactive OS reinstall, lists available"
-                            " OS templates for selection"),
-                 SUBMIT_OPT,
-                 ],
-                "[-f] <instance>", "Reinstall a stopped instance"),
-  'remove': (RemoveInstance, ARGS_ONE_INSTANCE,
-             [DEBUG_OPT, FORCE_OPT,
-              cli_option("--ignore-failures", dest="ignore_failures",
-                         action="store_true", default=False,
-                         help=("Remove the instance from the cluster even"
-                               " if there are failures during the removal"
-                               " process (shutdown, disk removal, etc.)")),
-              SUBMIT_OPT,
-              ],
-             "[-f] <instance>", "Shuts down the instance and removes it"),
-  'rename': (RenameInstance,
-             [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
-             [DEBUG_OPT,
-              cli_option("--no-ip-check", dest="ignore_ip",
-                         help="Do not check that the IP of the new name"
-                         " is alive",
-                         default=False, action="store_true"),
-              SUBMIT_OPT,
-              ],
-             "<instance> <new_name>", "Rename the instance"),
-  'replace-disks': (ReplaceDisks, ARGS_ONE_INSTANCE,
-                    [DEBUG_OPT,
-                     cli_option("-n", "--new-secondary", dest="new_secondary",
-                                help=("New secondary node (for secondary"
-                                      " node change)"), metavar="NODE",
-                                default=None),
-                     cli_option("-p", "--on-primary", dest="on_primary",
-                                default=False, action="store_true",
-                                help=("Replace the disk(s) on the primary"
-                                      " node (only for the drbd template)")),
-                     cli_option("-s", "--on-secondary", dest="on_secondary",
-                                default=False, action="store_true",
-                                help=("Replace the disk(s) on the secondary"
-                                      " node (only for the drbd template)")),
-                     cli_option("-a", "--auto", dest="auto",
-                                default=False, action="store_true",
-                                help=("Automatically replace faulty disks"
-                                      " (only for the drbd template)")),
-                     cli_option("--disks", dest="disks", default=None,
-                                help="Comma-separated list of disks"
-                                " indices to replace (e.g. 0,2) (optional,"
-                                " defaults to all disks)"),
-                     cli_option("-I", "--iallocator", metavar="<NAME>",
-                                help="Select new secondary for the instance"
-                                " automatically using the"
-                                " <NAME> iallocator plugin (enables"
-                                " secondary node replacement)",
-                                default=None, type="string"),
-                     SUBMIT_OPT,
-                     ],
-                    "[-s|-p|-n NODE|-I NAME] <instance>",
-                    "Replaces all disks for the instance"),
-  'modify': (SetInstanceParams, ARGS_ONE_INSTANCE,
-             [DEBUG_OPT, FORCE_OPT,
-              cli_option("-H", "--hypervisor", type="keyval",
-                         default={}, dest="hypervisor",
-                         help="Change hypervisor parameters"),
-              cli_option("-B", "--backend", type="keyval",
-                         default={}, dest="beparams",
-                         help="Change backend parameters"),
-              cli_option("--disk", help="Disk changes",
-                         default=[], dest="disks",
-                         action="append",
-                         type="identkeyval"),
-              cli_option("--net", help="NIC changes",
-                         default=[], dest="nics",
-                         action="append",
-                         type="identkeyval"),
-              SUBMIT_OPT,
-              ],
-             "<instance>", "Alters the parameters of an instance"),
-  'shutdown': (ShutdownInstance, [ArgInstance(min=1)],
-               [DEBUG_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt,
-                m_clust_opt, m_inst_opt, m_force_multi,
-                SUBMIT_OPT,
-                ],
-               "<instance>", "Stops an instance"),
-  'startup': (StartupInstance, [ArgInstance(min=1)],
-              [DEBUG_OPT, FORCE_OPT, m_force_multi,
-               m_node_opt, m_pri_node_opt, m_sec_node_opt,
-               m_clust_opt, m_inst_opt,
-               SUBMIT_OPT,
-               cli_option("-H", "--hypervisor", type="keyval",
-                          default={}, dest="hvparams",
-                          help="Temporary hypervisor parameters"),
-               cli_option("-B", "--backend", type="keyval",
-                          default={}, dest="beparams",
-                          help="Temporary backend parameters"),
-               ],
-              "<instance>", "Starts an instance"),
-  'reboot': (RebootInstance, [ArgInstance(min=1)],
-              [DEBUG_OPT, m_force_multi,
-               cli_option("-t", "--type", dest="reboot_type",
-                          help="Type of reboot: soft/hard/full",
-                          default=constants.INSTANCE_REBOOT_HARD,
-                          type="string", metavar="<REBOOT>"),
-               cli_option("--ignore-secondaries", dest="ignore_secondaries",
-                          default=False, action="store_true",
-                          help="Ignore errors from secondaries"),
-               m_node_opt, m_pri_node_opt, m_sec_node_opt,
-               m_clust_opt, m_inst_opt,
-               SUBMIT_OPT,
-               ],
-            "<instance>", "Reboots an instance"),
-  'activate-disks': (ActivateDisks, ARGS_ONE_INSTANCE,
-                     [DEBUG_OPT, SUBMIT_OPT,
-                      cli_option("--ignore-size", dest="ignore_size",
-                                 default=False, action="store_true",
-                                 help="Ignore current recorded size"
-                                 " (useful for forcing activation when"
-                                 " the recorded size is wrong)"),
-                      ],
-                     "<instance>",
-                     "Activate an instance's disks"),
-  'deactivate-disks': (DeactivateDisks, ARGS_ONE_INSTANCE,
-                       [DEBUG_OPT, SUBMIT_OPT],
-                       "<instance>",
-                       "Deactivate an instance's disks"),
-  'recreate-disks': (RecreateDisks, ARGS_ONE_INSTANCE,
-                     [DEBUG_OPT, SUBMIT_OPT,
-                     cli_option("--disks", dest="disks", default=None,
-                                help="Comma-separated list of disks"
-                                " indices to replace (e.g. 0,2) (optional,"
-                                " defaults to all disks)"),
-                      ],
-                     "<instance>",
-                     "Recreate an instance's disks"),
-  'grow-disk': (GrowDisk,
-                [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
-                 ArgUnknown(min=1, max=1)],
-                [DEBUG_OPT, SUBMIT_OPT,
-                 cli_option("--no-wait-for-sync",
-                            dest="wait_for_sync", default=True,
-                            action="store_false",
-                            help="Don't wait for sync (DANGEROUS!)"),
-                 ],
-                "<instance> <disk> <size>", "Grow an instance's disk"),
-  'list-tags': (ListTags, ARGS_ONE_INSTANCE, [DEBUG_OPT],
-                "<instance_name>", "List the tags of the given instance"),
-  'add-tags': (AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
-               [DEBUG_OPT, TAG_SRC_OPT],
-               "<instance_name> tag...", "Add tags to the given instance"),
-  'remove-tags': (RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
-                  [DEBUG_OPT, TAG_SRC_OPT],
-                  "<instance_name> tag...", "Remove tags from given instance"),
+  'add': (
+    AddInstance, [ArgHost(min=1, max=1)], add_opts,
+    "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
+    "Creates and adds a new instance to the cluster"),
+  'batch-create': (
+    BatchCreate, [ArgFile(min=1, max=1)], [],
+    "<instances.json>",
+    "Create a bunch of instances based on specs in the file."),
+  'console': (
+    ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
+    [SHOWCMD_OPT],
+    "[--show-cmd] <instance>", "Opens a console on the specified instance"),
+  'failover': (
+    FailoverInstance, ARGS_ONE_INSTANCE,
+    [FORCE_OPT, IGNORE_CONSIST_OPT, SUBMIT_OPT],
+    "[-f] <instance>", "Stops the instance and starts it on the backup node,"
+    " using the remote mirror (only for instances of type drbd)"),
+  'migrate': (
+    MigrateInstance, ARGS_ONE_INSTANCE,
+    [FORCE_OPT, NONLIVE_OPT, CLEANUP_OPT],
+    "[-f] <instance>", "Migrate instance to its secondary node"
+    " (only for instances of type drbd)"),
+  'move': (
+    MoveInstance, ARGS_ONE_INSTANCE,
+    [FORCE_OPT, SUBMIT_OPT, SINGLE_NODE_OPT],
+    "[-f] <instance>", "Move instance to an arbitrary node"
+    " (only for instances of type file and lv)"),
+  'info': (
+    ShowInstanceConfig, ARGS_MANY_INSTANCES,
+    [STATIC_OPT, ALL_OPT],
+    "[-s] {--all | <instance>...}",
+    "Show information on the specified instance(s)"),
+  'list': (
+    ListInstances, ARGS_MANY_INSTANCES,
+    [NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
+    "[<instance>...]",
+    "Lists the instances and their status. The available fields are"
+    " (see the man page for details): status, oper_state, oper_ram,"
+    " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
+    " ip, mac, mode, link, sda_size, sdb_size, vcpus, serial_no,"
+    " hypervisor."
+    " The default field"
+    " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
+    ),
+  'reinstall': (
+    ReinstallInstance, [ArgInstance()],
+    [FORCE_OPT, OS_OPT, m_force_multi, m_node_opt, m_pri_node_opt,
+     m_sec_node_opt, m_clust_opt, m_inst_opt, SELECT_OS_OPT, SUBMIT_OPT],
+    "[-f] <instance>", "Reinstall a stopped instance"),
+  'remove': (
+    RemoveInstance, ARGS_ONE_INSTANCE,
+    [FORCE_OPT, IGNORE_FAILURES_OPT, SUBMIT_OPT],
+    "[-f] <instance>", "Shuts down the instance and removes it"),
+  'rename': (
+    RenameInstance,
+    [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
+    [NOIPCHECK_OPT, SUBMIT_OPT],
+    "<instance> <new_name>", "Rename the instance"),
+  'replace-disks': (
+    ReplaceDisks, ARGS_ONE_INSTANCE,
+    [AUTO_REPLACE_OPT, DISKIDX_OPT, IALLOCATOR_OPT,
+     NEW_SECONDARY_OPT, ON_PRIMARY_OPT, ON_SECONDARY_OPT, SUBMIT_OPT],
+    "[-s|-p|-n NODE|-I NAME] <instance>",
+    "Replaces all disks for the instance"),
+  'modify': (
+    SetInstanceParams, ARGS_ONE_INSTANCE,
+    [BACKEND_OPT, DISK_OPT, FORCE_OPT, HVOPTS_OPT, NET_OPT, SUBMIT_OPT],
+    "<instance>", "Alters the parameters of an instance"),
+  'shutdown': (
+    GenericManyOps("shutdown", _ShutdownInstance), [ArgInstance()],
+    [m_node_opt, m_pri_node_opt, m_sec_node_opt, m_clust_opt,
+     m_inst_opt, m_force_multi, SUBMIT_OPT],
+    "<instance>", "Stops an instance"),
+  'startup': (
+    GenericManyOps("startup", _StartupInstance), [ArgInstance()],
+    [FORCE_OPT, m_force_multi, m_node_opt, m_pri_node_opt,
+     m_sec_node_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT, HVOPTS_OPT,
+     BACKEND_OPT],
+    "<instance>", "Starts an instance"),
+  'reboot': (
+    GenericManyOps("reboot", _RebootInstance), [ArgInstance()],
+    [m_force_multi, REBOOT_TYPE_OPT, IGNORE_SECONDARIES_OPT, m_node_opt,
+     m_pri_node_opt, m_sec_node_opt, m_clust_opt, m_inst_opt, SUBMIT_OPT],
+    "<instance>", "Reboots an instance"),
+  'activate-disks': (
+    ActivateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT, IGNORE_SIZE_OPT],
+    "<instance>", "Activate an instance's disks"),
+  'deactivate-disks': (
+    DeactivateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT],
+    "<instance>", "Deactivate an instance's disks"),
+  'recreate-disks': (
+    RecreateDisks, ARGS_ONE_INSTANCE, [SUBMIT_OPT, DISKIDX_OPT],
+    "<instance>", "Recreate an instance's disks"),
+  'grow-disk': (
+    GrowDisk,
+    [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
+     ArgUnknown(min=1, max=1)],
+    [SUBMIT_OPT, NWSYNC_OPT],
+    "<instance> <disk> <size>", "Grow an instance's disk"),
+  'list-tags': (
+    ListTags, ARGS_ONE_INSTANCE, [],
+    "<instance_name>", "List the tags of the given instance"),
+  'add-tags': (
+    AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
+    [TAG_SRC_OPT],
+    "<instance_name> tag...", "Add tags to the given instance"),
+  'remove-tags': (
+    RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
+    [TAG_SRC_OPT],
+    "<instance_name> tag...", "Remove tags from given instance"),
   }
 
 #: dictionary with aliases for commands