QA: Convert instances to objects
[ganeti-local] / qa / qa_config.py
index 9b50efb..879cff9 100644 (file)
@@ -36,14 +36,88 @@ import qa_error
 _INSTANCE_CHECK_KEY = "instance-check"
 _ENABLED_HV_KEY = "enabled-hypervisors"
 
-#: Cluster-wide run-time value of the exclusive storage flag
-_exclusive_storage = None
-
-
 #: QA configuration (L{_QaConfig})
 _config = None
 
 
+class _QaInstance(object):
+  __slots__ = [
+    "name",
+    "nicmac",
+    "used",
+    "disk_template",
+    ]
+
+  def __init__(self, name, nicmac):
+    """Initializes instances of this class.
+
+    """
+    self.name = name
+    self.nicmac = nicmac
+    self.used = None
+    self.disk_template = None
+
+  @classmethod
+  def FromDict(cls, data):
+    """Creates instance object from JSON dictionary.
+
+    """
+    nicmac = []
+
+    macaddr = data.get("nic.mac/0")
+    if macaddr:
+      nicmac.append(macaddr)
+
+    return cls(name=data["name"], nicmac=nicmac)
+
+  def __getitem__(self, key):
+    """Legacy dict-like interface.
+
+    """
+    if key == "name":
+      return self.name
+    else:
+      raise KeyError(key)
+
+  def get(self, key, default):
+    """Legacy dict-like interface.
+
+    """
+    try:
+      return self[key]
+    except KeyError:
+      return default
+
+  def GetNicMacAddr(self, idx, default):
+    """Returns MAC address for NIC.
+
+    @type idx: int
+    @param idx: NIC index
+    @param default: Default value
+
+    """
+    if len(self.nicmac) > idx:
+      return self.nicmac[idx]
+    else:
+      return default
+
+
+_RESOURCE_CONVERTER = {
+  "instances": _QaInstance.FromDict,
+  }
+
+
+def _ConvertResources((key, value)):
+  """Converts cluster resources in configuration to Python objects.
+
+  """
+  fn = _RESOURCE_CONVERTER.get(key, None)
+  if fn:
+    return (key, map(fn, value))
+  else:
+    return (key, value)
+
+
 class _QaConfig(object):
   def __init__(self, data):
     """Initializes instances of this class.
@@ -51,6 +125,9 @@ class _QaConfig(object):
     """
     self._data = data
 
+    #: Cluster-wide run-time value of the exclusive storage flag
+    self._exclusive_storage = None
+
   @classmethod
   def Load(cls, filename):
     """Loads a configuration file and produces a configuration object.
@@ -62,7 +139,8 @@ class _QaConfig(object):
     """
     data = serializer.LoadJson(utils.ReadFile(filename))
 
-    result = cls(data)
+    result = cls(dict(map(_ConvertResources,
+                          data.items()))) # pylint: disable=E1103
     result.Validate()
 
     return result
@@ -159,6 +237,27 @@ class _QaConfig(object):
     """
     return self.GetEnabledHypervisors()[0]
 
+  def SetExclusiveStorage(self, value):
+    """Set the expected value of the C{exclusive_storage} flag for the cluster.
+
+    """
+    self._exclusive_storage = bool(value)
+
+  def GetExclusiveStorage(self):
+    """Get the expected value of the C{exclusive_storage} flag for the cluster.
+
+    """
+    value = self._exclusive_storage
+    assert value is not None
+    return value
+
+  def IsTemplateSupported(self, templ):
+    """Is the given disk template supported by the current configuration?
+
+    """
+    return (not self.GetExclusiveStorage() or
+            templ in constants.DTS_EXCL_STORAGE)
+
 
 def Load(path):
   """Loads the passed configuration file.
@@ -288,7 +387,7 @@ def GetInstanceNicMac(inst, default=None):
   """Returns MAC address for instance's network interface.
 
   """
-  return inst.get("nic.mac/0", default)
+  return inst.GetNicMacAddr(0, default)
 
 
 def GetMasterNode():
@@ -298,33 +397,41 @@ def GetMasterNode():
   return GetConfig().GetMasterNode()
 
 
-def AcquireInstance():
+def AcquireInstance(_cfg=None):
   """Returns an instance which isn't in use.
 
   """
+  if _cfg is None:
+    cfg = GetConfig()
+  else:
+    cfg = _cfg
+
   # Filter out unwanted instances
-  tmp_flt = lambda inst: not inst.get("_used", False)
-  instances = filter(tmp_flt, GetConfig()["instances"])
-  del tmp_flt
+  instances = filter(lambda inst: not inst.used, cfg["instances"])
 
-  if len(instances) == 0:
+  if not instances:
     raise qa_error.OutOfInstancesError("No instances left")
 
   inst = instances[0]
-  inst["_used"] = True
-  inst["_template"] = None
+
+  assert not inst.used
+  assert inst.disk_template is None
+
+  inst.used = True
+
   return inst
 
 
 def ReleaseInstance(inst):
-  inst["_used"] = False
+  inst.used = False
+  inst.disk_template = None
 
 
 def GetInstanceTemplate(inst):
   """Return the disk template of an instance.
 
   """
-  templ = inst["_template"]
+  templ = inst.disk_template
   assert templ is not None
   return templ
 
@@ -333,35 +440,28 @@ def SetInstanceTemplate(inst, template):
   """Set the disk template for an instance.
 
   """
-  inst["_template"] = template
+  inst.disk_template = template
 
 
 def SetExclusiveStorage(value):
-  """Set the expected value of the exclusive_storage flag for the cluster.
+  """Wrapper for L{_QaConfig.SetExclusiveStorage}.
 
   """
-  global _exclusive_storage # pylint: disable=W0603
-
-  _exclusive_storage = bool(value)
+  return GetConfig().SetExclusiveStorage(value)
 
 
 def GetExclusiveStorage():
-  """Get the expected value of the exclusive_storage flag for the cluster.
+  """Wrapper for L{_QaConfig.GetExclusiveStorage}.
 
   """
-  val = _exclusive_storage
-  assert val is not None
-  return val
+  return GetConfig().GetExclusiveStorage()
 
 
 def IsTemplateSupported(templ):
-  """Is the given disk template supported by the current configuration?
+  """Wrapper for L{_QaConfig.GetExclusiveStorage}.
 
   """
-  if GetExclusiveStorage():
-    return templ in constants.DTS_EXCL_STORAGE
-  else:
-    return True
+  return GetConfig().IsTemplateSupported(templ)
 
 
 def AcquireNode(exclude=None):