Fix a bug in command line option parsing code
[ganeti-local] / lib / rapi / client.py
index 10f1975..f41b6fc 100644 (file)
@@ -63,6 +63,10 @@ REPLACE_DISK_SECONDARY = "replace_on_secondary"
 REPLACE_DISK_CHG = "replace_new_secondary"
 REPLACE_DISK_AUTO = "replace_auto"
 
+NODE_EVAC_PRI = "primary-only"
+NODE_EVAC_SEC = "secondary-only"
+NODE_EVAC_ALL = "all"
+
 NODE_ROLE_DRAINED = "drained"
 NODE_ROLE_MASTER_CANDIATE = "master-candidate"
 NODE_ROLE_MASTER = "master"
@@ -70,7 +74,7 @@ NODE_ROLE_OFFLINE = "offline"
 NODE_ROLE_REGULAR = "regular"
 
 JOB_STATUS_QUEUED = "queued"
-JOB_STATUS_WAITLOCK = "waiting"
+JOB_STATUS_WAITING = "waiting"
 JOB_STATUS_CANCELING = "canceling"
 JOB_STATUS_RUNNING = "running"
 JOB_STATUS_CANCELED = "canceled"
@@ -83,15 +87,20 @@ JOB_STATUS_FINALIZED = frozenset([
   ])
 JOB_STATUS_ALL = frozenset([
   JOB_STATUS_QUEUED,
-  JOB_STATUS_WAITLOCK,
+  JOB_STATUS_WAITING,
   JOB_STATUS_CANCELING,
   JOB_STATUS_RUNNING,
   ]) | JOB_STATUS_FINALIZED
 
+# Legacy name
+JOB_STATUS_WAITLOCK = JOB_STATUS_WAITING
+
 # Internal constants
 _REQ_DATA_VERSION_FIELD = "__version__"
 _INST_CREATE_REQV1 = "instance-create-reqv1"
 _INST_REINSTALL_REQV1 = "instance-reinstall-reqv1"
+_NODE_MIGRATE_REQV1 = "node-migrate-reqv1"
+_NODE_EVAC_RES1 = "node-evac-res1"
 _INST_NIC_PARAMS = frozenset(["mac", "ip", "mode", "link"])
 _INST_CREATE_V0_DISK_PARAMS = frozenset(["size"])
 _INST_CREATE_V0_PARAMS = frozenset([
@@ -256,7 +265,7 @@ def GenericCurlConfig(verbose=False, use_signal=False,
   return _ConfigCurl
 
 
-class GanetiRapiClient(object): # pylint: disable-msg=R0904
+class GanetiRapiClient(object): # pylint: disable=R0904
   """Ganeti RAPI client.
 
   """
@@ -675,82 +684,8 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
       body.update((key, value) for key, value in kwargs.iteritems()
                   if key != "dry_run")
     else:
-      # Old request format (version 0)
-
-      # The following code must make sure that an exception is raised when an
-      # unsupported setting is requested by the caller. Otherwise this can lead
-      # to bugs difficult to find. The interface of this function must stay
-      # exactly the same for version 0 and 1 (e.g. they aren't allowed to
-      # require different data types).
-
-      # Validate disks
-      for idx, disk in enumerate(disks):
-        unsupported = set(disk.keys()) - _INST_CREATE_V0_DISK_PARAMS
-        if unsupported:
-          raise GanetiApiError("Server supports request version 0 only, but"
-                               " disk %s specifies the unsupported parameters"
-                               " %s, allowed are %s" %
-                               (idx, unsupported,
-                                list(_INST_CREATE_V0_DISK_PARAMS)))
-
-      assert (len(_INST_CREATE_V0_DISK_PARAMS) == 1 and
-              "size" in _INST_CREATE_V0_DISK_PARAMS)
-      disk_sizes = [disk["size"] for disk in disks]
-
-      # Validate NICs
-      if not nics:
-        raise GanetiApiError("Server supports request version 0 only, but"
-                             " no NIC specified")
-      elif len(nics) > 1:
-        raise GanetiApiError("Server supports request version 0 only, but"
-                             " more than one NIC specified")
-
-      assert len(nics) == 1
-
-      unsupported = set(nics[0].keys()) - _INST_NIC_PARAMS
-      if unsupported:
-        raise GanetiApiError("Server supports request version 0 only, but"
-                             " NIC 0 specifies the unsupported parameters %s,"
-                             " allowed are %s" %
-                             (unsupported, list(_INST_NIC_PARAMS)))
-
-      # Validate other parameters
-      unsupported = (set(kwargs.keys()) - _INST_CREATE_V0_PARAMS -
-                     _INST_CREATE_V0_DPARAMS)
-      if unsupported:
-        allowed = _INST_CREATE_V0_PARAMS.union(_INST_CREATE_V0_DPARAMS)
-        raise GanetiApiError("Server supports request version 0 only, but"
-                             " the following unsupported parameters are"
-                             " specified: %s, allowed are %s" %
-                             (unsupported, list(allowed)))
-
-      # All required fields for request data version 0
-      body = {
-        _REQ_DATA_VERSION_FIELD: 0,
-        "name": name,
-        "disk_template": disk_template,
-        "disks": disk_sizes,
-        }
-
-      # NIC fields
-      assert len(nics) == 1
-      assert not (set(body.keys()) & set(nics[0].keys()))
-      body.update(nics[0])
-
-      # Copy supported fields
-      assert not (set(body.keys()) & set(kwargs.keys()))
-      body.update(dict((key, value) for key, value in kwargs.items()
-                       if key in _INST_CREATE_V0_PARAMS))
-
-      # Merge dictionaries
-      for i in (value for key, value in kwargs.items()
-                if key in _INST_CREATE_V0_DPARAMS):
-        assert not (set(body.keys()) & set(i.keys()))
-        body.update(i)
-
-      assert not (set(kwargs.keys()) -
-                  (_INST_CREATE_V0_PARAMS | _INST_CREATE_V0_DPARAMS))
-      assert not (set(body.keys()) & _INST_CREATE_V0_DPARAMS)
+      raise GanetiApiError("Server does not support new-style (version 1)"
+                           " instance creation requests")
 
     return self._SendRequest(HTTP_POST, "/%s/instances" % GANETI_RAPI_VERSION,
                              query, body)
@@ -937,13 +872,15 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                              ("/%s/instances/%s/reboot" %
                               (GANETI_RAPI_VERSION, instance)), query, None)
 
-  def ShutdownInstance(self, instance, dry_run=False):
+  def ShutdownInstance(self, instance, dry_run=False, no_remember=False):
     """Shuts down an instance.
 
     @type instance: str
     @param instance: the instance to shut down
     @type dry_run: bool
     @param dry_run: whether to perform a dry run
+    @type no_remember: bool
+    @param no_remember: if true, will not record the state change
     @rtype: string
     @return: job id
 
@@ -951,18 +888,22 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
     query = []
     if dry_run:
       query.append(("dry-run", 1))
+    if no_remember:
+      query.append(("no-remember", 1))
 
     return self._SendRequest(HTTP_PUT,
                              ("/%s/instances/%s/shutdown" %
                               (GANETI_RAPI_VERSION, instance)), query, None)
 
-  def StartupInstance(self, instance, dry_run=False):
+  def StartupInstance(self, instance, dry_run=False, no_remember=False):
     """Starts up an instance.
 
     @type instance: str
     @param instance: the instance to start up
     @type dry_run: bool
     @param dry_run: whether to perform a dry run
+    @type no_remember: bool
+    @param no_remember: if true, will not record the state change
     @rtype: string
     @return: job id
 
@@ -970,6 +911,8 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
     query = []
     if dry_run:
       query.append(("dry-run", 1))
+    if no_remember:
+      query.append(("no-remember", 1))
 
     return self._SendRequest(HTTP_PUT,
                              ("/%s/instances/%s/startup" %
@@ -1017,7 +960,7 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                               (GANETI_RAPI_VERSION, instance)), query, None)
 
   def ReplaceInstanceDisks(self, instance, disks=None, mode=REPLACE_DISK_AUTO,
-                           remote_node=None, iallocator=None, dry_run=False):
+                           remote_node=None, iallocator=None):
     """Replaces disks on an instance.
 
     @type instance: str
@@ -1032,8 +975,6 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
     @type iallocator: str or None
     @param iallocator: instance allocator plugin to use (for use with
                        replace_auto mode)
-    @type dry_run: bool
-    @param dry_run: whether to perform a dry run
 
     @rtype: string
     @return: job id
@@ -1043,18 +984,17 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
       ("mode", mode),
       ]
 
-    if disks:
+    # TODO: Convert to body parameters
+
+    if disks is not None:
       query.append(("disks", ",".join(str(idx) for idx in disks)))
 
-    if remote_node:
+    if remote_node is not None:
       query.append(("remote_node", remote_node))
 
-    if iallocator:
+    if iallocator is not None:
       query.append(("iallocator", iallocator))
 
-    if dry_run:
-      query.append(("dry-run", 1))
-
     return self._SendRequest(HTTP_POST,
                              ("/%s/instances/%s/replace-disks" %
                               (GANETI_RAPI_VERSION, instance)), query, None)
@@ -1134,6 +1074,38 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                              ("/%s/instances/%s/migrate" %
                               (GANETI_RAPI_VERSION, instance)), None, body)
 
+  def FailoverInstance(self, instance, iallocator=None,
+                       ignore_consistency=None, target_node=None):
+    """Does a failover of an instance.
+
+    @type instance: string
+    @param instance: Instance name
+    @type iallocator: string
+    @param iallocator: Iallocator for deciding the target node for
+      shared-storage instances
+    @type ignore_consistency: bool
+    @param ignore_consistency: Whether to ignore disk consistency
+    @type target_node: string
+    @param target_node: Target node for shared-storage instances
+    @rtype: string
+    @return: job id
+
+    """
+    body = {}
+
+    if iallocator is not None:
+      body["iallocator"] = iallocator
+
+    if ignore_consistency is not None:
+      body["ignore_consistency"] = ignore_consistency
+
+    if target_node is not None:
+      body["target_node"] = target_node
+
+    return self._SendRequest(HTTP_PUT,
+                             ("/%s/instances/%s/failover" %
+                              (GANETI_RAPI_VERSION, instance)), None, body)
+
   def RenameInstance(self, instance, new_name, ip_check=None, name_check=None):
     """Changes the name of an instance.
 
@@ -1315,7 +1287,8 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                              None, None)
 
   def EvacuateNode(self, node, iallocator=None, remote_node=None,
-                   dry_run=False, early_release=False):
+                   dry_run=False, early_release=None,
+                   mode=None, accept_old=False):
     """Evacuates instances from a Ganeti node.
 
     @type node: str
@@ -1328,11 +1301,17 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
     @param dry_run: whether to perform a dry run
     @type early_release: bool
     @param early_release: whether to enable parallelization
+    @type mode: string
+    @param mode: Node evacuation mode
+    @type accept_old: bool
+    @param accept_old: Whether caller is ready to accept old-style (pre-2.5)
+        results
 
-    @rtype: list
-    @return: list of (job ID, instance name, new secondary node); if
-        dry_run was specified, then the actual move jobs were not
-        submitted and the job IDs will be C{None}
+    @rtype: string, or a list for pre-2.5 results
+    @return: Job ID or, if C{accept_old} is set and server is pre-2.5,
+      list of (job ID, instance name, new secondary node); if dry_run was
+      specified, then the actual move jobs were not submitted and the job IDs
+      will be C{None}
 
     @raises GanetiApiError: if an iallocator and remote_node are both
         specified
@@ -1342,20 +1321,47 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
       raise GanetiApiError("Only one of iallocator or remote_node can be used")
 
     query = []
-    if iallocator:
-      query.append(("iallocator", iallocator))
-    if remote_node:
-      query.append(("remote_node", remote_node))
     if dry_run:
       query.append(("dry-run", 1))
-    if early_release:
-      query.append(("early_release", 1))
+
+    if _NODE_EVAC_RES1 in self.GetFeatures():
+      # Server supports body parameters
+      body = {}
+
+      if iallocator is not None:
+        body["iallocator"] = iallocator
+      if remote_node is not None:
+        body["remote_node"] = remote_node
+      if early_release is not None:
+        body["early_release"] = early_release
+      if mode is not None:
+        body["mode"] = mode
+    else:
+      # Pre-2.5 request format
+      body = None
+
+      if not accept_old:
+        raise GanetiApiError("Server is version 2.4 or earlier and caller does"
+                             " not accept old-style results (parameter"
+                             " accept_old)")
+
+      # Pre-2.5 servers can only evacuate secondaries
+      if mode is not None and mode != NODE_EVAC_SEC:
+        raise GanetiApiError("Server can only evacuate secondary instances")
+
+      if iallocator:
+        query.append(("iallocator", iallocator))
+      if remote_node:
+        query.append(("remote_node", remote_node))
+      if early_release:
+        query.append(("early_release", 1))
 
     return self._SendRequest(HTTP_POST,
                              ("/%s/nodes/%s/evacuate" %
-                              (GANETI_RAPI_VERSION, node)), query, None)
+                              (GANETI_RAPI_VERSION, node)), query, body)
 
-  def MigrateNode(self, node, mode=None, dry_run=False):
+  def MigrateNode(self, node, mode=None, dry_run=False, iallocator=None,
+                  target_node=None):
     """Migrates all primary instances from a node.
 
     @type node: str
@@ -1365,20 +1371,46 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
         otherwise the hypervisor default will be used
     @type dry_run: bool
     @param dry_run: whether to perform a dry run
+    @type iallocator: string
+    @param iallocator: instance allocator to use
+    @type target_node: string
+    @param target_node: Target node for shared-storage instances
 
     @rtype: string
     @return: job id
 
     """
     query = []
-    if mode is not None:
-      query.append(("mode", mode))
     if dry_run:
       query.append(("dry-run", 1))
 
-    return self._SendRequest(HTTP_POST,
-                             ("/%s/nodes/%s/migrate" %
-                              (GANETI_RAPI_VERSION, node)), query, None)
+    if _NODE_MIGRATE_REQV1 in self.GetFeatures():
+      body = {}
+
+      if mode is not None:
+        body["mode"] = mode
+      if iallocator is not None:
+        body["iallocator"] = iallocator
+      if target_node is not None:
+        body["target_node"] = target_node
+
+      assert len(query) <= 1
+
+      return self._SendRequest(HTTP_POST,
+                               ("/%s/nodes/%s/migrate" %
+                                (GANETI_RAPI_VERSION, node)), query, body)
+    else:
+      # Use old request format
+      if target_node is not None:
+        raise GanetiApiError("Server does not support specifying target node"
+                             " for node migration")
+
+      if mode is not None:
+        query.append(("mode", mode))
+
+      return self._SendRequest(HTTP_POST,
+                               ("/%s/nodes/%s/migrate" %
+                                (GANETI_RAPI_VERSION, node)), query, None)
 
   def GetNodeRole(self, node):
     """Gets the current role for a node.
@@ -1394,7 +1426,7 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                              ("/%s/nodes/%s/role" %
                               (GANETI_RAPI_VERSION, node)), None, None)
 
-  def SetNodeRole(self, node, role, force=False):
+  def SetNodeRole(self, node, role, force=False, auto_promote=None):
     """Sets the role for a node.
 
     @type node: str
@@ -1403,6 +1435,9 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
     @param role: the role to set for the node
     @type force: bool
     @param force: whether to force the role change
+    @type auto_promote: bool
+    @param auto_promote: Whether node(s) should be promoted to master candidate
+                         if necessary
 
     @rtype: string
     @return: job id
@@ -1412,10 +1447,28 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
       ("force", force),
       ]
 
+    if auto_promote is not None:
+      query.append(("auto-promote", auto_promote))
+
     return self._SendRequest(HTTP_PUT,
                              ("/%s/nodes/%s/role" %
                               (GANETI_RAPI_VERSION, node)), query, role)
 
+  def ModifyNode(self, node, **kwargs):
+    """Modifies a node.
+
+    More details for parameters can be found in the RAPI documentation.
+
+    @type node: string
+    @param node: Node name
+    @rtype: string
+    @return: job id
+
+    """
+    return self._SendRequest(HTTP_POST,
+                             ("/%s/nodes/%s/modify" %
+                              (GANETI_RAPI_VERSION, node)), None, kwargs)
+
   def GetNodeStorageUnits(self, node, storage_type, output_fields):
     """Gets the storage units for a node.
 
@@ -1694,6 +1747,63 @@ class GanetiRapiClient(object): # pylint: disable-msg=R0904
                              ("/%s/groups/%s/assign-nodes" %
                              (GANETI_RAPI_VERSION, group)), query, body)
 
+  def GetGroupTags(self, group):
+    """Gets tags for a node group.
+
+    @type group: string
+    @param group: Node group whose tags to return
+
+    @rtype: list of strings
+    @return: tags for the group
+
+    """
+    return self._SendRequest(HTTP_GET,
+                             ("/%s/groups/%s/tags" %
+                              (GANETI_RAPI_VERSION, group)), None, None)
+
+  def AddGroupTags(self, group, tags, dry_run=False):
+    """Adds tags to a node group.
+
+    @type group: str
+    @param group: group to add tags to
+    @type tags: list of string
+    @param tags: tags to add to the group
+    @type dry_run: bool
+    @param dry_run: whether to perform a dry run
+
+    @rtype: string
+    @return: job id
+
+    """
+    query = [("tag", t) for t in tags]
+    if dry_run:
+      query.append(("dry-run", 1))
+
+    return self._SendRequest(HTTP_PUT,
+                             ("/%s/groups/%s/tags" %
+                              (GANETI_RAPI_VERSION, group)), query, None)
+
+  def DeleteGroupTags(self, group, tags, dry_run=False):
+    """Deletes tags from a node group.
+
+    @type group: str
+    @param group: group to delete tags from
+    @type tags: list of string
+    @param tags: tags to delete
+    @type dry_run: bool
+    @param dry_run: whether to perform a dry run
+    @rtype: string
+    @return: job id
+
+    """
+    query = [("tag", t) for t in tags]
+    if dry_run:
+      query.append(("dry-run", 1))
+
+    return self._SendRequest(HTTP_DELETE,
+                             ("/%s/groups/%s/tags" %
+                              (GANETI_RAPI_VERSION, group)), query, None)
+
   def Query(self, what, fields, filter_=None):
     """Retrieves information about resources.