Make the disks_active flag queryable
[ganeti-local] / lib / ssconf.py
index c36aa65..fc79422 100644 (file)
@@ -1,7 +1,7 @@
 #
 #
 
 #
 #
 
-# Copyright (C) 2006, 2007, 2008 Google Inc.
+# Copyright (C) 2006, 2007, 2008, 2010, 2011, 2012 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
 #
 # 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
@@ -27,89 +27,70 @@ configuration data, which is mostly static and available to all nodes.
 """
 
 import sys
 """
 
 import sys
-import re
+import errno
+import logging
 
 
+from ganeti import compat
 from ganeti import errors
 from ganeti import constants
 from ganeti import utils
 from ganeti import errors
 from ganeti import constants
 from ganeti import utils
-from ganeti import serializer
+from ganeti import netutils
+from ganeti import pathutils
 
 
 SSCONF_LOCK_TIMEOUT = 10
 
 
 
 SSCONF_LOCK_TIMEOUT = 10
 
-RE_VALID_SSCONF_NAME = re.compile(r'^[-_a-z0-9]+$')
-
-
-class SimpleConfigReader(object):
-  """Simple class to read configuration file.
+#: Valid ssconf keys
+_VALID_KEYS = compat.UniqueFrozenset([
+  constants.SS_CLUSTER_NAME,
+  constants.SS_CLUSTER_TAGS,
+  constants.SS_FILE_STORAGE_DIR,
+  constants.SS_SHARED_FILE_STORAGE_DIR,
+  constants.SS_MASTER_CANDIDATES,
+  constants.SS_MASTER_CANDIDATES_IPS,
+  constants.SS_MASTER_IP,
+  constants.SS_MASTER_NETDEV,
+  constants.SS_MASTER_NETMASK,
+  constants.SS_MASTER_NODE,
+  constants.SS_NODE_LIST,
+  constants.SS_NODE_PRIMARY_IPS,
+  constants.SS_NODE_SECONDARY_IPS,
+  constants.SS_OFFLINE_NODES,
+  constants.SS_ONLINE_NODES,
+  constants.SS_PRIMARY_IP_FAMILY,
+  constants.SS_INSTANCE_LIST,
+  constants.SS_RELEASE_VERSION,
+  constants.SS_HYPERVISOR_LIST,
+  constants.SS_MAINTAIN_NODE_HEALTH,
+  constants.SS_UID_POOL,
+  constants.SS_NODEGROUPS,
+  constants.SS_NETWORKS,
+  ])
+
+#: Maximum size for ssconf files
+_MAX_SIZE = 128 * 1024
+
+
+def ReadSsconfFile(filename):
+  """Reads an ssconf file and verifies its size.
+
+  @type filename: string
+  @param filename: Path to file
+  @rtype: string
+  @return: File contents without newlines at the end
+  @raise RuntimeError: When the file size exceeds L{_MAX_SIZE}
 
   """
 
   """
-  def __init__(self, file_name=constants.CLUSTER_CONF_FILE):
-    """Initializes this class.
-
-    @type file_name: string
-    @param file_name: Configuration file path
-
-    """
-    self._file_name = file_name
-    self._config_data = serializer.Load(utils.ReadFile(file_name))
-    # TODO: Error handling
-
-  def GetClusterName(self):
-    return self._config_data["cluster"]["cluster_name"]
-
-  def GetHostKey(self):
-    return self._config_data["cluster"]["rsahostkeypub"]
+  statcb = utils.FileStatHelper()
 
 
-  def GetMasterNode(self):
-    return self._config_data["cluster"]["master_node"]
-
-  def GetMasterIP(self):
-    return self._config_data["cluster"]["master_ip"]
-
-  def GetMasterNetdev(self):
-    return self._config_data["cluster"]["master_netdev"]
-
-  def GetFileStorageDir(self):
-    return self._config_data["cluster"]["file_storage_dir"]
+  data = utils.ReadFile(filename, size=_MAX_SIZE, preread=statcb)
 
 
-  def GetHypervisorType(self):
-    return self._config_data["cluster"]["hypervisor"]
+  if statcb.st.st_size > _MAX_SIZE:
+    msg = ("File '%s' has a size of %s bytes (up to %s allowed)" %
+           (filename, statcb.st.st_size, _MAX_SIZE))
+    raise RuntimeError(msg)
 
 
-  def GetNodeList(self):
-    return self._config_data["nodes"].keys()
-
-  @classmethod
-  def FromDict(cls, val, cfg_file=constants.CLUSTER_CONF_FILE):
-    """Alternative construction from a dictionary.
-
-    """
-    obj = SimpleConfigReader.__new__(cls)
-    obj._config_data = val
-    obj._file_name = cfg_file
-    return obj
-
-
-class SimpleConfigWriter(SimpleConfigReader):
-  """Simple class to write configuration file.
-
-  """
-  def SetMasterNode(self, node):
-    """Change master node.
-
-    """
-    self._config_data["cluster"]["master_node"] = node
-
-  def Save(self):
-    """Writes configuration file.
-
-    Warning: Doesn't take care of locking or synchronizing with other
-    processes.
-
-    """
-    utils.WriteFile(self._file_name,
-                    data=serializer.Dump(self._config_data),
-                    mode=0600)
+  return data.rstrip("\n")
 
 
 class SimpleStore(object):
 
 
 class SimpleStore(object):
@@ -123,36 +104,26 @@ class SimpleStore(object):
     - keys are restricted to predefined values
 
   """
     - keys are restricted to predefined values
 
   """
-  _SS_FILEPREFIX = "ssconf_"
-  _VALID_KEYS = (
-    constants.SS_CLUSTER_NAME,
-    constants.SS_FILE_STORAGE_DIR,
-    constants.SS_MASTER_CANDIDATES,
-    constants.SS_MASTER_IP,
-    constants.SS_MASTER_NETDEV,
-    constants.SS_MASTER_NODE,
-    constants.SS_NODE_LIST,
-    )
-  _MAX_SIZE = 131072
-
-  def __init__(self, cfg_location=None):
+  def __init__(self, cfg_location=None, _lockfile=pathutils.SSCONF_LOCK_FILE):
     if cfg_location is None:
     if cfg_location is None:
-      self._cfg_dir = constants.DATA_DIR
+      self._cfg_dir = pathutils.DATA_DIR
     else:
       self._cfg_dir = cfg_location
 
     else:
       self._cfg_dir = cfg_location
 
+    self._lockfile = _lockfile
+
   def KeyToFilename(self, key):
     """Convert a given key into filename.
 
     """
   def KeyToFilename(self, key):
     """Convert a given key into filename.
 
     """
-    if key not in self._VALID_KEYS:
+    if key not in _VALID_KEYS:
       raise errors.ProgrammerError("Invalid key requested from SSConf: '%s'"
                                    % str(key))
 
       raise errors.ProgrammerError("Invalid key requested from SSConf: '%s'"
                                    % str(key))
 
-    filename = self._cfg_dir + '/' + self._SS_FILEPREFIX + key
+    filename = self._cfg_dir + "/" + constants.SSCONF_FILEPREFIX + key
     return filename
 
     return filename
 
-  def _ReadFile(self, key):
+  def _ReadFile(self, key, default=None):
     """Generic routine to read keys.
 
     This will read the file which holds the value requested. Errors
     """Generic routine to read keys.
 
     This will read the file which holds the value requested. Errors
@@ -161,25 +132,43 @@ class SimpleStore(object):
     """
     filename = self.KeyToFilename(key)
     try:
     """
     filename = self.KeyToFilename(key)
     try:
-      fh = file(filename, 'r')
-      try:
-        data = fh.read(self._MAX_SIZE)
-        data = data.rstrip('\n')
-      finally:
-        fh.close()
+      return ReadSsconfFile(filename)
     except EnvironmentError, err:
     except EnvironmentError, err:
-      raise errors.ConfigurationError("Can't read from the ssconf file:"
-                                      " '%s'" % str(err))
-    return data
+      if err.errno == errno.ENOENT and default is not None:
+        return default
+      raise errors.ConfigurationError("Can't read ssconf file %s: %s" %
+                                      (filename, str(err)))
+
+  def ReadAll(self):
+    """Reads all keys and returns their values.
 
 
-  def WriteFiles(self, values):
+    @rtype: dict
+    @return: Dictionary, ssconf key as key, value as value
+
+    """
+    result = []
+
+    for key in _VALID_KEYS:
+      try:
+        value = self._ReadFile(key)
+      except errors.ConfigurationError:
+        # Ignore non-existing files
+        pass
+      else:
+        result.append((key, value))
+
+    return dict(result)
+
+  def WriteFiles(self, values, dry_run=False):
     """Writes ssconf files used by external scripts.
 
     @type values: dict
     @param values: Dictionary of (name, value)
     """Writes ssconf files used by external scripts.
 
     @type values: dict
     @param values: Dictionary of (name, value)
+    @type dry_run boolean
+    @param dry_run: Whether to perform a dry run
 
     """
 
     """
-    ssconf_lock = utils.FileLock(constants.SSCONF_LOCK_FILE)
+    ssconf_lock = utils.FileLock.Open(self._lockfile)
 
     # Get lock while writing files
     ssconf_lock.Exclusive(blocking=True, timeout=SSCONF_LOCK_TIMEOUT)
 
     # Get lock while writing files
     ssconf_lock.Exclusive(blocking=True, timeout=SSCONF_LOCK_TIMEOUT)
@@ -187,7 +176,15 @@ class SimpleStore(object):
       for name, value in values.iteritems():
         if value and not value.endswith("\n"):
           value += "\n"
       for name, value in values.iteritems():
         if value and not value.endswith("\n"):
           value += "\n"
-        utils.WriteFile(self.KeyToFilename(name), data=value)
+
+        if len(value) > _MAX_SIZE:
+          msg = ("Value '%s' has a length of %s bytes, but only up to %s are"
+                 " allowed" % (name, len(value), _MAX_SIZE))
+          raise errors.ConfigurationError(msg)
+
+        utils.WriteFile(self.KeyToFilename(name), data=value,
+                        mode=constants.SS_FILE_PERMS,
+                        dry_run=dry_run)
     finally:
       ssconf_lock.Unlock()
 
     finally:
       ssconf_lock.Unlock()
 
@@ -197,7 +194,7 @@ class SimpleStore(object):
     This is used for computing node replication data.
 
     """
     This is used for computing node replication data.
 
     """
-    return [self.KeyToFilename(key) for key in self._VALID_KEYS]
+    return [self.KeyToFilename(key) for key in _VALID_KEYS]
 
   def GetClusterName(self):
     """Get the cluster name.
 
   def GetClusterName(self):
     """Get the cluster name.
@@ -211,6 +208,12 @@ class SimpleStore(object):
     """
     return self._ReadFile(constants.SS_FILE_STORAGE_DIR)
 
     """
     return self._ReadFile(constants.SS_FILE_STORAGE_DIR)
 
+  def GetSharedFileStorageDir(self):
+    """Get the shared file storage dir.
+
+    """
+    return self._ReadFile(constants.SS_SHARED_FILE_STORAGE_DIR)
+
   def GetMasterCandidates(self):
     """Return the list of master candidates.
 
   def GetMasterCandidates(self):
     """Return the list of master candidates.
 
@@ -219,6 +222,14 @@ class SimpleStore(object):
     nl = data.splitlines(False)
     return nl
 
     nl = data.splitlines(False)
     return nl
 
+  def GetMasterCandidatesIPList(self):
+    """Return the list of master candidates' primary IP.
+
+    """
+    data = self._ReadFile(constants.SS_MASTER_CANDIDATES_IPS)
+    nl = data.splitlines(False)
+    return nl
+
   def GetMasterIP(self):
     """Get the IP of the master node for this cluster.
 
   def GetMasterIP(self):
     """Get the IP of the master node for this cluster.
 
@@ -231,6 +242,17 @@ class SimpleStore(object):
     """
     return self._ReadFile(constants.SS_MASTER_NETDEV)
 
     """
     return self._ReadFile(constants.SS_MASTER_NETDEV)
 
+  def GetMasterNetmask(self):
+    """Get the master netmask.
+
+    """
+    try:
+      return self._ReadFile(constants.SS_MASTER_NETMASK)
+    except errors.ConfigurationError:
+      family = self.GetPrimaryIPFamily()
+      ipcls = netutils.IPAddress.GetClassFromIpFamily(family)
+      return ipcls.iplen
+
   def GetMasterNode(self):
     """Get the hostname of the master node for this cluster.
 
   def GetMasterNode(self):
     """Get the hostname of the master node for this cluster.
 
@@ -245,6 +267,96 @@ class SimpleStore(object):
     nl = data.splitlines(False)
     return nl
 
     nl = data.splitlines(False)
     return nl
 
+  def GetNodePrimaryIPList(self):
+    """Return the list of cluster nodes' primary IP.
+
+    """
+    data = self._ReadFile(constants.SS_NODE_PRIMARY_IPS)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetNodeSecondaryIPList(self):
+    """Return the list of cluster nodes' secondary IP.
+
+    """
+    data = self._ReadFile(constants.SS_NODE_SECONDARY_IPS)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetNodegroupList(self):
+    """Return the list of nodegroups.
+
+    """
+    data = self._ReadFile(constants.SS_NODEGROUPS)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetNetworkList(self):
+    """Return the list of networks.
+
+    """
+    data = self._ReadFile(constants.SS_NETWORKS)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetClusterTags(self):
+    """Return the cluster tags.
+
+    """
+    data = self._ReadFile(constants.SS_CLUSTER_TAGS)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetHypervisorList(self):
+    """Return the list of enabled hypervisors.
+
+    """
+    data = self._ReadFile(constants.SS_HYPERVISOR_LIST)
+    nl = data.splitlines(False)
+    return nl
+
+  def GetMaintainNodeHealth(self):
+    """Return the value of the maintain_node_health option.
+
+    """
+    data = self._ReadFile(constants.SS_MAINTAIN_NODE_HEALTH)
+    # we rely on the bool serialization here
+    return data == "True"
+
+  def GetUidPool(self):
+    """Return the user-id pool definition string.
+
+    The separator character is a newline.
+
+    The return value can be parsed using uidpool.ParseUidPool()::
+
+      ss = ssconf.SimpleStore()
+      uid_pool = uidpool.ParseUidPool(ss.GetUidPool(), separator="\\n")
+
+    """
+    data = self._ReadFile(constants.SS_UID_POOL)
+    return data
+
+  def GetPrimaryIPFamily(self):
+    """Return the cluster-wide primary address family.
+
+    """
+    try:
+      return int(self._ReadFile(constants.SS_PRIMARY_IP_FAMILY,
+                                default=netutils.IP4Address.family))
+    except (ValueError, TypeError), err:
+      raise errors.ConfigurationError("Error while trying to parse primary IP"
+                                      " family: %s" % err)
+
+
+def WriteSsconfFiles(values, dry_run=False):
+  """Update all ssconf files.
+
+  Wrapper around L{SimpleStore.WriteFiles}.
+
+  """
+  SimpleStore().WriteFiles(values, dry_run=dry_run)
+
 
 def GetMasterAndMyself(ss=None):
   """Get the master node and my own hostname.
 
 def GetMasterAndMyself(ss=None):
   """Get the master node and my own hostname.
@@ -263,7 +375,7 @@ def GetMasterAndMyself(ss=None):
   """
   if ss is None:
     ss = SimpleStore()
   """
   if ss is None:
     ss = SimpleStore()
-  return ss.GetMasterNode(), utils.HostInfo().name
+  return ss.GetMasterNode(), netutils.Hostname.GetSysName()
 
 
 def CheckMaster(debug, ss=None):
 
 
 def CheckMaster(debug, ss=None):
@@ -286,3 +398,35 @@ def CheckMaster(debug, ss=None):
     if debug:
       sys.stderr.write("Not master, exiting.\n")
     sys.exit(constants.EXIT_NOTMASTER)
     if debug:
       sys.stderr.write("Not master, exiting.\n")
     sys.exit(constants.EXIT_NOTMASTER)
+
+
+def VerifyClusterName(name, _cfg_location=None):
+  """Verifies cluster name against a local cluster name.
+
+  @type name: string
+  @param name: Cluster name
+
+  """
+  sstore = SimpleStore(cfg_location=_cfg_location)
+
+  try:
+    local_name = sstore.GetClusterName()
+  except errors.ConfigurationError, err:
+    logging.debug("Can't get local cluster name: %s", err)
+  else:
+    if name != local_name:
+      raise errors.GenericError("Current cluster name is '%s'" % local_name)
+
+
+def VerifyKeys(keys):
+  """Raises an exception if unknown ssconf keys are given.
+
+  @type keys: sequence
+  @param keys: Key names to verify
+  @raise errors.GenericError: When invalid keys were found
+
+  """
+  invalid = frozenset(keys) - _VALID_KEYS
+  if invalid:
+    raise errors.GenericError("Invalid ssconf keys: %s" %
+                              utils.CommaJoin(sorted(invalid)))