4 # Copyright (C) 2007, 2011, 2012, 2013 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
28 from ganeti import constants
29 from ganeti import utils
30 from ganeti import serializer
31 from ganeti import compat
36 _INSTANCE_CHECK_KEY = "instance-check"
37 _ENABLED_HV_KEY = "enabled-hypervisors"
39 #: Cluster-wide run-time value of the exclusive storage flag
40 _exclusive_storage = None
43 #: QA configuration (L{_QaConfig})
47 class _QaConfig(object):
48 def __init__(self, data):
49 """Initializes instances of this class.
55 def Load(cls, filename):
56 """Loads a configuration file and produces a configuration object.
58 @type filename: string
59 @param filename: Path to configuration file
63 data = serializer.LoadJson(utils.ReadFile(filename))
71 """Validates loaded configuration data.
74 if not self.get("nodes"):
75 raise qa_error.Error("Need at least one node")
77 if not self.get("instances"):
78 raise qa_error.Error("Need at least one instance")
80 if (self.get("disk") is None or
81 self.get("disk-growth") is None or
82 len(self.get("disk")) != len(self.get("disk-growth"))):
83 raise qa_error.Error("Config options 'disk' and 'disk-growth' must exist"
84 " and have the same number of items")
86 check = self.GetInstanceCheckScript()
90 except EnvironmentError, err:
91 raise qa_error.Error("Can't find instance check script '%s': %s" %
94 enabled_hv = frozenset(self.GetEnabledHypervisors())
96 raise qa_error.Error("No hypervisor is enabled")
98 difference = enabled_hv - constants.HYPER_TYPES
100 raise qa_error.Error("Unknown hypervisor(s) enabled: %s" %
101 utils.CommaJoin(difference))
103 def __getitem__(self, name):
104 """Returns configuration value.
107 @param name: Name of configuration entry
110 return self._data[name]
112 def get(self, name, default=None):
113 """Returns configuration value.
116 @param name: Name of configuration entry
117 @param default: Default value
120 return self._data.get(name, default)
122 def GetMasterNode(self):
123 """Returns the default master node for the cluster.
126 return self["nodes"][0]
128 def GetInstanceCheckScript(self):
129 """Returns path to instance check script or C{None}.
132 return self._data.get(_INSTANCE_CHECK_KEY, None)
134 def GetEnabledHypervisors(self):
135 """Returns list of enabled hypervisors.
141 value = self._data[_ENABLED_HV_KEY]
143 return [constants.DEFAULT_ENABLED_HYPERVISOR]
147 elif isinstance(value, basestring):
148 # The configuration key ("enabled-hypervisors") implies there can be
149 # multiple values. Multiple hypervisors are comma-separated on the
150 # command line option to "gnt-cluster init", so we need to handle them
152 return value.split(",")
156 def GetDefaultHypervisor(self):
157 """Returns the default hypervisor to be used.
160 return self.GetEnabledHypervisors()[0]
164 """Loads the passed configuration file.
167 global _config # pylint: disable=W0603
169 _config = _QaConfig.Load(path)
173 """Returns the configuration object.
177 raise RuntimeError("Configuration not yet loaded")
182 def get(name, default=None):
183 """Wrapper for L{_QaConfig.get}.
186 return GetConfig().get(name, default=default)
190 def __init__(self, tests):
191 """Initializes this class.
193 @type tests: list or string
194 @param tests: List of test names
195 @see: L{TestEnabled} for details
201 def _MakeSequence(value):
202 """Make sequence of single argument.
204 If the single argument is not already a list or tuple, a list with the
205 argument as a single item is returned.
208 if isinstance(value, (list, tuple)):
214 def _TestEnabledInner(check_fn, names, fn):
215 """Evaluate test conditions.
217 @type check_fn: callable
218 @param check_fn: Callback to check whether a test is enabled
219 @type names: sequence or string
220 @param names: Test name(s)
222 @param fn: Aggregation function
224 @return: Whether test is enabled
227 names = _MakeSequence(names)
232 if isinstance(name, Either):
233 value = _TestEnabledInner(check_fn, name.tests, compat.any)
234 elif isinstance(name, (list, tuple)):
235 value = _TestEnabledInner(check_fn, name, compat.all)
237 value = check_fn(name)
244 def TestEnabled(tests, _cfg=None):
245 """Returns True if the given tests are enabled.
247 @param tests: A single test as a string, or a list of tests to check; can
248 contain L{Either} for OR conditions, AND is default
256 # Get settings for all tests
257 cfg_tests = cfg.get("tests", {})
259 # Get default setting
260 default = cfg_tests.get("default", True)
262 return _TestEnabledInner(lambda name: cfg_tests.get(name, default),
266 def GetInstanceCheckScript(*args):
267 """Wrapper for L{_QaConfig.GetInstanceCheckScript}.
270 return GetConfig().GetInstanceCheckScript(*args)
273 def GetEnabledHypervisors(*args):
274 """Wrapper for L{_QaConfig.GetEnabledHypervisors}.
277 return GetConfig().GetEnabledHypervisors(*args)
280 def GetDefaultHypervisor(*args):
281 """Wrapper for L{_QaConfig.GetDefaultHypervisor}.
284 return GetConfig().GetDefaultHypervisor(*args)
287 def GetInstanceNicMac(inst, default=None):
288 """Returns MAC address for instance's network interface.
291 return inst.get("nic.mac/0", default)
295 """Wrapper for L{_QaConfig.GetMasterNode}.
298 return GetConfig().GetMasterNode()
301 def AcquireInstance():
302 """Returns an instance which isn't in use.
305 # Filter out unwanted instances
306 tmp_flt = lambda inst: not inst.get("_used", False)
307 instances = filter(tmp_flt, GetConfig()["instances"])
310 if len(instances) == 0:
311 raise qa_error.OutOfInstancesError("No instances left")
315 inst["_template"] = None
319 def ReleaseInstance(inst):
320 inst["_used"] = False
323 def GetInstanceTemplate(inst):
324 """Return the disk template of an instance.
327 templ = inst["_template"]
328 assert templ is not None
332 def SetInstanceTemplate(inst, template):
333 """Set the disk template for an instance.
336 inst["_template"] = template
339 def SetExclusiveStorage(value):
340 """Set the expected value of the exclusive_storage flag for the cluster.
343 global _exclusive_storage # pylint: disable=W0603
345 _exclusive_storage = bool(value)
348 def GetExclusiveStorage():
349 """Get the expected value of the exclusive_storage flag for the cluster.
352 val = _exclusive_storage
353 assert val is not None
357 def IsTemplateSupported(templ):
358 """Is the given disk template supported by the current configuration?
361 if GetExclusiveStorage():
362 return templ in constants.DTS_EXCL_STORAGE
367 def AcquireNode(exclude=None):
368 """Returns the least used node.
371 master = GetMasterNode()
374 # Filter out unwanted nodes
375 # TODO: Maybe combine filters
377 nodes = cfg["nodes"][:]
378 elif isinstance(exclude, (list, tuple)):
379 nodes = filter(lambda node: node not in exclude, cfg["nodes"])
381 nodes = filter(lambda node: node != exclude, cfg["nodes"])
383 tmp_flt = lambda node: node.get("_added", False) or node == master
384 nodes = filter(tmp_flt, nodes)
388 raise qa_error.OutOfNodesError("No nodes left")
390 # Get node with least number of uses
392 result = cmp(a.get("_count", 0), b.get("_count", 0))
394 result = cmp(a["primary"], b["primary"])
397 nodes.sort(cmp=compare)
400 node["_count"] = node.get("_count", 0) + 1
404 def AcquireManyNodes(num, exclude=None):
405 """Return the least used nodes.
408 @param num: Number of nodes; can be 0.
409 @type exclude: list of nodes or C{None}
410 @param exclude: nodes to be excluded from the choice
411 @rtype: list of nodes
412 @return: C{num} different nodes
418 elif isinstance(exclude, (list, tuple)):
419 # Don't modify the incoming argument
420 exclude = list(exclude)
425 for _ in range(0, num):
426 n = AcquireNode(exclude=exclude)
429 except qa_error.OutOfNodesError:
430 ReleaseManyNodes(nodes)
435 def ReleaseNode(node):
436 node["_count"] = node.get("_count", 0) - 1
439 def ReleaseManyNodes(nodes):