Statistics
| Branch: | Tag: | Revision:

root / qa / qa_config.py @ cf62af3a

History | View | Annotate | Download (10.3 kB)

1
#
2
#
3

    
4
# Copyright (C) 2007, 2011, 2012, 2013 Google Inc.
5
#
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.
10
#
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.
15
#
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
19
# 02110-1301, USA.
20

    
21

    
22
"""QA configuration.
23

24
"""
25

    
26
import os
27

    
28
from ganeti import constants
29
from ganeti import utils
30
from ganeti import serializer
31
from ganeti import compat
32

    
33
import qa_error
34

    
35

    
36
_INSTANCE_CHECK_KEY = "instance-check"
37
_ENABLED_HV_KEY = "enabled-hypervisors"
38

    
39
#: QA configuration (L{_QaConfig})
40
_config = None
41

    
42

    
43
class _QaConfig(object):
44
  def __init__(self, data):
45
    """Initializes instances of this class.
46

47
    """
48
    self._data = data
49

    
50
    #: Cluster-wide run-time value of the exclusive storage flag
51
    self._exclusive_storage = None
52

    
53
  @classmethod
54
  def Load(cls, filename):
55
    """Loads a configuration file and produces a configuration object.
56

57
    @type filename: string
58
    @param filename: Path to configuration file
59
    @rtype: L{_QaConfig}
60

61
    """
62
    data = serializer.LoadJson(utils.ReadFile(filename))
63

    
64
    result = cls(data)
65
    result.Validate()
66

    
67
    return result
68

    
69
  def Validate(self):
70
    """Validates loaded configuration data.
71

72
    """
73
    if not self.get("nodes"):
74
      raise qa_error.Error("Need at least one node")
75

    
76
    if not self.get("instances"):
77
      raise qa_error.Error("Need at least one instance")
78

    
79
    if (self.get("disk") is None or
80
        self.get("disk-growth") is None or
81
        len(self.get("disk")) != len(self.get("disk-growth"))):
82
      raise qa_error.Error("Config options 'disk' and 'disk-growth' must exist"
83
                           " and have the same number of items")
84

    
85
    check = self.GetInstanceCheckScript()
86
    if check:
87
      try:
88
        os.stat(check)
89
      except EnvironmentError, err:
90
        raise qa_error.Error("Can't find instance check script '%s': %s" %
91
                             (check, err))
92

    
93
    enabled_hv = frozenset(self.GetEnabledHypervisors())
94
    if not enabled_hv:
95
      raise qa_error.Error("No hypervisor is enabled")
96

    
97
    difference = enabled_hv - constants.HYPER_TYPES
98
    if difference:
99
      raise qa_error.Error("Unknown hypervisor(s) enabled: %s" %
100
                           utils.CommaJoin(difference))
101

    
102
  def __getitem__(self, name):
103
    """Returns configuration value.
104

105
    @type name: string
106
    @param name: Name of configuration entry
107

108
    """
109
    return self._data[name]
110

    
111
  def get(self, name, default=None):
112
    """Returns configuration value.
113

114
    @type name: string
115
    @param name: Name of configuration entry
116
    @param default: Default value
117

118
    """
119
    return self._data.get(name, default)
120

    
121
  def GetMasterNode(self):
122
    """Returns the default master node for the cluster.
123

124
    """
125
    return self["nodes"][0]
126

    
127
  def GetInstanceCheckScript(self):
128
    """Returns path to instance check script or C{None}.
129

130
    """
131
    return self._data.get(_INSTANCE_CHECK_KEY, None)
132

    
133
  def GetEnabledHypervisors(self):
134
    """Returns list of enabled hypervisors.
135

136
    @rtype: list
137

138
    """
139
    try:
140
      value = self._data[_ENABLED_HV_KEY]
141
    except KeyError:
142
      return [constants.DEFAULT_ENABLED_HYPERVISOR]
143
    else:
144
      if value is None:
145
        return []
146
      elif isinstance(value, basestring):
147
        # The configuration key ("enabled-hypervisors") implies there can be
148
        # multiple values. Multiple hypervisors are comma-separated on the
149
        # command line option to "gnt-cluster init", so we need to handle them
150
        # equally here.
151
        return value.split(",")
152
      else:
153
        return value
154

    
155
  def GetDefaultHypervisor(self):
156
    """Returns the default hypervisor to be used.
157

158
    """
159
    return self.GetEnabledHypervisors()[0]
160

    
161
  def SetExclusiveStorage(self, value):
162
    """Set the expected value of the C{exclusive_storage} flag for the cluster.
163

164
    """
165
    self._exclusive_storage = bool(value)
166

    
167
  def GetExclusiveStorage(self):
168
    """Get the expected value of the C{exclusive_storage} flag for the cluster.
169

170
    """
171
    value = self._exclusive_storage
172
    assert value is not None
173
    return value
174

    
175
  def IsTemplateSupported(self, templ):
176
    """Is the given disk template supported by the current configuration?
177

178
    """
179
    return (not self.GetExclusiveStorage() or
180
            templ in constants.DTS_EXCL_STORAGE)
181

    
182

    
183
def Load(path):
184
  """Loads the passed configuration file.
185

186
  """
187
  global _config # pylint: disable=W0603
188

    
189
  _config = _QaConfig.Load(path)
190

    
191

    
192
def GetConfig():
193
  """Returns the configuration object.
194

195
  """
196
  if _config is None:
197
    raise RuntimeError("Configuration not yet loaded")
198

    
199
  return _config
200

    
201

    
202
def get(name, default=None):
203
  """Wrapper for L{_QaConfig.get}.
204

205
  """
206
  return GetConfig().get(name, default=default)
207

    
208

    
209
class Either:
210
  def __init__(self, tests):
211
    """Initializes this class.
212

213
    @type tests: list or string
214
    @param tests: List of test names
215
    @see: L{TestEnabled} for details
216

217
    """
218
    self.tests = tests
219

    
220

    
221
def _MakeSequence(value):
222
  """Make sequence of single argument.
223

224
  If the single argument is not already a list or tuple, a list with the
225
  argument as a single item is returned.
226

227
  """
228
  if isinstance(value, (list, tuple)):
229
    return value
230
  else:
231
    return [value]
232

    
233

    
234
def _TestEnabledInner(check_fn, names, fn):
235
  """Evaluate test conditions.
236

237
  @type check_fn: callable
238
  @param check_fn: Callback to check whether a test is enabled
239
  @type names: sequence or string
240
  @param names: Test name(s)
241
  @type fn: callable
242
  @param fn: Aggregation function
243
  @rtype: bool
244
  @return: Whether test is enabled
245

246
  """
247
  names = _MakeSequence(names)
248

    
249
  result = []
250

    
251
  for name in names:
252
    if isinstance(name, Either):
253
      value = _TestEnabledInner(check_fn, name.tests, compat.any)
254
    elif isinstance(name, (list, tuple)):
255
      value = _TestEnabledInner(check_fn, name, compat.all)
256
    else:
257
      value = check_fn(name)
258

    
259
    result.append(value)
260

    
261
  return fn(result)
262

    
263

    
264
def TestEnabled(tests, _cfg=None):
265
  """Returns True if the given tests are enabled.
266

267
  @param tests: A single test as a string, or a list of tests to check; can
268
    contain L{Either} for OR conditions, AND is default
269

270
  """
271
  if _cfg is None:
272
    cfg = GetConfig()
273
  else:
274
    cfg = _cfg
275

    
276
  # Get settings for all tests
277
  cfg_tests = cfg.get("tests", {})
278

    
279
  # Get default setting
280
  default = cfg_tests.get("default", True)
281

    
282
  return _TestEnabledInner(lambda name: cfg_tests.get(name, default),
283
                           tests, compat.all)
284

    
285

    
286
def GetInstanceCheckScript(*args):
287
  """Wrapper for L{_QaConfig.GetInstanceCheckScript}.
288

289
  """
290
  return GetConfig().GetInstanceCheckScript(*args)
291

    
292

    
293
def GetEnabledHypervisors(*args):
294
  """Wrapper for L{_QaConfig.GetEnabledHypervisors}.
295

296
  """
297
  return GetConfig().GetEnabledHypervisors(*args)
298

    
299

    
300
def GetDefaultHypervisor(*args):
301
  """Wrapper for L{_QaConfig.GetDefaultHypervisor}.
302

303
  """
304
  return GetConfig().GetDefaultHypervisor(*args)
305

    
306

    
307
def GetInstanceNicMac(inst, default=None):
308
  """Returns MAC address for instance's network interface.
309

310
  """
311
  return inst.get("nic.mac/0", default)
312

    
313

    
314
def GetMasterNode():
315
  """Wrapper for L{_QaConfig.GetMasterNode}.
316

317
  """
318
  return GetConfig().GetMasterNode()
319

    
320

    
321
def AcquireInstance():
322
  """Returns an instance which isn't in use.
323

324
  """
325
  # Filter out unwanted instances
326
  tmp_flt = lambda inst: not inst.get("_used", False)
327
  instances = filter(tmp_flt, GetConfig()["instances"])
328
  del tmp_flt
329

    
330
  if len(instances) == 0:
331
    raise qa_error.OutOfInstancesError("No instances left")
332

    
333
  inst = instances[0]
334
  inst["_used"] = True
335
  inst["_template"] = None
336
  return inst
337

    
338

    
339
def ReleaseInstance(inst):
340
  inst["_used"] = False
341

    
342

    
343
def GetInstanceTemplate(inst):
344
  """Return the disk template of an instance.
345

346
  """
347
  templ = inst["_template"]
348
  assert templ is not None
349
  return templ
350

    
351

    
352
def SetInstanceTemplate(inst, template):
353
  """Set the disk template for an instance.
354

355
  """
356
  inst["_template"] = template
357

    
358

    
359
def SetExclusiveStorage(value):
360
  """Wrapper for L{_QaConfig.SetExclusiveStorage}.
361

362
  """
363
  return GetConfig().SetExclusiveStorage(value)
364

    
365

    
366
def GetExclusiveStorage():
367
  """Wrapper for L{_QaConfig.GetExclusiveStorage}.
368

369
  """
370
  return GetConfig().GetExclusiveStorage()
371

    
372

    
373
def IsTemplateSupported(templ):
374
  """Wrapper for L{_QaConfig.GetExclusiveStorage}.
375

376
  """
377
  return GetConfig().IsTemplateSupported(templ)
378

    
379

    
380
def AcquireNode(exclude=None):
381
  """Returns the least used node.
382

383
  """
384
  master = GetMasterNode()
385
  cfg = GetConfig()
386

    
387
  # Filter out unwanted nodes
388
  # TODO: Maybe combine filters
389
  if exclude is None:
390
    nodes = cfg["nodes"][:]
391
  elif isinstance(exclude, (list, tuple)):
392
    nodes = filter(lambda node: node not in exclude, cfg["nodes"])
393
  else:
394
    nodes = filter(lambda node: node != exclude, cfg["nodes"])
395

    
396
  tmp_flt = lambda node: node.get("_added", False) or node == master
397
  nodes = filter(tmp_flt, nodes)
398
  del tmp_flt
399

    
400
  if len(nodes) == 0:
401
    raise qa_error.OutOfNodesError("No nodes left")
402

    
403
  # Get node with least number of uses
404
  def compare(a, b):
405
    result = cmp(a.get("_count", 0), b.get("_count", 0))
406
    if result == 0:
407
      result = cmp(a["primary"], b["primary"])
408
    return result
409

    
410
  nodes.sort(cmp=compare)
411

    
412
  node = nodes[0]
413
  node["_count"] = node.get("_count", 0) + 1
414
  return node
415

    
416

    
417
def AcquireManyNodes(num, exclude=None):
418
  """Return the least used nodes.
419

420
  @type num: int
421
  @param num: Number of nodes; can be 0.
422
  @type exclude: list of nodes or C{None}
423
  @param exclude: nodes to be excluded from the choice
424
  @rtype: list of nodes
425
  @return: C{num} different nodes
426

427
  """
428
  nodes = []
429
  if exclude is None:
430
    exclude = []
431
  elif isinstance(exclude, (list, tuple)):
432
    # Don't modify the incoming argument
433
    exclude = list(exclude)
434
  else:
435
    exclude = [exclude]
436

    
437
  try:
438
    for _ in range(0, num):
439
      n = AcquireNode(exclude=exclude)
440
      nodes.append(n)
441
      exclude.append(n)
442
  except qa_error.OutOfNodesError:
443
    ReleaseManyNodes(nodes)
444
    raise
445
  return nodes
446

    
447

    
448
def ReleaseNode(node):
449
  node["_count"] = node.get("_count", 0) - 1
450

    
451

    
452
def ReleaseManyNodes(nodes):
453
  for n in nodes:
454
    ReleaseNode(n)