Fix handling of ^C in the CLI scripts
[ganeti-local] / lib / hypervisor / hv_base.py
index 7f10047..ec47400 100644 (file)
@@ -1,7 +1,7 @@
 #
 #
 
-# Copyright (C) 2006, 2007, 2008 Google Inc.
+# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
 #
 # This program is free software; you can redistribute it and/or modify
 # it under the terms of the GNU General Public License as published by
@@ -39,28 +39,48 @@ dict is the same, see the docstring for L{BaseHypervisor.PARAMETERS}.
 
 import os
 import re
+import logging
 
 
 from ganeti import errors
 from ganeti import utils
+from ganeti import constants
+
+
+def _IsCpuMaskWellFormed(cpu_mask):
+  try:
+    cpu_list = utils.ParseCpuMask(cpu_mask)
+  except errors.ParseError, _:
+    return False
+  return isinstance(cpu_list, list) and len(cpu_list) > 0
 
 
 # Read the BaseHypervisor.PARAMETERS docstring for the syntax of the
 # _CHECK values
 
 # must be afile
-_FILE_CHECK = (os.path.isabs, "must be an absolute path",
+_FILE_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
               os.path.isfile, "not found or not a file")
 
 # must be a directory
-_DIR_CHECK = (os.path.isabs, "must be an absolute path",
+_DIR_CHECK = (utils.IsNormAbsPath, "must be an absolute normalized path",
              os.path.isdir, "not found or not a directory")
 
+# CPU mask must be well-formed
+# TODO: implement node level check for the CPU mask
+_CPU_MASK_CHECK = (_IsCpuMaskWellFormed,
+                   "CPU mask definition is not well-formed",
+                   None, None)
+
 # nice wrappers for users
 REQ_FILE_CHECK = (True, ) + _FILE_CHECK
 OPT_FILE_CHECK = (False, ) + _FILE_CHECK
 REQ_DIR_CHECK = (True, ) + _DIR_CHECK
 OPT_DIR_CHECK = (False, ) + _DIR_CHECK
+NET_PORT_CHECK = (True, lambda x: x > 0 and x < 65535, "invalid port number",
+                  None, None)
+OPT_CPU_MASK_CHECK = (False, ) + _CPU_MASK_CHECK
+REQ_CPU_MASK_CHECK = (True, ) + _CPU_MASK_CHECK
 
 # no checks at all
 NO_CHECK = (False, None, None, None, None)
@@ -68,6 +88,11 @@ NO_CHECK = (False, None, None, None, None)
 # required, but no other checks
 REQUIRED_CHECK = (True, None, None, None, None)
 
+# migration type
+MIGRATION_MODE_CHECK = (True, lambda x: x in constants.HT_MIGRATION_MODES,
+                        "invalid migration mode", None, None)
+
+
 def ParamInSet(required, my_set):
   """Builds parameter checker for set membership.
 
@@ -97,9 +122,14 @@ class BaseHypervisor(object):
           - a function to check for parameter validity on the remote node,
             in the L{ValidateParameters} function
           - an error message for the above function
+  @type CAN_MIGRATE: boolean
+  @cvar CAN_MIGRATE: whether this hypervisor can do migration (either
+      live or non-live)
 
   """
   PARAMETERS = {}
+  ANCILLARY_FILES = []
+  CAN_MIGRATE = False
 
   def __init__(self):
     pass
@@ -108,10 +138,35 @@ class BaseHypervisor(object):
     """Start an instance."""
     raise NotImplementedError
 
-  def StopInstance(self, instance, force=False):
-    """Stop an instance."""
+  def StopInstance(self, instance, force=False, retry=False, name=None):
+    """Stop an instance
+
+    @type instance: L{objects.Instance}
+    @param instance: instance to stop
+    @type force: boolean
+    @param force: whether to do a "hard" stop (destroy)
+    @type retry: boolean
+    @param retry: whether this is just a retry call
+    @type name: string or None
+    @param name: if this parameter is passed, the the instance object
+        should not be used (will be passed as None), and the shutdown
+        must be done by name only
+
+    """
     raise NotImplementedError
 
+  def CleanupInstance(self, instance_name):
+    """Cleanup after a stopped instance
+
+    This is an optional method, used by hypervisors that need to cleanup after
+    an instance has been stopped.
+
+    @type instance_name: string
+    @param instance_name: instance name to cleanup after
+
+    """
+    pass
+
   def RebootInstance(self, instance):
     """Reboot an instance."""
     raise NotImplementedError
@@ -151,19 +206,32 @@ class BaseHypervisor(object):
     raise NotImplementedError
 
   @classmethod
-  def GetShellCommandForConsole(cls, instance, hvparams, beparams):
-    """Return a command for connecting to the console of an instance.
+  def GetInstanceConsole(cls, instance, hvparams, beparams):
+    """Return information for connecting to the console of an instance.
 
     """
     raise NotImplementedError
 
+  @classmethod
+  def GetAncillaryFiles(cls):
+    """Return a list of ancillary files to be copied to all nodes as ancillary
+    configuration files.
+
+    @rtype: list of strings
+    @return: list of absolute paths of files to ship cluster-wide
+
+    """
+    # By default we return a member variable, so that if an hypervisor has just
+    # a static list of files it doesn't have to override this function.
+    return cls.ANCILLARY_FILES
+
   def Verify(self):
     """Verify the hypervisor.
 
     """
     raise NotImplementedError
 
-  def MigrationInfo(self, instance):
+  def MigrationInfo(self, instance): # pylint: disable-msg=R0201,W0613
     """Get instance information to perform a migration.
 
     By default assume no information is needed.
@@ -198,7 +266,7 @@ class BaseHypervisor(object):
     Since by default we do no preparation, we also don't have anything to do
 
     @type instance: L{objects.Instance}
-    @param instance: instance whose migration is being aborted
+    @param instance: instance whose migration is being finalized
     @type info: string/data (opaque)
     @param info: migration information, from the source node
     @type success: boolean
@@ -207,11 +275,11 @@ class BaseHypervisor(object):
     """
     pass
 
-  def MigrateInstance(self, name, target, live):
+  def MigrateInstance(self, instance, target, live):
     """Migrate an instance.
 
-    @type name: string
-    @param name: name of the instance to be migrated
+    @type instance: L{objects.Instance}
+    @param instance: the instance to be migrated
     @type target: string
     @param target: hostname (usually ip) of the target node
     @type live: boolean
@@ -272,7 +340,19 @@ class BaseHypervisor(object):
                                      " validation: %s (current value: '%s')" %
                                      (name, errstr, value))
 
-  def GetLinuxNodeInfo(self):
+  @classmethod
+  def PowercycleNode(cls):
+    """Hard powercycle a node using hypervisor specific methods.
+
+    This method should hard powercycle the node, using whatever
+    methods the hypervisor provides. Note that this means that all
+    instances running on the node must be stopped too.
+
+    """
+    raise NotImplementedError
+
+  @staticmethod
+  def GetLinuxNodeInfo():
     """For linux systems, return actual OS information.
 
     This is an abstraction for all non-hypervisor-based classes, where
@@ -288,11 +368,7 @@ class BaseHypervisor(object):
 
     """
     try:
-      fh = file("/proc/meminfo")
-      try:
-        data = fh.readlines()
-      finally:
-        fh.close()
+      data = utils.ReadFile("/proc/meminfo").splitlines()
     except EnvironmentError, err:
       raise errors.HypervisorError("Failed to list node info: %s" % (err,))
 
@@ -332,3 +408,20 @@ class BaseHypervisor(object):
     result['cpu_sockets'] = 1
 
     return result
+
+  @classmethod
+  def LinuxPowercycle(cls):
+    """Linux-specific powercycle method.
+
+    """
+    try:
+      fd = os.open("/proc/sysrq-trigger", os.O_WRONLY)
+      try:
+        os.write(fd, "b")
+      finally:
+        fd.close()
+    except OSError:
+      logging.exception("Can't open the sysrq-trigger file")
+      result = utils.RunCmd(["reboot", "-n", "-f"])
+      if not result:
+        logging.error("Can't run shutdown: %s", result.output)