Unify the “--no-nics” option
[ganeti-local] / scripts / gnt-node
index c2b2f88..ed667ba 100755 (executable)
@@ -24,7 +24,6 @@
 # W0614: Unused import %s from wildcard import (since we need cli)
 
 import sys
-from optparse import make_option
 
 from ganeti.cli import *
 from ganeti import cli
@@ -57,8 +56,41 @@ _LIST_HEADERS = {
   "master": "IsMaster",
   "offline": "Offline", "drained": "Drained",
   "role": "Role",
+  "ctime": "CTime", "mtime": "MTime",
   }
 
+#: User-facing storage unit types
+_USER_STORAGE_TYPE = {
+  constants.ST_FILE: "file",
+  constants.ST_LVM_PV: "lvm-pv",
+  constants.ST_LVM_VG: "lvm-vg",
+  }
+
+_STORAGE_TYPE_OPT = \
+  cli_option("--storage-type",
+             dest="user_storage_type",
+             choices=_USER_STORAGE_TYPE.keys(),
+             default=None,
+             metavar="STORAGE_TYPE",
+             help=("Storage type (%s)" %
+                   utils.CommaJoin(_USER_STORAGE_TYPE.keys())))
+
+_REPAIRABLE_STORAGE_TYPES = \
+  [st for st, so in constants.VALID_STORAGE_OPERATIONS.iteritems()
+   if constants.SO_FIX_CONSISTENCY in so]
+
+_MODIFIABLE_STORAGE_TYPES = constants.MODIFIABLE_STORAGE_FIELDS.keys()
+
+
+def ConvertStorageType(user_storage_type):
+  """Converts a user storage type to its internal name.
+
+  """
+  try:
+    return _USER_STORAGE_TYPE[user_storage_type]
+  except KeyError:
+    raise errors.OpPrereqError("Unknown storage type: %s" % user_storage_type)
+
 
 @UsesRPC
 def AddNode(opts, args):
@@ -158,6 +190,8 @@ def ListNodes(opts, args):
           val = 'Y'
         else:
           val = 'N'
+      elif field == "ctime" or field == "mtime":
+        val = utils.FormatTime(val)
       elif val is None:
         val = "?"
       row[idx] = str(val)
@@ -189,7 +223,7 @@ def EvacuateNode(opts, args):
 
   cnt = [dst_node, iallocator].count(None)
   if cnt != 1:
-    raise errors.OpPrereqError("One and only one of the -n and -i"
+    raise errors.OpPrereqError("One and only one of the -n and -I"
                                " options must be passed")
 
   selected_fields = ["name", "sinst_list"]
@@ -224,17 +258,9 @@ def EvacuateNode(opts, args):
                                src_node, txt_msg)):
     return constants.EXIT_CONFIRMATION
 
-  ops = []
-  for iname in sinst:
-    op = opcodes.OpReplaceDisks(instance_name=iname,
-                                remote_node=dst_node,
-                                mode=constants.REPLACE_DISK_CHG,
-                                iallocator=iallocator,
-                                disks=[])
-    ops.append(op)
-
-  job_id = cli.SendJob(ops, cl=cl)
-  cli.PollJob(job_id, cl=cl)
+  op = opcodes.OpEvacuateNode(node_name=args[0], remote_node=dst_node,
+                              iallocator=iallocator)
+  SubmitOpCode(op, cl=cl)
 
 
 def FailoverNode(opts, args):
@@ -307,20 +333,8 @@ def MigrateNode(opts, args):
                                (",".join("'%s'" % name for name in pinst))):
     return 2
 
-  jex = JobExecutor(cl=cl)
-  for iname in pinst:
-    op = opcodes.OpMigrateInstance(instance_name=iname, live=opts.live,
-                                   cleanup=False)
-    jex.QueueJob(iname, op)
-
-  results = jex.GetResults()
-  bad_cnt = len([row for row in results if not row[0]])
-  if bad_cnt == 0:
-    ToStdout("All %d instance(s) migrated successfully.", len(results))
-  else:
-    ToStdout("There were errors during the migration:\n"
-             "%d error(s) out of %d instance(s).", bad_cnt, len(results))
-  return retcode
+  op = opcodes.OpMigrateNode(node_name=args[0], live=opts.live)
+  SubmitOpCode(op, cl=cl)
 
 
 def ShowNodeConfig(opts, args):
@@ -445,6 +459,125 @@ def ListVolumes(opts, args):
   return 0
 
 
+def ListPhysicalVolumes(opts, args):
+  """List physical volumes on node(s).
+
+  @param opts: the command line options selected by the user
+  @type args: list
+  @param args: should either be an empty list, in which case
+      we list data for all nodes, or contain a list of nodes
+      to display data only for those
+  @rtype: int
+  @return: the desired exit code
+
+  """
+  # TODO: Default to ST_FILE if LVM is disabled on the cluster
+  if opts.user_storage_type is None:
+    opts.user_storage_type = constants.ST_LVM_PV
+
+  storage_type = ConvertStorageType(opts.user_storage_type)
+
+  default_fields = {
+    constants.ST_FILE: [
+      constants.SF_NAME,
+      constants.SF_USED,
+      constants.SF_FREE,
+      ],
+    constants.ST_LVM_PV: [
+      constants.SF_NAME,
+      constants.SF_SIZE,
+      constants.SF_USED,
+      constants.SF_FREE,
+      ],
+    constants.ST_LVM_VG: [
+      constants.SF_NAME,
+      constants.SF_SIZE,
+      ],
+  }
+
+  if opts.output is None:
+    selected_fields = ["node"]
+    selected_fields.extend(default_fields[storage_type])
+  else:
+    selected_fields = opts.output.split(",")
+
+  op = opcodes.OpQueryNodeStorage(nodes=args,
+                                  storage_type=storage_type,
+                                  output_fields=selected_fields)
+  output = SubmitOpCode(op)
+
+  if not opts.no_headers:
+    headers = {
+      "node": "Node",
+      constants.SF_NAME: "Name",
+      constants.SF_SIZE: "Size",
+      constants.SF_USED: "Used",
+      constants.SF_FREE: "Free",
+      constants.SF_ALLOCATABLE: "Allocatable",
+      }
+  else:
+    headers = None
+
+  unitfields = [constants.SF_SIZE, constants.SF_USED, constants.SF_FREE]
+  numfields = [constants.SF_SIZE, constants.SF_USED, constants.SF_FREE]
+
+  data = GenerateTable(separator=opts.separator, headers=headers,
+                       fields=selected_fields, unitfields=unitfields,
+                       numfields=numfields, data=output, units=opts.units)
+
+  for line in data:
+    ToStdout(line)
+
+  return 0
+
+
+def ModifyVolume(opts, args):
+  """Modify storage volume on a node.
+
+  @param opts: the command line options selected by the user
+  @type args: list
+  @param args: should contain 3 items: node name, storage type and volume name
+  @rtype: int
+  @return: the desired exit code
+
+  """
+  (node_name, user_storage_type, volume_name) = args
+
+  storage_type = ConvertStorageType(user_storage_type)
+
+  changes = {}
+
+  if opts.allocatable is not None:
+    changes[constants.SF_ALLOCATABLE] = (opts.allocatable == "yes")
+
+  if changes:
+    op = opcodes.OpModifyNodeStorage(node_name=node_name,
+                                     storage_type=storage_type,
+                                     name=volume_name,
+                                     changes=changes)
+    SubmitOpCode(op)
+
+
+def RepairVolume(opts, args):
+  """Repairs a storage volume on a node.
+
+  @param opts: the command line options selected by the user
+  @type args: list
+  @param args: should contain 3 items: node name, storage type and volume name
+  @rtype: int
+  @return: the desired exit code
+
+  """
+  (node_name, user_storage_type, volume_name) = args
+
+  storage_type = ConvertStorageType(user_storage_type)
+
+  op = opcodes.OpRepairNodeStorage(node_name=node_name,
+                                   storage_type=storage_type,
+                                   name=volume_name)
+  SubmitOpCode(op)
+
+
 def SetNodeParams(opts, args):
   """Modifies a node.
 
@@ -489,93 +622,123 @@ def SetNodeParams(opts, args):
 
 
 commands = {
-  'add': (AddNode, ARGS_ONE,
+  'add': (AddNode, [ArgHost(min=1, max=1)],
           [DEBUG_OPT,
-           make_option("-s", "--secondary-ip", dest="secondary_ip",
-                       help="Specify the secondary ip for the node",
-                       metavar="ADDRESS", default=None),
-           make_option("--readd", dest="readd",
-                       default=False, action="store_true",
-                       help="Readd old node after replacing it"),
-           make_option("--no-ssh-key-check", dest="ssh_key_check",
-                       default=True, action="store_false",
-                       help="Disable SSH key fingerprint checking"),
+           cli_option("-s", "--secondary-ip", dest="secondary_ip",
+                      help="Specify the secondary ip for the node",
+                      metavar="ADDRESS", default=None),
+           cli_option("--readd", dest="readd",
+                      default=False, action="store_true",
+                      help="Readd old node after replacing it"),
+           cli_option("--no-ssh-key-check", dest="ssh_key_check",
+                      default=True, action="store_false",
+                      help="Disable SSH key fingerprint checking"),
            ],
           "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
           "Add a node to the cluster"),
-  'evacuate': (EvacuateNode, ARGS_ONE,
+  'evacuate': (EvacuateNode, ARGS_ONE_NODE,
                [DEBUG_OPT, FORCE_OPT,
-                make_option("-n", "--new-secondary", dest="dst_node",
-                            help="New secondary node", metavar="NODE",
-                            default=None),
-                make_option("-I", "--iallocator", metavar="<NAME>",
-                            help="Select new secondary for the instance"
-                            " automatically using the"
-                            " <NAME> iallocator plugin",
-                            default=None, type="string"),
+                cli_option("-n", "--new-secondary", dest="dst_node",
+                           help="New secondary node", metavar="NODE",
+                           default=None,
+                           completion_suggest=OPT_COMPL_ONE_NODE),
+                cli_option("-I", "--iallocator", metavar="<NAME>",
+                           help="Select new secondary for the instance"
+                           " automatically using the"
+                           " <NAME> iallocator plugin",
+                           default=None, type="string",
+                           completion_suggest=OPT_COMPL_ONE_IALLOCATOR),
                 ],
                "[-f] {-I <iallocator> | -n <dst>} <node>",
                "Relocate the secondary instances from a node"
                " to other nodes (only for instances with drbd disk template)"),
-  'failover': (FailoverNode, ARGS_ONE,
+  'failover': (FailoverNode, ARGS_ONE_NODE,
                [DEBUG_OPT, FORCE_OPT,
-                make_option("--ignore-consistency", dest="ignore_consistency",
-                            action="store_true", default=False,
-                            help="Ignore the consistency of the disks on"
-                            " the secondary"),
+                cli_option("--ignore-consistency", dest="ignore_consistency",
+                           action="store_true", default=False,
+                           help="Ignore the consistency of the disks on"
+                           " the secondary"),
                 ],
                "[-f] <node>",
                "Stops the primary instances on a node and start them on their"
                " secondary node (only for instances with drbd disk template)"),
-  'migrate': (MigrateNode, ARGS_ONE,
+  'migrate': (MigrateNode, ARGS_ONE_NODE,
                [DEBUG_OPT, FORCE_OPT,
-                make_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("--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)"),
                 ],
                "[-f] <node>",
                "Migrate all the primary instance on a node away from it"
                " (only for instances of type drbd)"),
-  'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
+  'info': (ShowNodeConfig, ARGS_MANY_NODES, [DEBUG_OPT],
            "[<node_name>...]", "Show information about the node(s)"),
-  'list': (ListNodes, ARGS_ANY,
+  'list': (ListNodes, ARGS_MANY_NODES,
            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
            "[nodes...]",
            "Lists the nodes in the cluster. The available fields"
            " are (see the man page for details): %s"
            " The default field list is (in order): %s." %
            (", ".join(_LIST_HEADERS), ", ".join(_LIST_DEF_FIELDS))),
-  'modify': (SetNodeParams, ARGS_ONE,
+  'modify': (SetNodeParams, ARGS_ONE_NODE,
              [DEBUG_OPT, FORCE_OPT,
               SUBMIT_OPT,
-              make_option("-C", "--master-candidate", dest="master_candidate",
-                          choices=('yes', 'no'), default=None,
-                          metavar="yes|no",
-                          help="Set the master_candidate flag on the node"),
-
-              make_option("-O", "--offline", dest="offline", metavar="yes|no",
-                          choices=('yes', 'no'), default=None,
-                          help="Set the offline flag on the node"),
-              make_option("-D", "--drained", dest="drained", metavar="yes|no",
-                          choices=('yes', 'no'), default=None,
-                          help="Set the drained flag on the node"),
+              cli_option("-C", "--master-candidate", dest="master_candidate",
+                         choices=('yes', 'no'), default=None,
+                         metavar="yes|no",
+                         help="Set the master_candidate flag on the node"),
+              cli_option("-O", "--offline", dest="offline", metavar="yes|no",
+                         choices=('yes', 'no'), default=None,
+                         help="Set the offline flag on the node"),
+              cli_option("-D", "--drained", dest="drained", metavar="yes|no",
+                         choices=('yes', 'no'), default=None,
+                         help="Set the drained flag on the node"),
               ],
-             "<instance>", "Alters the parameters of an instance"),
-  'powercycle': (PowercycleNode, ARGS_ONE, [DEBUG_OPT, FORCE_OPT, CONFIRM_OPT],
+             "<node_name>", "Alters the parameters of a node"),
+  'powercycle': (PowercycleNode, ARGS_ONE_NODE,
+                 [DEBUG_OPT, FORCE_OPT, CONFIRM_OPT],
                  "<node_name>", "Tries to forcefully powercycle a node"),
-  'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
+  'remove': (RemoveNode, ARGS_ONE_NODE, [DEBUG_OPT],
              "<node_name>", "Removes a node from the cluster"),
-  'volumes': (ListVolumes, ARGS_ANY,
+  'volumes': (ListVolumes, [ArgNode()],
               [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
               "[<node_name>...]", "List logical volumes on node(s)"),
-  'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
+  'physical-volumes': (ListPhysicalVolumes, ARGS_MANY_NODES,
+                       [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT,
+                        FIELDS_OPT, _STORAGE_TYPE_OPT],
+                       "[<node_name>...]",
+                       "List physical volumes on node(s)"),
+  'modify-volume': (ModifyVolume,
+                    [ArgNode(min=1, max=1),
+                     ArgChoice(min=1, max=1,
+                               choices=_MODIFIABLE_STORAGE_TYPES),
+                     ArgFile(min=1, max=1)],
+                    [DEBUG_OPT,
+                     cli_option("--allocatable", dest="allocatable",
+                                choices=["yes", "no"], default=None,
+                                metavar="yes|no",
+                                help="Set the allocatable flag on a volume"),
+                     ],
+                    "<node_name> <storage_type> <name>",
+                    "Modify storage volume on a node"),
+  'repair-volume': (RepairVolume,
+                    [ArgNode(min=1, max=1),
+                     ArgChoice(min=1, max=1,
+                               choices=_REPAIRABLE_STORAGE_TYPES),
+                     ArgFile(min=1, max=1)],
+                    [DEBUG_OPT],
+                    "<node_name> <storage_type> <name>",
+                    "Repairs a storage volume on a node"),
+  'list-tags': (ListTags, ARGS_ONE_NODE, [DEBUG_OPT],
                 "<node_name>", "List the tags of the given node"),
-  'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
+  'add-tags': (AddTags, [ArgNode(min=1, max=1), ArgUnknown()],
+               [DEBUG_OPT, TAG_SRC_OPT],
                "<node_name> tag...", "Add tags to the given node"),
-  'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
+  'remove-tags': (RemoveTags, [ArgNode(min=1, max=1), ArgUnknown()],
+                  [DEBUG_OPT, TAG_SRC_OPT],
                   "<node_name> tag...", "Remove tags from the given node"),
   }