Implement --dry-run for cfgupgrade.
[ganeti-local] / scripts / gnt-instance
index 45f6795..4dcf7b1 100755 (executable)
@@ -22,7 +22,6 @@
 import sys
 import os
 from optparse import make_option
 import sys
 import os
 from optparse import make_option
-import textwrap
 from cStringIO import StringIO
 
 from ganeti.cli import *
 from cStringIO import StringIO
 
 from ganeti.cli import *
@@ -45,52 +44,26 @@ def ListInstances(opts, args):
   op = opcodes.OpQueryInstances(output_fields=selected_fields)
   output = SubmitOpCode(op)
 
   op = opcodes.OpQueryInstances(output_fields=selected_fields)
   output = SubmitOpCode(op)
 
-  mlens = [0 for name in selected_fields]
+  if not opts.no_headers:
+    headers = {"name": "Instance", "os": "OS", "pnode": "Primary_node",
+               "snodes": "Secondary_Nodes", "admin_state": "Autostart",
+               "oper_state": "Status", "admin_ram": "Configured_memory",
+               "oper_ram": "Memory", "disk_template": "Disk_template",
+               "ip": "IP Address", "mac": "MAC Address",
+               "bridge": "Bridge"}
+  else:
+    headers = None
 
 
-  format_fields = []
-  unitformat_fields = ("admin_ram", "oper_ram")
-  for field in selected_fields:
-    if field in ("admin_ram", "oper_ram"):
-      format_fields.append("%*s")
-    else:
-      format_fields.append("%-*s")
-  separator = opts.separator
-  if "%" in separator:
-    separator = separator.replace("%", "%%")
-  format = separator.join(format_fields)
-
-  for row in output:
-    for idx, val in enumerate(row):
-      if opts.human_readable and selected_fields[idx] in unitformat_fields:
-        try:
-          val = int(val)
-        except ValueError:
-          pass
-        else:
-          val = row[idx] = utils.FormatUnit(val)
-      mlens[idx] = max(mlens[idx], len(val))
+  if opts.human_readable:
+    unitfields = ["admin_ram", "oper_ram"]
+  else:
+    unitfields = None
 
 
-  if not opts.no_headers:
-    header_list = {"name": "Instance", "os": "OS", "pnode": "Primary_node",
-                   "snodes": "Secondary_Nodes", "admin_state": "Autostart",
-                   "oper_state": "Status", "admin_ram": "Configured_memory",
-                   "oper_ram": "Memory", "disk_template": "Disk_template",
-                   "ip": "IP Address", "mac": "MAC Address",
-                   "bridge": "Bridge"}
-    args = []
-    for idx, name in enumerate(selected_fields):
-      hdr = header_list[name]
-      mlens[idx] = max(mlens[idx], len(hdr))
-      args.append(mlens[idx])
-      args.append(hdr)
-    logger.ToStdout(format % tuple(args))
-
-  for line in output:
-    args = []
-    for idx in range(len(selected_fields)):
-      args.append(mlens[idx])
-      args.append(line[idx])
-    logger.ToStdout(format % tuple(args))
+  numfields = ["admin_ram", "oper_ram"]
+
+  OutputTable(separator=opts.separator, headers=headers,
+      fields=selected_fields, unitfields=unitfields,
+      numfields=numfields, data=output)
 
   return 0
 
 
   return 0
 
@@ -108,7 +81,6 @@ def AddInstance(opts, args):
     node - node to run new instance on
 
   """
     node - node to run new instance on
 
   """
-
   instance = args[0]
 
   op = opcodes.OpCreateInstance(instance_name=instance, mem_size=opts.mem,
   instance = args[0]
 
   op = opcodes.OpCreateInstance(instance_name=instance, mem_size=opts.mem,
@@ -123,6 +95,29 @@ def AddInstance(opts, args):
   return 0
 
 
   return 0
 
 
+def ReinstallInstance(opts, args):
+  """Reinstall an instance.
+
+  Args:
+    opts - class with options as members
+    args - list containing a single element, the instance name
+
+  """
+  instance_name = args[0]
+
+  if not opts.force:
+    usertext = ("This will reinstall the instance %s and remove "
+                "all data. Continue?") % instance_name
+    if not opts._ask_user(usertext):
+      return 1
+
+  op = opcodes.OpReinstallInstance(instance_name=instance_name,
+                                   os_type=opts.os)
+  SubmitOpCode(op)
+
+  return 0
+
+
 def RemoveInstance(opts, args):
   """Remove an instance.
 
 def RemoveInstance(opts, args):
   """Remove an instance.
 
@@ -221,7 +216,7 @@ def AddMDDRBDComponent(opts, args):
 
 
 def RemoveMDDRBDComponent(opts, args):
 
 
 def RemoveMDDRBDComponent(opts, args):
-  """Connect to the console of an instance
+  """Remove a component from a remote_raid1 disk.
 
   Args:
     opts - class with options as members
 
   Args:
     opts - class with options as members
@@ -271,7 +266,6 @@ def FailoverInstance(opts, args):
     usertext = ("Failover will happen to image %s."
                 " This requires a shutdown of the instance. Continue?" %
                 (instance_name,))
     usertext = ("Failover will happen to image %s."
                 " This requires a shutdown of the instance. Continue?" %
                 (instance_name,))
-    usertext = textwrap.fill(usertext)
     if not opts._ask_user(usertext):
       return 1
 
     if not opts._ask_user(usertext):
       return 1
 
@@ -359,7 +353,6 @@ def ShowInstanceConfig(opts, args):
   """Compute instance run-time status.
 
   """
   """Compute instance run-time status.
 
   """
-
   retcode = 0
   op = opcodes.OpQueryInstanceData(instances=args)
   result = SubmitOpCode(op)
   retcode = 0
   op = opcodes.OpQueryInstanceData(instances=args)
   result = SubmitOpCode(op)
@@ -428,8 +421,9 @@ def SetInstanceParms(opts, args):
 # options used in more than one cmd
 node_opt = make_option("-n", "--node", dest="node", help="Target node",
                        metavar="<node>")
 # options used in more than one cmd
 node_opt = make_option("-n", "--node", dest="node", help="Target node",
                        metavar="<node>")
-force_opt = make_option("-f", "--force", dest="force", action="store_true",
-                        default=False, help="Force the operation")
+
+os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
+                    metavar="<os>")
 
 # this is defined separately due to readability only
 add_opts = [
 
 # this is defined separately due to readability only
 add_opts = [
@@ -439,8 +433,7 @@ add_opts = [
              default=20 * 1024, type="unit", metavar="<size>"),
   cli_option("--swap-size", dest="swap", help="Swap size",
              default=4 * 1024, type="unit", metavar="<size>"),
              default=20 * 1024, type="unit", metavar="<size>"),
   cli_option("--swap-size", dest="swap", help="Swap size",
              default=4 * 1024, type="unit", metavar="<size>"),
-  cli_option("-o", "--os-type", dest="os", help="What OS to run",
-             metavar="<os>"),
+  os_opt,
   cli_option("-m", "--memory", dest="mem", help="Memory size",
               default=128, type="unit", metavar="<mem>"),
   make_option("-p", "--cpu", dest="vcpus", help="Number of virtual CPUs",
   cli_option("-m", "--memory", dest="mem", help="Memory size",
               default=128, type="unit", metavar="<mem>"),
   make_option("-p", "--cpu", dest="vcpus", help="Number of virtual CPUs",
@@ -461,7 +454,6 @@ add_opts = [
               default=None, metavar="<bridge>")
   ]
 
               default=None, metavar="<bridge>")
   ]
 
-
 commands = {
   'add': (AddInstance, ARGS_ONE, add_opts,
           "[opts...] <name>",
 commands = {
   'add': (AddInstance, ARGS_ONE, add_opts,
           "[opts...] <name>",
@@ -477,7 +469,7 @@ commands = {
               "<instance>",
               "Opens a console on the specified instance"),
   'failover': (FailoverInstance, ARGS_ONE,
               "<instance>",
               "Opens a console on the specified instance"),
   'failover': (FailoverInstance, ARGS_ONE,
-               [DEBUG_OPT, force_opt,
+               [DEBUG_OPT, FORCE_OPT,
                 make_option("--ignore-consistency", dest="ignore_consistency",
                             action="store_true", default=False,
                             help="Ignore the consistency of the disks on"
                 make_option("--ignore-consistency", dest="ignore_consistency",
                             action="store_true", default=False,
                             help="Ignore the consistency of the disks on"
@@ -491,7 +483,9 @@ commands = {
   'list': (ListInstances, ARGS_NONE,
            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
            "", "Lists the instances and their status"),
   'list': (ListInstances, ARGS_NONE,
            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
            "", "Lists the instances and their status"),
-  'remove': (RemoveInstance, ARGS_ONE, [DEBUG_OPT, force_opt],
+  'reinstall': (ReinstallInstance, ARGS_ONE, [DEBUG_OPT, FORCE_OPT, os_opt],
+                "[-f] <instance>", "Reinstall the instance"),
+  'remove': (RemoveInstance, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
              "[-f] <instance>", "Shuts down the instance and removes it"),
   'remove-mirror': (RemoveMDDRBDComponent, ARGS_ONE,
                    [DEBUG_OPT, node_opt,
              "[-f] <instance>", "Shuts down the instance and removes it"),
   'remove-mirror': (RemoveMDDRBDComponent, ARGS_ONE,
                    [DEBUG_OPT, node_opt,
@@ -513,9 +507,8 @@ commands = {
                                        " change the secondary)"))],
                     "[-n NODE] <instance>",
                     "Replaces all disks for the instance"),
                                        " change the secondary)"))],
                     "[-n NODE] <instance>",
                     "Replaces all disks for the instance"),
-
   'modify': (SetInstanceParms, ARGS_ONE,
   'modify': (SetInstanceParms, ARGS_ONE,
-             [DEBUG_OPT, force_opt,
+             [DEBUG_OPT, FORCE_OPT,
               cli_option("-m", "--memory", dest="mem",
                          help="Memory size",
                          default=None, type="unit", metavar="<mem>"),
               cli_option("-m", "--memory", dest="mem",
                          help="Memory size",
                          default=None, type="unit", metavar="<mem>"),
@@ -533,7 +526,7 @@ commands = {
   'shutdown': (ShutdownInstance, ARGS_ONE, [DEBUG_OPT],
                "<instance>", "Stops an instance"),
   'startup': (StartupInstance, ARGS_ONE,
   'shutdown': (ShutdownInstance, ARGS_ONE, [DEBUG_OPT],
                "<instance>", "Stops an instance"),
   'startup': (StartupInstance, ARGS_ONE,
-              [DEBUG_OPT, force_opt,
+              [DEBUG_OPT, FORCE_OPT,
                make_option("-e", "--extra", dest="extra_args",
                            help="Extra arguments for the instance's kernel",
                            default=None, type="string", metavar="<PARAMS>"),
                make_option("-e", "--extra", dest="extra_args",
                            help="Extra arguments for the instance's kernel",
                            default=None, type="string", metavar="<PARAMS>"),