Actually mark drives as read-only if so configured
[ganeti-local] / lib / hypervisor / hv_xen.py
index cea3fa8..c8dd581 100644 (file)
 import os
 import os.path
 import time
+import logging
 from cStringIO import StringIO
 
 from ganeti import constants
 from ganeti import errors
-from ganeti import logger
 from ganeti import utils
 from ganeti.hypervisor import hv_base
 
@@ -43,36 +43,56 @@ class XenHypervisor(hv_base.BaseHypervisor):
 
   """
 
-  @staticmethod
-  def _WriteConfigFile(instance, block_devices, extra_args):
+  @classmethod
+  def _WriteConfigFile(cls, instance, block_devices, extra_args):
     """Write the Xen config file for the instance.
 
     """
     raise NotImplementedError
 
   @staticmethod
-  def _RemoveConfigFile(instance):
+  def _WriteConfigFileStatic(instance_name, data):
+    """Write the Xen config file for the instance.
+
+    This version of the function just writes the config file from static data.
+
+    """
+    utils.WriteFile("/etc/xen/%s" % instance_name, data=data)
+
+  @staticmethod
+  def _ReadConfigFile(instance_name):
+    """Returns the contents of the instance config file.
+
+    """
+    try:
+      file_content = utils.ReadFile("/etc/xen/%s" % instance_name)
+    except EnvironmentError, err:
+      raise errors.HypervisorError("Failed to load Xen config file: %s" % err)
+    return file_content
+
+  @staticmethod
+  def _RemoveConfigFile(instance_name):
     """Remove the xen configuration file.
 
     """
-    utils.RemoveFile("/etc/xen/%s" % instance.name)
+    utils.RemoveFile("/etc/xen/%s" % instance_name)
 
   @staticmethod
   def _GetXMList(include_node):
     """Return the list of running instances.
 
-    If the `include_node` argument is True, then we return information
+    If the include_node argument is True, then we return information
     for dom0 also, otherwise we filter that from the return value.
 
-    The return value is a list of (name, id, memory, vcpus, state, time spent)
+    @return: list of (name, id, memory, vcpus, state, time spent)
 
     """
     for dummy in range(5):
       result = utils.RunCmd(["xm", "list"])
       if not result.failed:
         break
-      logger.Error("xm list failed (%s): %s" % (result.fail_reason,
-                                                result.output))
+      logging.error("xm list failed (%s): %s", result.fail_reason,
+                    result.output)
       time.sleep(1)
 
     if result.failed:
@@ -117,11 +137,10 @@ class XenHypervisor(hv_base.BaseHypervisor):
   def GetInstanceInfo(self, instance_name):
     """Get instance properties.
 
-    Args:
-      instance_name: the instance name
+    @param instance_name: the instance name
+
+    @return: tuple (name, id, memory, vcpus, stat, times)
 
-    Returns:
-      (name, id, memory, vcpus, stat, times)
     """
     xm_list = self._GetXMList(instance_name=="Domain-0")
     result = None
@@ -134,14 +153,16 @@ class XenHypervisor(hv_base.BaseHypervisor):
   def GetAllInstancesInfo(self):
     """Get properties of all instances.
 
-    Returns:
-      [(name, id, memory, vcpus, stat, times),...]
+    @return: list of tuples (name, id, memory, vcpus, stat, times)
+
     """
     xm_list = self._GetXMList(False)
     return xm_list
 
   def StartInstance(self, instance, block_devices, extra_args):
-    """Start an instance."""
+    """Start an instance.
+
+    """
     self._WriteConfigFile(instance, block_devices, extra_args)
     result = utils.RunCmd(["xm", "create", instance.name])
 
@@ -151,8 +172,10 @@ class XenHypervisor(hv_base.BaseHypervisor):
                                     result.output))
 
   def StopInstance(self, instance, force=False):
-    """Stop an instance."""
-    self._RemoveConfigFile(instance)
+    """Stop an instance.
+
+    """
+    self._RemoveConfigFile(instance.name)
     if force:
       command = ["xm", "destroy", instance.name]
     else:
@@ -164,7 +187,9 @@ class XenHypervisor(hv_base.BaseHypervisor):
                                    (instance.name, result.fail_reason))
 
   def RebootInstance(self, instance):
-    """Reboot an instance."""
+    """Reboot an instance.
+
+    """
     result = utils.RunCmd(["xm", "reboot", instance.name])
 
     if result.failed:
@@ -174,17 +199,17 @@ class XenHypervisor(hv_base.BaseHypervisor):
   def GetNodeInfo(self):
     """Return information about the node.
 
-    The return value is a dict, which has to have the following items:
-      (all values in MiB)
-      - memory_total: the total memory size on the node
-      - memory_free: the available memory on the node for instances
-      - memory_dom0: the memory used by the node itself, if available
+    @return: a dict with the following keys (values in MiB):
+          - memory_total: the total memory size on the node
+          - memory_free: the available memory on the node for instances
+          - memory_dom0: the memory used by the node itself, if available
 
     """
     # note: in xen 3, memory has changed to total_memory
     result = utils.RunCmd(["xm", "info"])
     if result.failed:
-      logger.Error("Can't run 'xm info': %s" % result.fail_reason)
+      logging.error("Can't run 'xm info' (%s): %s", result.fail_reason,
+                    result.output)
       return None
 
     xmoutput = result.stdout.splitlines()
@@ -207,8 +232,8 @@ class XenHypervisor(hv_base.BaseHypervisor):
 
     return result
 
-  @staticmethod
-  def GetShellCommandForConsole(instance):
+  @classmethod
+  def GetShellCommandForConsole(cls, instance):
     """Return a command for connecting to the console of an instance.
 
     """
@@ -232,15 +257,12 @@ class XenHypervisor(hv_base.BaseHypervisor):
     This method builds the xen config disk directive according to the
     given disk_template and block_devices.
 
-    Args:
-      disk_template: String containing instance disk template
-      block_devices: List[tuple1,tuple2,...]
-        tuple: (cfdev, rldev)
-          cfdev: dict containing ganeti config disk part
-          rldev: ganeti.bdev.BlockDev object
+    @param disk_template: string containing instance disk template
+    @param block_devices: list of tuples (cfdev, rldev):
+        - cfdev: dict containing ganeti config disk part
+        - rldev: ganeti.bdev.BlockDev object
 
-    Returns:
-      String containing disk directive for xen instance config file
+    @return: string containing disk directive for xen instance config file
 
     """
     FILE_DRIVER_MAP = {
@@ -248,29 +270,80 @@ class XenHypervisor(hv_base.BaseHypervisor):
       constants.FD_BLKTAP: "tap:aio",
       }
     disk_data = []
-    for cfdev, rldev in block_devices:
+    if len(block_devices) > 24:
+      # 'z' - 'a' = 24
+      raise errors.HypervisorError("Too many disks")
+    # FIXME: instead of this hardcoding here, each of PVM/HVM should
+    # directly export their info (currently HVM will just sed this info)
+    namespace = ["sd" + chr(i + ord('a')) for i in range(24)]
+    for sd_name, (cfdev, dev_path) in zip(namespace, block_devices):
+      if cfdev.mode == constants.DISK_RDWR:
+        mode = "w"
+      else:
+        mode = "r"
       if cfdev.dev_type == constants.LD_FILE:
-        line = "'%s:%s,%s,w'" % (FILE_DRIVER_MAP[cfdev.physical_id[0]],
-                                 rldev.dev_path, cfdev.iv_name)
+        line = "'%s:%s,%s,%s'" % (FILE_DRIVER_MAP[cfdev.physical_id[0]],
+                                  dev_path, sd_name, mode)
       else:
-        line = "'phy:%s,%s,w'" % (rldev.dev_path, cfdev.iv_name)
+        line = "'phy:%s,%s,%s'" % (dev_path, sd_name, mode)
       disk_data.append(line)
 
     return disk_data
 
-  def MigrateInstance(self, instance, target, live):
-    """Migrate an instance to a target node.
+  def MigrationInfo(self, instance):
+    """Get instance information to perform a migration.
+
+    @type instance: L{objects.Instance}
+    @param instance: instance to be migrated
+    @rtype: string
+    @return: content of the xen config file
+
+    """
+    return self._ReadConfigFile(instance.name)
+
+  def AcceptInstance(self, instance, info, target):
+    """Prepare to accept an instance.
+
+    @type instance: L{objects.Instance}
+    @param instance: instance to be accepted
+    @type info: string
+    @param info: content of the xen config file on the source node
+    @type target: string
+    @param target: target host (usually ip), on this node
+
+    """
+    pass
+
+  def FinalizeMigration(self, instance, info, success):
+    """Finalize an instance migration.
+
+    After a successful migration we write the xen config file.
+    We do nothing on a failure, as we did not change anything at accept time.
+
+    @type instance: L{objects.Instance}
+    @param instance: instance whose migration is being aborted
+    @type info: string
+    @param info: content of the xen config file on the source node
+    @type success: boolean
+    @param success: whether the migration was a success or a failure
 
-    Arguments:
-      - instance: the name of the instance
-      - target: the ip of the target node
-      - live: whether to do live migration or not
+    """
+    if success:
+      self._WriteConfigFileStatic(instance.name, info)
 
-    Returns: none, errors will be signaled by exception.
+  def MigrateInstance(self, instance, target, live):
+    """Migrate an instance to a target node.
 
     The migration will not be attempted if the instance is not
     currently running.
 
+    @type instance: string
+    @param instance: instance name
+    @type target: string
+    @param target: ip address of the target node
+    @type live: boolean
+    @param live: perform a live migration
+
     """
     if self.GetInstanceInfo(instance) is None:
       raise errors.HypervisorError("Instance not running, cannot migrate")
@@ -282,6 +355,11 @@ class XenHypervisor(hv_base.BaseHypervisor):
     if result.failed:
       raise errors.HypervisorError("Failed to migrate instance %s: %s" %
                                    (instance, result.output))
+    # remove old xen file after migration succeeded
+    try:
+      self._RemoveConfigFile(instance)
+    except EnvironmentError:
+      logging.exception("Failure while removing instance config file")
 
 
 class XenPvmHypervisor(XenHypervisor):
@@ -290,6 +368,7 @@ class XenPvmHypervisor(XenHypervisor):
   PARAMETERS = [
     constants.HV_KERNEL_PATH,
     constants.HV_INITRD_PATH,
+    constants.HV_ROOT_PATH,
     ]
 
   @classmethod
@@ -310,11 +389,14 @@ class XenPvmHypervisor(XenHypervisor):
       raise errors.HypervisorError("Need a kernel for the instance")
 
     if not os.path.isabs(hvparams[constants.HV_KERNEL_PATH]):
-      raise errors.HypervisorError("The kernel path must an absolute path")
+      raise errors.HypervisorError("The kernel path must be an absolute path")
+
+    if not hvparams[constants.HV_ROOT_PATH]:
+      raise errors.HypervisorError("Need a root partition for the instance")
 
     if hvparams[constants.HV_INITRD_PATH]:
       if not os.path.isabs(hvparams[constants.HV_INITRD_PATH]):
-        raise errors.HypervisorError("The initrd path must an absolute path"
+        raise errors.HypervisorError("The initrd path must be an absolute path"
                                      ", if defined")
 
   def ValidateParameters(self, hvparams):
@@ -353,8 +435,8 @@ class XenPvmHypervisor(XenHypervisor):
       config.write("ramdisk = '%s'\n" % initrd_path)
 
     # rest of the settings
-    config.write("memory = %d\n" % instance.memory)
-    config.write("vcpus = %d\n" % instance.vcpus)
+    config.write("memory = %d\n" % instance.beparams[constants.BE_MEMORY])
+    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
     config.write("name = '%s'\n" % instance.name)
 
     vif_data = []
@@ -369,7 +451,9 @@ class XenPvmHypervisor(XenHypervisor):
     config.write("disk = [%s]\n" % ",".join(
                  cls._GetConfigFileDiskData(instance.disk_template,
                                             block_devices)))
-    config.write("root = '/dev/sda ro'\n")
+
+    rpath = instance.hvparams[constants.HV_ROOT_PATH]
+    config.write("root = '%s ro'\n" % rpath)
     config.write("on_poweroff = 'destroy'\n")
     config.write("on_reboot = 'restart'\n")
     config.write("on_crash = 'restart'\n")
@@ -378,14 +462,13 @@ class XenPvmHypervisor(XenHypervisor):
     # just in case it exists
     utils.RemoveFile("/etc/xen/auto/%s" % instance.name)
     try:
-      f = open("/etc/xen/%s" % instance.name, "w")
-      try:
-        f.write(config.getvalue())
-      finally:
-        f.close()
-    except IOError, err:
-      raise errors.OpExecError("Cannot write Xen instance confile"
-                               " file /etc/xen/%s: %s" % (instance.name, err))
+      utils.WriteFile("/etc/xen/%s" % instance.name,
+                      data=config.getvalue())
+    except EnvironmentError, err:
+      raise errors.HypervisorError("Cannot write Xen instance confile"
+                                   " file /etc/xen/%s: %s" %
+                                   (instance.name, err))
+
     return True
 
 
@@ -433,9 +516,9 @@ class XenHvmHypervisor(XenHypervisor):
 
     iso_path = hvparams[constants.HV_CDROM_IMAGE_PATH]
     if iso_path and not os.path.isabs(iso_path):
-        raise errors.HypervisorError("The path to the HVM CDROM image must"
-                                     " be an absolute path or None, not %s" %
-                                     iso_path)
+      raise errors.HypervisorError("The path to the HVM CDROM image must"
+                                   " be an absolute path or None, not %s" %
+                                   iso_path)
 
   def ValidateParameters(self, hvparams):
     """Check the given parameters for validity.
@@ -453,10 +536,10 @@ class XenHvmHypervisor(XenHypervisor):
     # hvm_cdrom_image_path verification
     iso_path = hvparams[constants.HV_CDROM_IMAGE_PATH]
     if iso_path and not os.path.isfile(iso_path):
-        raise errors.HypervisorError("The HVM CDROM image must either be a"
-                                     " regular file or a symlink pointing to"
-                                     " an existing regular file, not %s" %
-                                     iso_path)
+      raise errors.HypervisorError("The HVM CDROM image must either be a"
+                                   " regular file or a symlink pointing to"
+                                   " an existing regular file, not %s" %
+                                   iso_path)
 
   @classmethod
   def _WriteConfigFile(cls, instance, block_devices, extra_args):
@@ -467,8 +550,8 @@ class XenHvmHypervisor(XenHypervisor):
     config.write("# this is autogenerated by Ganeti, please do not edit\n#\n")
     config.write("kernel = '/usr/lib/xen/boot/hvmloader'\n")
     config.write("builder = 'hvm'\n")
-    config.write("memory = %d\n" % instance.memory)
-    config.write("vcpus = %d\n" % instance.vcpus)
+    config.write("memory = %d\n" % instance.beparams[constants.BE_MEMORY])
+    config.write("vcpus = %d\n" % instance.beparams[constants.BE_VCPUS])
     config.write("name = '%s'\n" % instance.name)
     if instance.hvparams[constants.HV_PAE]:
       config.write("pae = 1\n")
@@ -507,14 +590,10 @@ class XenHvmHypervisor(XenHypervisor):
       config.write("vncunused = 1\n")
 
     try:
-      password_file = open(constants.VNC_PASSWORD_FILE, "r")
-      try:
-        password = password_file.readline()
-      finally:
-        password_file.close()
-    except IOError:
-      raise errors.OpExecError("failed to open VNC password file %s " %
-                               constants.VNC_PASSWORD_FILE)
+      password = utils.ReadFile(constants.VNC_PASSWORD_FILE)
+    except EnvironmentError, err:
+      raise errors.HypervisorError("Failed to open VNC password file %s: %s" %
+                                   (constants.VNC_PASSWORD_FILE, err))
 
     config.write("vncpasswd = '%s'\n" % password.rstrip())
 
@@ -561,12 +640,11 @@ class XenHvmHypervisor(XenHypervisor):
     # just in case it exists
     utils.RemoveFile("/etc/xen/auto/%s" % instance.name)
     try:
-      f = open("/etc/xen/%s" % instance.name, "w")
-      try:
-        f.write(config.getvalue())
-      finally:
-        f.close()
-    except IOError, err:
-      raise errors.OpExecError("Cannot write Xen instance confile"
-                               " file /etc/xen/%s: %s" % (instance.name, err))
+      utils.WriteFile("/etc/xen/%s" % instance.name,
+                      data=config.getvalue())
+    except EnvironmentError, err:
+      raise errors.HypervisorError("Cannot write Xen instance confile"
+                                   " file /etc/xen/%s: %s" %
+                                   (instance.name, err))
+
     return True