Implement utils.RunParts and use it for hooks
[ganeti-local] / lib / rapi / rlib2.py
index 9ef6247..f475277 100644 (file)
 
 """
 
+# pylint: disable-msg=C0103
+
+# C0103: Invalid name, since the R_* names are not conforming
+
 from ganeti import opcodes
 from ganeti import http
 from ganeti import constants
 from ganeti import cli
+from ganeti import rapi
 from ganeti.rapi import baserlib
 
 
+_COMMON_FIELDS = ["ctime", "mtime", "uuid", "serial_no", "tags"]
 I_FIELDS = ["name", "admin_state", "os",
             "pnode", "snodes",
             "disk_template",
-            "nic.ips", "nic.macs", "nic.modes", "nic.links",
+            "nic.ips", "nic.macs", "nic.modes", "nic.links", "nic.bridges",
             "network_port",
             "disk.sizes", "disk_usage",
             "beparams", "hvparams",
             "oper_state", "oper_ram", "status",
-            "tags"]
+            ] + _COMMON_FIELDS
 
 N_FIELDS = ["name", "offline", "master_candidate", "drained",
             "dtotal", "dfree",
             "mtotal", "mnode", "mfree",
-            "pinst_cnt", "sinst_cnt", "tags",
+            "pinst_cnt", "sinst_cnt",
             "ctotal", "cnodes", "csockets",
-            ]
+            "pip", "sip", "role",
+            "pinst_list", "sinst_list",
+            ] + _COMMON_FIELDS
 
 _NR_DRAINED = "drained"
 _NR_MASTER_CANDIATE = "master-candidate"
@@ -69,7 +77,8 @@ class R_version(baserlib.R_Generic):
   to adapt clients accordingly.
 
   """
-  def GET(self):
+  @staticmethod
+  def GET():
     """Returns the remote API version.
 
     """
@@ -80,7 +89,8 @@ class R_2_info(baserlib.R_Generic):
   """Cluster info.
 
   """
-  def GET(self):
+  @staticmethod
+  def GET():
     """Returns cluster information.
 
     """
@@ -92,7 +102,8 @@ class R_2_os(baserlib.R_Generic):
   """/2/os resource.
 
   """
-  def GET(self):
+  @staticmethod
+  def GET():
     """Return a list of all OSes.
 
     Can return error 500 in case of a problem.
@@ -101,7 +112,8 @@ class R_2_os(baserlib.R_Generic):
 
     """
     cl = baserlib.GetClient()
-    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
+    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid", "variants"],
+                              names=[])
     job_id = baserlib.SubmitJob([op], cl)
     # we use custom feedback function, instead of print we log the status
     result = cli.PollJob(job_id, cl, feedback_fn=baserlib.FeedbackFn)
@@ -110,14 +122,32 @@ class R_2_os(baserlib.R_Generic):
     if not isinstance(diagnose_data, list):
       raise http.HttpBadGateway(message="Can't get OS list")
 
-    return [row[0] for row in diagnose_data if row[1]]
+    os_names = []
+    for (name, valid, variants) in diagnose_data:
+      if valid:
+        os_names.extend(cli.CalculateOSNames(name, variants))
+
+    return os_names
+
+
+class R_2_redist_config(baserlib.R_Generic):
+  """/2/redistribute-config resource.
+
+  """
+  @staticmethod
+  def PUT():
+    """Redistribute configuration to all nodes.
+
+    """
+    return baserlib.SubmitJob([opcodes.OpRedistributeConfig()])
 
 
 class R_2_jobs(baserlib.R_Generic):
   """/2/jobs resource.
 
   """
-  def GET(self):
+  @staticmethod
+  def GET():
     """Returns a dictionary of jobs.
 
     @return: a dictionary with jobs id and uri.
@@ -280,6 +310,101 @@ class R_2_nodes_name_evacuate(baserlib.R_Generic):
     return baserlib.SubmitJob([op])
 
 
+class R_2_nodes_name_migrate(baserlib.R_Generic):
+  """/2/nodes/[node_name]/migrate resource.
+
+  """
+  def POST(self):
+    """Migrate all primary instances from a node.
+
+    """
+    node_name = self.items[0]
+    live = bool(self._checkIntVariable("live", default=1))
+
+    op = opcodes.OpMigrateNode(node_name=node_name, live=live)
+
+    return baserlib.SubmitJob([op])
+
+
+class R_2_nodes_name_storage(baserlib.R_Generic):
+  """/2/nodes/[node_name]/storage ressource.
+
+  """
+  # LUQueryNodeStorage acquires locks, hence restricting access to GET
+  GET_ACCESS = [rapi.RAPI_ACCESS_WRITE]
+
+  def GET(self):
+    node_name = self.items[0]
+
+    storage_type = self._checkStringVariable("storage_type", None)
+    if not storage_type:
+      raise http.HttpBadRequest("Missing the required 'storage_type'"
+                                " parameter")
+
+    output_fields = self._checkStringVariable("output_fields", None)
+    if not output_fields:
+      raise http.HttpBadRequest("Missing the required 'output_fields'"
+                                " parameter")
+
+    op = opcodes.OpQueryNodeStorage(nodes=[node_name],
+                                    storage_type=storage_type,
+                                    output_fields=output_fields.split(","))
+    return baserlib.SubmitJob([op])
+
+
+class R_2_nodes_name_storage_modify(baserlib.R_Generic):
+  """/2/nodes/[node_name]/storage/modify ressource.
+
+  """
+  def PUT(self):
+    node_name = self.items[0]
+
+    storage_type = self._checkStringVariable("storage_type", None)
+    if not storage_type:
+      raise http.HttpBadRequest("Missing the required 'storage_type'"
+                                " parameter")
+
+    name = self._checkStringVariable("name", None)
+    if not name:
+      raise http.HttpBadRequest("Missing the required 'name'"
+                                " parameter")
+
+    changes = {}
+
+    if "allocatable" in self.queryargs:
+      changes[constants.SF_ALLOCATABLE] = \
+        bool(self._checkIntVariable("allocatable", default=1))
+
+    op = opcodes.OpModifyNodeStorage(node_name=node_name,
+                                     storage_type=storage_type,
+                                     name=name,
+                                     changes=changes)
+    return baserlib.SubmitJob([op])
+
+
+class R_2_nodes_name_storage_repair(baserlib.R_Generic):
+  """/2/nodes/[node_name]/storage/repair ressource.
+
+  """
+  def PUT(self):
+    node_name = self.items[0]
+
+    storage_type = self._checkStringVariable("storage_type", None)
+    if not storage_type:
+      raise http.HttpBadRequest("Missing the required 'storage_type'"
+                                " parameter")
+
+    name = self._checkStringVariable("name", None)
+    if not name:
+      raise http.HttpBadRequest("Missing the required 'name'"
+                                " parameter")
+
+    op = opcodes.OpRepairNodeStorage(node_name=node_name,
+                                     storage_type=storage_type,
+                                     name=name)
+    return baserlib.SubmitJob([op])
+
+
 class R_2_instances(baserlib.R_Generic):
   """/2/instances resource.
 
@@ -323,7 +448,7 @@ class R_2_instances(baserlib.R_Generic):
     for idx, d in enumerate(disk_data):
       if not isinstance(d, int):
         raise http.HttpBadRequest("Disk %d specification wrong: should"
-                                  " be an integer")
+                                  " be an integer" % idx)
       disks.append({"size": d})
     # nic processing (one nic only)
     nics = [{"mac": fn("mac", constants.VALUE_AUTO)}]
@@ -334,7 +459,7 @@ class R_2_instances(baserlib.R_Generic):
     if fn("link", None) is not None:
       nics[0]["link"] = fn("link")
     if fn("bridge", None) is not None:
-       nics[0]["bridge"] = fn("bridge")
+      nics[0]["bridge"] = fn("bridge")
 
     op = opcodes.OpCreateInstance(
       mode=constants.INSTANCE_CREATE,
@@ -348,6 +473,7 @@ class R_2_instances(baserlib.R_Generic):
       nics=nics,
       start=fn('start', True),
       ip_check=fn('ip_check', True),
+      name_check=fn('name_check', True),
       wait_for_sync=True,
       hypervisor=fn('hypervisor', None),
       hvparams=hvparams,
@@ -385,6 +511,22 @@ class R_2_instances_name(baserlib.R_Generic):
     return baserlib.SubmitJob([op])
 
 
+class R_2_instances_name_info(baserlib.R_Generic):
+  """/2/instances/[instance_name]/info resource.
+
+  """
+  def GET(self):
+    """Request detailed instance information.
+
+    """
+    instance_name = self.items[0]
+    static = bool(self._checkIntVariable("static", default=0))
+
+    op = opcodes.OpQueryInstanceData(instances=[instance_name],
+                                     static=static)
+    return baserlib.SubmitJob([op])
+
+
 class R_2_instances_name_reboot(baserlib.R_Generic):
   """/2/instances/[instance_name]/reboot resource.
 
@@ -401,8 +543,7 @@ class R_2_instances_name_reboot(baserlib.R_Generic):
     instance_name = self.items[0]
     reboot_type = self.queryargs.get('type',
                                      [constants.INSTANCE_REBOOT_HARD])[0]
-    ignore_secondaries = bool(self.queryargs.get('ignore_secondaries',
-                                                 [False])[0])
+    ignore_secondaries = bool(self._checkIntVariable('ignore_secondaries'))
     op = opcodes.OpRebootInstance(instance_name=instance_name,
                                   reboot_type=reboot_type,
                                   ignore_secondaries=ignore_secondaries,
@@ -425,7 +566,7 @@ class R_2_instances_name_startup(baserlib.R_Generic):
 
     """
     instance_name = self.items[0]
-    force_startup = bool(self.queryargs.get('force', [False])[0])
+    force_startup = bool(self._checkIntVariable('force'))
     op = opcodes.OpStartupInstance(instance_name=instance_name,
                                    force=force_startup,
                                    dry_run=bool(self.dryRun()))
@@ -456,9 +597,6 @@ class R_2_instances_name_reinstall(baserlib.R_Generic):
   Implements an instance reinstall.
 
   """
-
-  DOC_URI = "/2/instances/[instance_name]/reinstall"
-
   def POST(self):
     """Reinstall an instance.
 
@@ -480,6 +618,37 @@ class R_2_instances_name_reinstall(baserlib.R_Generic):
     return baserlib.SubmitJob(ops)
 
 
+class R_2_instances_name_replace_disks(baserlib.R_Generic):
+  """/2/instances/[instance_name]/replace-disks resource.
+
+  """
+  def POST(self):
+    """Replaces disks on an instance.
+
+    """
+    instance_name = self.items[0]
+    remote_node = self._checkStringVariable("remote_node", default=None)
+    mode = self._checkStringVariable("mode", default=None)
+    raw_disks = self._checkStringVariable("disks", default=None)
+    iallocator = self._checkStringVariable("iallocator", default=None)
+
+    if raw_disks:
+      try:
+        disks = [int(part) for part in raw_disks.split(",")]
+      except ValueError, err:
+        raise http.HttpBadRequest("Invalid disk index passed: %s" % str(err))
+    else:
+      disks = []
+
+    op = opcodes.OpReplaceDisks(instance_name=instance_name,
+                                remote_node=remote_node,
+                                mode=mode,
+                                disks=disks,
+                                iallocator=iallocator)
+
+    return baserlib.SubmitJob([op])
+
+
 class _R_Tags(baserlib.R_Generic):
   """ Quasiclass for tagging resources
 
@@ -508,6 +677,7 @@ class _R_Tags(baserlib.R_Generic):
     Example: ["tag1", "tag2", "tag3"]
 
     """
+    # pylint: disable-msg=W0212
     return baserlib._Tags_GET(self.TAG_LEVEL, name=self.name)
 
   def PUT(self):
@@ -517,6 +687,7 @@ class _R_Tags(baserlib.R_Generic):
     you'll have back a job id.
 
     """
+    # pylint: disable-msg=W0212
     if 'tag' not in self.queryargs:
       raise http.HttpBadRequest("Please specify tag(s) to add using the"
                                 " the 'tag' parameter")
@@ -532,6 +703,7 @@ class _R_Tags(baserlib.R_Generic):
     /tags?tag=[tag]&tag=[tag]
 
     """
+    # pylint: disable-msg=W0212
     if 'tag' not in self.queryargs:
       # no we not gonna delete all tags
       raise http.HttpBadRequest("Cannot delete all tags - please specify"