Statistics
| Branch: | Tag: | Revision:

root / qa / ganeti-qa.py @ a4c589d2

History | View | Annotate | Download (29.5 kB)

1
#!/usr/bin/python -u
2
#
3

    
4
# Copyright (C) 2007, 2008, 2009, 2010, 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
"""Script for doing QA on Ganeti.
23

24
"""
25

    
26
# pylint: disable=C0103
27
# due to invalid name
28

    
29
import copy
30
import datetime
31
import optparse
32
import sys
33

    
34
import qa_cluster
35
import qa_config
36
import qa_daemon
37
import qa_env
38
import qa_error
39
import qa_group
40
import qa_instance
41
import qa_network
42
import qa_node
43
import qa_os
44
import qa_job
45
import qa_rapi
46
import qa_tags
47
import qa_utils
48

    
49
from ganeti import utils
50
from ganeti import rapi # pylint: disable=W0611
51
from ganeti import constants
52
from ganeti import pathutils
53

    
54
from ganeti.http.auth import ParsePasswordFile
55
import ganeti.rapi.client # pylint: disable=W0611
56
from ganeti.rapi.client import UsesRapiClient
57

    
58

    
59
def _FormatHeader(line, end=72):
60
  """Fill a line up to the end column.
61

62
  """
63
  line = "---- " + line + " "
64
  line += "-" * (end - len(line))
65
  line = line.rstrip()
66
  return line
67

    
68

    
69
def _DescriptionOf(fn):
70
  """Computes the description of an item.
71

72
  """
73
  if fn.__doc__:
74
    desc = fn.__doc__.splitlines()[0].strip()
75
  else:
76
    desc = "%r" % fn
77

    
78
  return desc.rstrip(".")
79

    
80

    
81
def RunTest(fn, *args, **kwargs):
82
  """Runs a test after printing a header.
83

84
  """
85

    
86
  tstart = datetime.datetime.now()
87

    
88
  desc = _DescriptionOf(fn)
89

    
90
  print
91
  print _FormatHeader("%s start %s" % (tstart, desc))
92

    
93
  try:
94
    retval = fn(*args, **kwargs)
95
    return retval
96
  finally:
97
    tstop = datetime.datetime.now()
98
    tdelta = tstop - tstart
99
    print _FormatHeader("%s time=%s %s" % (tstop, tdelta, desc))
100

    
101

    
102
def RunTestIf(testnames, fn, *args, **kwargs):
103
  """Runs a test conditionally.
104

105
  @param testnames: either a single test name in the configuration
106
      file, or a list of testnames (which will be AND-ed together)
107

108
  """
109
  if qa_config.TestEnabled(testnames):
110
    RunTest(fn, *args, **kwargs)
111
  else:
112
    tstart = datetime.datetime.now()
113
    desc = _DescriptionOf(fn)
114
    # TODO: Formatting test names when non-string names are involved
115
    print _FormatHeader("%s skipping %s, test(s) %s disabled" %
116
                        (tstart, desc, testnames))
117

    
118

    
119
def RunEnvTests():
120
  """Run several environment tests.
121

122
  """
123
  RunTestIf("env", qa_env.TestSshConnection)
124
  RunTestIf("env", qa_env.TestIcmpPing)
125
  RunTestIf("env", qa_env.TestGanetiCommands)
126

    
127

    
128
def _LookupRapiSecret(rapi_user):
129
  """Find the RAPI secret for the given user.
130

131
  @param rapi_user: Login user
132
  @return: Login secret for the user
133

134
  """
135
  CTEXT = "{CLEARTEXT}"
136
  master = qa_config.GetMasterNode()
137
  cmd = ["cat", qa_utils.MakeNodePath(master, pathutils.RAPI_USERS_FILE)]
138
  file_content = qa_utils.GetCommandOutput(master.primary,
139
                                           utils.ShellQuoteArgs(cmd))
140
  users = ParsePasswordFile(file_content)
141
  entry = users.get(rapi_user)
142
  if not entry:
143
    raise qa_error.Error("User %s not found in RAPI users file" % rapi_user)
144
  secret = entry.password
145
  if secret.upper().startswith(CTEXT):
146
    secret = secret[len(CTEXT):]
147
  elif secret.startswith("{"):
148
    raise qa_error.Error("Unsupported password schema for RAPI user %s:"
149
                         " not a clear text password" % rapi_user)
150
  return secret
151

    
152

    
153
def SetupCluster(rapi_user):
154
  """Initializes the cluster.
155

156
  @param rapi_user: Login user for RAPI
157
  @return: Login secret for RAPI
158

159
  """
160
  rapi_secret = utils.GenerateSecret()
161
  RunTestIf("create-cluster", qa_cluster.TestClusterInit,
162
            rapi_user, rapi_secret)
163
  if not qa_config.TestEnabled("create-cluster"):
164
    # If the cluster is already in place, we assume that exclusive-storage is
165
    # already set according to the configuration
166
    qa_config.SetExclusiveStorage(qa_config.get("exclusive-storage", False))
167
    if qa_rapi.Enabled():
168
      # To support RAPI on an existing cluster we have to find out the secret
169
      rapi_secret = _LookupRapiSecret(rapi_user)
170

    
171
  # Test on empty cluster
172
  RunTestIf("node-list", qa_node.TestNodeList)
173
  RunTestIf("instance-list", qa_instance.TestInstanceList)
174
  RunTestIf("job-list", qa_job.TestJobList)
175

    
176
  RunTestIf("create-cluster", qa_node.TestNodeAddAll)
177
  if not qa_config.TestEnabled("create-cluster"):
178
    # consider the nodes are already there
179
    qa_node.MarkNodeAddedAll()
180

    
181
  RunTestIf("test-jobqueue", qa_cluster.TestJobqueue)
182

    
183
  # enable the watcher (unconditionally)
184
  RunTest(qa_daemon.TestResumeWatcher)
185

    
186
  RunTestIf("node-list", qa_node.TestNodeList)
187

    
188
  # Test listing fields
189
  RunTestIf("node-list", qa_node.TestNodeListFields)
190
  RunTestIf("instance-list", qa_instance.TestInstanceListFields)
191
  RunTestIf("job-list", qa_job.TestJobListFields)
192
  RunTestIf("instance-export", qa_instance.TestBackupListFields)
193

    
194
  RunTestIf("node-info", qa_node.TestNodeInfo)
195

    
196
  return rapi_secret
197

    
198

    
199
def RunClusterTests():
200
  """Runs tests related to gnt-cluster.
201

202
  """
203
  for test, fn in [
204
    ("create-cluster", qa_cluster.TestClusterInitDisk),
205
    ("cluster-renew-crypto", qa_cluster.TestClusterRenewCrypto),
206
    ("cluster-verify", qa_cluster.TestClusterVerify),
207
    ("cluster-reserved-lvs", qa_cluster.TestClusterReservedLvs),
208
    # TODO: add more cluster modify tests
209
    ("cluster-modify", qa_cluster.TestClusterModifyEmpty),
210
    ("cluster-modify", qa_cluster.TestClusterModifyIPolicy),
211
    ("cluster-modify", qa_cluster.TestClusterModifyISpecs),
212
    ("cluster-modify", qa_cluster.TestClusterModifyBe),
213
    ("cluster-modify", qa_cluster.TestClusterModifyDisk),
214
    ("cluster-modify", qa_cluster.TestClusterModifyDiskTemplates),
215
    ("cluster-rename", qa_cluster.TestClusterRename),
216
    ("cluster-info", qa_cluster.TestClusterVersion),
217
    ("cluster-info", qa_cluster.TestClusterInfo),
218
    ("cluster-info", qa_cluster.TestClusterGetmaster),
219
    ("cluster-redist-conf", qa_cluster.TestClusterRedistConf),
220
    (["cluster-copyfile", qa_config.NoVirtualCluster],
221
     qa_cluster.TestClusterCopyfile),
222
    ("cluster-command", qa_cluster.TestClusterCommand),
223
    ("cluster-burnin", qa_cluster.TestClusterBurnin),
224
    ("cluster-master-failover", qa_cluster.TestClusterMasterFailover),
225
    ("cluster-master-failover",
226
     qa_cluster.TestClusterMasterFailoverWithDrainedQueue),
227
    (["cluster-oob", qa_config.NoVirtualCluster],
228
     qa_cluster.TestClusterOob),
229
    (qa_rapi.Enabled, qa_rapi.TestVersion),
230
    (qa_rapi.Enabled, qa_rapi.TestEmptyCluster),
231
    (qa_rapi.Enabled, qa_rapi.TestRapiQuery),
232
    ]:
233
    RunTestIf(test, fn)
234

    
235

    
236
def RunRepairDiskSizes():
237
  """Run the repair disk-sizes test.
238

239
  """
240
  RunTestIf("cluster-repair-disk-sizes", qa_cluster.TestClusterRepairDiskSizes)
241

    
242

    
243
def RunOsTests():
244
  """Runs all tests related to gnt-os.
245

246
  """
247
  os_enabled = ["os", qa_config.NoVirtualCluster]
248

    
249
  if qa_config.TestEnabled(qa_rapi.Enabled):
250
    rapi_getos = qa_rapi.GetOperatingSystems
251
  else:
252
    rapi_getos = None
253

    
254
  for fn in [
255
    qa_os.TestOsList,
256
    qa_os.TestOsDiagnose,
257
    ]:
258
    RunTestIf(os_enabled, fn)
259

    
260
  for fn in [
261
    qa_os.TestOsValid,
262
    qa_os.TestOsInvalid,
263
    qa_os.TestOsPartiallyValid,
264
    ]:
265
    RunTestIf(os_enabled, fn, rapi_getos)
266

    
267
  for fn in [
268
    qa_os.TestOsModifyValid,
269
    qa_os.TestOsModifyInvalid,
270
    qa_os.TestOsStatesNonExisting,
271
    ]:
272
    RunTestIf(os_enabled, fn)
273

    
274

    
275
def RunCommonInstanceTests(instance):
276
  """Runs a few tests that are common to all disk types.
277

278
  """
279
  RunTestIf("instance-shutdown", qa_instance.TestInstanceShutdown, instance)
280
  RunTestIf(["instance-shutdown", "instance-console", qa_rapi.Enabled],
281
            qa_rapi.TestRapiStoppedInstanceConsole, instance)
282
  RunTestIf(["instance-shutdown", "instance-modify"],
283
            qa_instance.TestInstanceStoppedModify, instance)
284
  RunTestIf("instance-shutdown", qa_instance.TestInstanceStartup, instance)
285

    
286
  # Test shutdown/start via RAPI
287
  RunTestIf(["instance-shutdown", qa_rapi.Enabled],
288
            qa_rapi.TestRapiInstanceShutdown, instance)
289
  RunTestIf(["instance-shutdown", qa_rapi.Enabled],
290
            qa_rapi.TestRapiInstanceStartup, instance)
291

    
292
  RunTestIf("instance-list", qa_instance.TestInstanceList)
293

    
294
  RunTestIf("instance-info", qa_instance.TestInstanceInfo, instance)
295

    
296
  RunTestIf("instance-modify", qa_instance.TestInstanceModify, instance)
297
  RunTestIf(["instance-modify", qa_rapi.Enabled],
298
            qa_rapi.TestRapiInstanceModify, instance)
299

    
300
  RunTestIf("instance-console", qa_instance.TestInstanceConsole, instance)
301
  RunTestIf(["instance-console", qa_rapi.Enabled],
302
            qa_rapi.TestRapiInstanceConsole, instance)
303

    
304
  RunTestIf("instance-device-names", qa_instance.TestInstanceDeviceNames,
305
            instance)
306
  DOWN_TESTS = qa_config.Either([
307
    "instance-reinstall",
308
    "instance-rename",
309
    "instance-grow-disk",
310
    ])
311

    
312
  # shutdown instance for any 'down' tests
313
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceShutdown, instance)
314

    
315
  # now run the 'down' state tests
316
  RunTestIf("instance-reinstall", qa_instance.TestInstanceReinstall, instance)
317
  RunTestIf(["instance-reinstall", qa_rapi.Enabled],
318
            qa_rapi.TestRapiInstanceReinstall, instance)
319

    
320
  if qa_config.TestEnabled("instance-rename"):
321
    tgt_instance = qa_config.AcquireInstance()
322
    try:
323
      rename_source = instance.name
324
      rename_target = tgt_instance.name
325
      # perform instance rename to the same name
326
      RunTest(qa_instance.TestInstanceRenameAndBack,
327
              rename_source, rename_source)
328
      RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
329
                rename_source, rename_source)
330
      if rename_target is not None:
331
        # perform instance rename to a different name, if we have one configured
332
        RunTest(qa_instance.TestInstanceRenameAndBack,
333
                rename_source, rename_target)
334
        RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
335
                  rename_source, rename_target)
336
    finally:
337
      tgt_instance.Release()
338

    
339
  RunTestIf(["instance-grow-disk"], qa_instance.TestInstanceGrowDisk, instance)
340

    
341
  # and now start the instance again
342
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceStartup, instance)
343

    
344
  RunTestIf("instance-reboot", qa_instance.TestInstanceReboot, instance)
345

    
346
  RunTestIf("tags", qa_tags.TestInstanceTags, instance)
347

    
348
  RunTestIf("cluster-verify", qa_cluster.TestClusterVerify)
349

    
350
  RunTestIf(qa_rapi.Enabled, qa_rapi.TestInstance, instance)
351

    
352
  # Lists instances, too
353
  RunTestIf("node-list", qa_node.TestNodeList)
354

    
355
  # Some jobs have been run, let's test listing them
356
  RunTestIf("job-list", qa_job.TestJobList)
357

    
358

    
359
def RunCommonNodeTests():
360
  """Run a few common node tests.
361

362
  """
363
  RunTestIf("node-volumes", qa_node.TestNodeVolumes)
364
  RunTestIf("node-storage", qa_node.TestNodeStorage)
365
  RunTestIf(["node-oob", qa_config.NoVirtualCluster], qa_node.TestOutOfBand)
366

    
367

    
368
def RunGroupListTests():
369
  """Run tests for listing node groups.
370

371
  """
372
  RunTestIf("group-list", qa_group.TestGroupList)
373
  RunTestIf("group-list", qa_group.TestGroupListFields)
374

    
375

    
376
def RunNetworkTests():
377
  """Run tests for network management.
378

379
  """
380
  RunTestIf("network", qa_network.TestNetworkAddRemove)
381
  RunTestIf("network", qa_network.TestNetworkConnect)
382
  RunTestIf(["network", "tags"], qa_network.TestNetworkTags)
383

    
384

    
385
def RunGroupRwTests():
386
  """Run tests for adding/removing/renaming groups.
387

388
  """
389
  RunTestIf("group-rwops", qa_group.TestGroupAddRemoveRename)
390
  RunTestIf("group-rwops", qa_group.TestGroupAddWithOptions)
391
  RunTestIf("group-rwops", qa_group.TestGroupModify)
392
  RunTestIf(["group-rwops", qa_rapi.Enabled], qa_rapi.TestRapiNodeGroups)
393
  RunTestIf(["group-rwops", "tags"], qa_tags.TestGroupTags,
394
            qa_group.GetDefaultGroup())
395

    
396

    
397
def RunExportImportTests(instance, inodes):
398
  """Tries to export and import the instance.
399

400
  @type inodes: list of nodes
401
  @param inodes: current nodes of the instance
402

403
  """
404
  # FIXME: export explicitly bails out on file based storage. other non-lvm
405
  # based storage types are untested, though. Also note that import could still
406
  # work, but is deeply embedded into the "export" case.
407
  if (qa_config.TestEnabled("instance-export") and
408
      instance.disk_template != constants.DT_FILE):
409
    RunTest(qa_instance.TestInstanceExportNoTarget, instance)
410

    
411
    pnode = inodes[0]
412
    expnode = qa_config.AcquireNode(exclude=pnode)
413
    try:
414
      name = RunTest(qa_instance.TestInstanceExport, instance, expnode)
415

    
416
      RunTest(qa_instance.TestBackupList, expnode)
417

    
418
      if qa_config.TestEnabled("instance-import"):
419
        newinst = qa_config.AcquireInstance()
420
        try:
421
          RunTest(qa_instance.TestInstanceImport, newinst, pnode,
422
                  expnode, name)
423
          # Check if starting the instance works
424
          RunTest(qa_instance.TestInstanceStartup, newinst)
425
          RunTest(qa_instance.TestInstanceRemove, newinst)
426
        finally:
427
          newinst.Release()
428
    finally:
429
      expnode.Release()
430

    
431
  # FIXME: inter-cluster-instance-move crashes on file based instances :/
432
  # See Issue 414.
433
  if (qa_config.TestEnabled([qa_rapi.Enabled, "inter-cluster-instance-move"])
434
      and instance.disk_template != constants.DT_FILE):
435
    newinst = qa_config.AcquireInstance()
436
    try:
437
      tnode = qa_config.AcquireNode(exclude=inodes)
438
      try:
439
        RunTest(qa_rapi.TestInterClusterInstanceMove, instance, newinst,
440
                inodes, tnode)
441
      finally:
442
        tnode.Release()
443
    finally:
444
      newinst.Release()
445

    
446

    
447
def RunDaemonTests(instance):
448
  """Test the ganeti-watcher script.
449

450
  """
451
  RunTest(qa_daemon.TestPauseWatcher)
452

    
453
  RunTestIf("instance-automatic-restart",
454
            qa_daemon.TestInstanceAutomaticRestart, instance)
455
  RunTestIf("instance-consecutive-failures",
456
            qa_daemon.TestInstanceConsecutiveFailures, instance)
457

    
458
  RunTest(qa_daemon.TestResumeWatcher)
459

    
460

    
461
def RunHardwareFailureTests(instance, inodes):
462
  """Test cluster internal hardware failure recovery.
463

464
  """
465
  RunTestIf("instance-failover", qa_instance.TestInstanceFailover, instance)
466
  RunTestIf(["instance-failover", qa_rapi.Enabled],
467
            qa_rapi.TestRapiInstanceFailover, instance)
468

    
469
  RunTestIf("instance-migrate", qa_instance.TestInstanceMigrate, instance)
470
  RunTestIf(["instance-migrate", qa_rapi.Enabled],
471
            qa_rapi.TestRapiInstanceMigrate, instance)
472

    
473
  if qa_config.TestEnabled("instance-replace-disks"):
474
    # We just need alternative secondary nodes, hence "- 1"
475
    othernodes = qa_config.AcquireManyNodes(len(inodes) - 1, exclude=inodes)
476
    try:
477
      RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceReplaceDisks, instance)
478
      RunTest(qa_instance.TestReplaceDisks,
479
              instance, inodes, othernodes)
480
    finally:
481
      qa_config.ReleaseManyNodes(othernodes)
482
    del othernodes
483

    
484
  if qa_config.TestEnabled("instance-recreate-disks"):
485
    try:
486
      acquirednodes = qa_config.AcquireManyNodes(len(inodes), exclude=inodes)
487
      othernodes = acquirednodes
488
    except qa_error.OutOfNodesError:
489
      if len(inodes) > 1:
490
        # If the cluster is not big enough, let's reuse some of the nodes, but
491
        # with different roles. In this way, we can test a DRBD instance even on
492
        # a 3-node cluster.
493
        acquirednodes = [qa_config.AcquireNode(exclude=inodes)]
494
        othernodes = acquirednodes + inodes[:-1]
495
      else:
496
        raise
497
    try:
498
      RunTest(qa_instance.TestRecreateDisks,
499
              instance, inodes, othernodes)
500
    finally:
501
      qa_config.ReleaseManyNodes(acquirednodes)
502

    
503
  if len(inodes) >= 2:
504
    RunTestIf("node-evacuate", qa_node.TestNodeEvacuate, inodes[0], inodes[1])
505
    RunTestIf("node-failover", qa_node.TestNodeFailover, inodes[0], inodes[1])
506

    
507

    
508
def RunExclusiveStorageTests():
509
  """Test exclusive storage."""
510
  if not qa_config.TestEnabled("cluster-exclusive-storage"):
511
    return
512

    
513
  node = qa_config.AcquireNode()
514
  try:
515
    old_es = qa_cluster.TestSetExclStorCluster(False)
516
    qa_node.TestExclStorSingleNode(node)
517

    
518
    qa_cluster.TestSetExclStorCluster(True)
519
    qa_cluster.TestExclStorSharedPv(node)
520

    
521
    if qa_config.TestEnabled("instance-add-plain-disk"):
522
      # Make sure that the cluster doesn't have any pre-existing problem
523
      qa_cluster.AssertClusterVerify()
524

    
525
      # Create and allocate instances
526
      instance1 = qa_instance.TestInstanceAddWithPlainDisk([node])
527
      try:
528
        instance2 = qa_instance.TestInstanceAddWithPlainDisk([node])
529
        try:
530
          # cluster-verify checks that disks are allocated correctly
531
          qa_cluster.AssertClusterVerify()
532

    
533
          # Remove instances
534
          qa_instance.TestInstanceRemove(instance2)
535
          qa_instance.TestInstanceRemove(instance1)
536
        finally:
537
          instance2.Release()
538
      finally:
539
        instance1.Release()
540

    
541
    if qa_config.TestEnabled("instance-add-drbd-disk"):
542
      snode = qa_config.AcquireNode()
543
      try:
544
        qa_cluster.TestSetExclStorCluster(False)
545
        instance = qa_instance.TestInstanceAddWithDrbdDisk([node, snode])
546
        try:
547
          qa_cluster.TestSetExclStorCluster(True)
548
          exp_err = [constants.CV_EINSTANCEUNSUITABLENODE]
549
          qa_cluster.AssertClusterVerify(fail=True, errors=exp_err)
550
          qa_instance.TestInstanceRemove(instance)
551
        finally:
552
          instance.Release()
553
      finally:
554
        snode.Release()
555
    qa_cluster.TestSetExclStorCluster(old_es)
556
  finally:
557
    node.Release()
558

    
559

    
560
def _BuildSpecDict(par, mn, st, mx):
561
  return {
562
    constants.ISPECS_MINMAX: [{
563
      constants.ISPECS_MIN: {par: mn},
564
      constants.ISPECS_MAX: {par: mx},
565
      }],
566
    constants.ISPECS_STD: {par: st},
567
    }
568

    
569

    
570
def _BuildDoubleSpecDict(index, par, mn, st, mx):
571
  new_spec = {
572
    constants.ISPECS_MINMAX: [{}, {}],
573
    }
574
  if st is not None:
575
    new_spec[constants.ISPECS_STD] = {par: st}
576
  new_spec[constants.ISPECS_MINMAX][index] = {
577
    constants.ISPECS_MIN: {par: mn},
578
    constants.ISPECS_MAX: {par: mx},
579
    }
580
  return new_spec
581

    
582

    
583
def TestIPolicyPlainInstance():
584
  """Test instance policy interaction with instances"""
585
  params = ["memory-size", "cpu-count", "disk-count", "disk-size", "nic-count"]
586
  if not qa_config.IsTemplateSupported(constants.DT_PLAIN):
587
    print "Template %s not supported" % constants.DT_PLAIN
588
    return
589

    
590
  # This test assumes that the group policy is empty
591
  (_, old_specs) = qa_cluster.TestClusterSetISpecs()
592
  # We also assume to have only one min/max bound
593
  assert len(old_specs[constants.ISPECS_MINMAX]) == 1
594
  node = qa_config.AcquireNode()
595
  try:
596
    # Log of policy changes, list of tuples:
597
    # (full_change, incremental_change, policy_violated)
598
    history = []
599
    instance = qa_instance.TestInstanceAddWithPlainDisk([node])
600
    try:
601
      policyerror = [constants.CV_EINSTANCEPOLICY]
602
      for par in params:
603
        (iminval, imaxval) = qa_instance.GetInstanceSpec(instance.name, par)
604
        # Some specs must be multiple of 4
605
        new_spec = _BuildSpecDict(par, imaxval + 4, imaxval + 4, imaxval + 4)
606
        history.append((None, new_spec, True))
607
        if iminval > 0:
608
          # Some specs must be multiple of 4
609
          if iminval >= 4:
610
            upper = iminval - 4
611
          else:
612
            upper = iminval - 1
613
          new_spec = _BuildSpecDict(par, 0, upper, upper)
614
          history.append((None, new_spec, True))
615
        history.append((old_specs, None, False))
616

    
617
      # Test with two instance specs
618
      double_specs = copy.deepcopy(old_specs)
619
      double_specs[constants.ISPECS_MINMAX] = \
620
          double_specs[constants.ISPECS_MINMAX] * 2
621
      (par1, par2) = params[0:2]
622
      (_, imaxval1) = qa_instance.GetInstanceSpec(instance.name, par1)
623
      (_, imaxval2) = qa_instance.GetInstanceSpec(instance.name, par2)
624
      old_minmax = old_specs[constants.ISPECS_MINMAX][0]
625
      history.extend([
626
        (double_specs, None, False),
627
        # The first min/max limit is being violated
628
        (None,
629
         _BuildDoubleSpecDict(0, par1, imaxval1 + 4, imaxval1 + 4,
630
                              imaxval1 + 4),
631
         False),
632
        # Both min/max limits are being violated
633
        (None,
634
         _BuildDoubleSpecDict(1, par2, imaxval2 + 4, None, imaxval2 + 4),
635
         True),
636
        # The second min/max limit is being violated
637
        (None,
638
         _BuildDoubleSpecDict(0, par1,
639
                              old_minmax[constants.ISPECS_MIN][par1],
640
                              old_specs[constants.ISPECS_STD][par1],
641
                              old_minmax[constants.ISPECS_MAX][par1]),
642
         False),
643
        (old_specs, None, False),
644
        ])
645

    
646
      # Apply the changes, and check policy violations after each change
647
      qa_cluster.AssertClusterVerify()
648
      for (new_specs, diff_specs, failed) in history:
649
        qa_cluster.TestClusterSetISpecs(new_specs=new_specs,
650
                                        diff_specs=diff_specs)
651
        if failed:
652
          qa_cluster.AssertClusterVerify(warnings=policyerror)
653
        else:
654
          qa_cluster.AssertClusterVerify()
655

    
656
      qa_instance.TestInstanceRemove(instance)
657
    finally:
658
      instance.Release()
659

    
660
    # Now we replay the same policy changes, and we expect that the instance
661
    # cannot be created for the cases where we had a policy violation above
662
    for (new_specs, diff_specs, failed) in history:
663
      qa_cluster.TestClusterSetISpecs(new_specs=new_specs,
664
                                      diff_specs=diff_specs)
665
      if failed:
666
        qa_instance.TestInstanceAddWithPlainDisk([node], fail=True)
667
      # Instance creation with no policy violation has been tested already
668
  finally:
669
    node.Release()
670

    
671

    
672
def IsExclusiveStorageInstanceTestEnabled():
673
  test_name = "exclusive-storage-instance-tests"
674
  if qa_config.TestEnabled(test_name):
675
    vgname = qa_config.get("vg-name", constants.DEFAULT_VG)
676
    vgscmd = utils.ShellQuoteArgs([
677
      "vgs", "--noheadings", "-o", "pv_count", vgname,
678
      ])
679
    nodes = qa_config.GetConfig()["nodes"]
680
    for node in nodes:
681
      try:
682
        pvnum = int(qa_utils.GetCommandOutput(node.primary, vgscmd))
683
      except Exception, e:
684
        msg = ("Cannot get the number of PVs on %s, needed by '%s': %s" %
685
               (node.primary, test_name, e))
686
        raise qa_error.Error(msg)
687
      if pvnum < 2:
688
        raise qa_error.Error("Node %s has not enough PVs (%s) to run '%s'" %
689
                             (node.primary, pvnum, test_name))
690
    res = True
691
  else:
692
    res = False
693
  return res
694

    
695

    
696
def RunInstanceTests():
697
  """Create and exercise instances."""
698
  instance_tests = [
699
    ("instance-add-plain-disk", constants.DT_PLAIN,
700
     qa_instance.TestInstanceAddWithPlainDisk, 1),
701
    ("instance-add-drbd-disk", constants.DT_DRBD8,
702
     qa_instance.TestInstanceAddWithDrbdDisk, 2),
703
    ("instance-add-diskless", constants.DT_DISKLESS,
704
     qa_instance.TestInstanceAddDiskless, 1),
705
    ("instance-add-file", constants.DT_FILE,
706
     qa_instance.TestInstanceAddFile, 1)
707
    ]
708

    
709
  for (test_name, templ, create_fun, num_nodes) in instance_tests:
710
    if (qa_config.TestEnabled(test_name) and
711
        qa_config.IsTemplateSupported(templ)):
712
      inodes = qa_config.AcquireManyNodes(num_nodes)
713
      try:
714
        instance = RunTest(create_fun, inodes)
715
        try:
716
          RunTestIf("cluster-epo", qa_cluster.TestClusterEpo)
717
          RunDaemonTests(instance)
718
          for node in inodes:
719
            RunTestIf("haskell-confd", qa_node.TestNodeListDrbd, node)
720
          if len(inodes) > 1:
721
            RunTestIf("group-rwops", qa_group.TestAssignNodesIncludingSplit,
722
                      constants.INITIAL_NODE_GROUP_NAME,
723
                      inodes[0].primary, inodes[1].primary)
724
          if qa_config.TestEnabled("instance-convert-disk"):
725
            RunTest(qa_instance.TestInstanceShutdown, instance)
726
            RunTest(qa_instance.TestInstanceConvertDiskToPlain,
727
                    instance, inodes)
728
            RunTest(qa_instance.TestInstanceStartup, instance)
729
          RunTestIf("instance-modify-disks",
730
                    qa_instance.TestInstanceModifyDisks, instance)
731
          RunCommonInstanceTests(instance)
732
          if qa_config.TestEnabled("instance-modify-primary"):
733
            othernode = qa_config.AcquireNode()
734
            RunTest(qa_instance.TestInstanceModifyPrimaryAndBack,
735
                    instance, inodes[0], othernode)
736
            othernode.Release()
737
          RunGroupListTests()
738
          RunExportImportTests(instance, inodes)
739
          RunHardwareFailureTests(instance, inodes)
740
          RunRepairDiskSizes()
741
          RunTest(qa_instance.TestInstanceRemove, instance)
742
        finally:
743
          instance.Release()
744
        del instance
745
      finally:
746
        qa_config.ReleaseManyNodes(inodes)
747
      qa_cluster.AssertClusterVerify()
748

    
749

    
750
def RunQa():
751
  """Main QA body.
752

753
  """
754
  rapi_user = "ganeti-qa"
755

    
756
  RunEnvTests()
757
  rapi_secret = SetupCluster(rapi_user)
758

    
759
  if qa_rapi.Enabled():
760
    # Load RAPI certificate
761
    qa_rapi.Setup(rapi_user, rapi_secret)
762

    
763
  RunClusterTests()
764
  RunOsTests()
765

    
766
  RunTestIf("tags", qa_tags.TestClusterTags)
767

    
768
  RunCommonNodeTests()
769
  RunGroupListTests()
770
  RunGroupRwTests()
771
  RunNetworkTests()
772

    
773
  # The master shouldn't be readded or put offline; "delay" needs a non-master
774
  # node to test
775
  pnode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
776
  try:
777
    RunTestIf("node-readd", qa_node.TestNodeReadd, pnode)
778
    RunTestIf("node-modify", qa_node.TestNodeModify, pnode)
779
    RunTestIf("delay", qa_cluster.TestDelay, pnode)
780
  finally:
781
    pnode.Release()
782

    
783
  # Make sure the cluster is clean before running instance tests
784
  qa_cluster.AssertClusterVerify()
785

    
786
  pnode = qa_config.AcquireNode()
787
  try:
788
    RunTestIf("tags", qa_tags.TestNodeTags, pnode)
789

    
790
    if qa_rapi.Enabled():
791
      RunTest(qa_rapi.TestNode, pnode)
792

    
793
      if qa_config.TestEnabled("instance-add-plain-disk"):
794
        for use_client in [True, False]:
795
          rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
796
                                  use_client)
797
          try:
798
            if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
799
              RunCommonInstanceTests(rapi_instance)
800
            RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
801
          finally:
802
            rapi_instance.Release()
803
          del rapi_instance
804

    
805
  finally:
806
    pnode.Release()
807

    
808
  config_list = [
809
    ("default-instance-tests", lambda: None, lambda _: None),
810
    (IsExclusiveStorageInstanceTestEnabled,
811
     lambda: qa_cluster.TestSetExclStorCluster(True),
812
     qa_cluster.TestSetExclStorCluster),
813
  ]
814
  for (conf_name, setup_conf_f, restore_conf_f) in config_list:
815
    if qa_config.TestEnabled(conf_name):
816
      oldconf = setup_conf_f()
817
      RunInstanceTests()
818
      restore_conf_f(oldconf)
819

    
820
  pnode = qa_config.AcquireNode()
821
  try:
822
    if qa_config.TestEnabled(["instance-add-plain-disk", "instance-export"]):
823
      for shutdown in [False, True]:
824
        instance = RunTest(qa_instance.TestInstanceAddWithPlainDisk, [pnode])
825
        try:
826
          expnode = qa_config.AcquireNode(exclude=pnode)
827
          try:
828
            if shutdown:
829
              # Stop instance before exporting and removing it
830
              RunTest(qa_instance.TestInstanceShutdown, instance)
831
            RunTest(qa_instance.TestInstanceExportWithRemove, instance, expnode)
832
            RunTest(qa_instance.TestBackupList, expnode)
833
          finally:
834
            expnode.Release()
835
        finally:
836
          instance.Release()
837
        del expnode
838
        del instance
839
      qa_cluster.AssertClusterVerify()
840

    
841
  finally:
842
    pnode.Release()
843

    
844
  RunExclusiveStorageTests()
845
  RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
846
            TestIPolicyPlainInstance)
847

    
848
  RunTestIf(
849
    "instance-add-restricted-by-disktemplates",
850
    qa_instance.TestInstanceCreationRestrictedByDiskTemplates)
851

    
852
  # Test removing instance with offline drbd secondary
853
  if qa_config.TestEnabled(["instance-remove-drbd-offline",
854
                            "instance-add-drbd-disk"]):
855
    # Make sure the master is not put offline
856
    snode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
857
    try:
858
      pnode = qa_config.AcquireNode(exclude=snode)
859
      try:
860
        instance = qa_instance.TestInstanceAddWithDrbdDisk([pnode, snode])
861
        set_offline = lambda node: qa_node.MakeNodeOffline(node, "yes")
862
        set_online = lambda node: qa_node.MakeNodeOffline(node, "no")
863
        RunTest(qa_instance.TestRemoveInstanceOfflineNode, instance, snode,
864
                set_offline, set_online)
865
      finally:
866
        pnode.Release()
867
    finally:
868
      snode.Release()
869
    qa_cluster.AssertClusterVerify()
870

    
871
  RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)
872

    
873
  RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)
874

    
875

    
876
@UsesRapiClient
877
def main():
878
  """Main program.
879

880
  """
881
  parser = optparse.OptionParser(usage="%prog [options] <config-file>")
882
  parser.add_option("--yes-do-it", dest="yes_do_it",
883
                    action="store_true",
884
                    help="Really execute the tests")
885
  (opts, args) = parser.parse_args()
886

    
887
  if len(args) == 1:
888
    (config_file, ) = args
889
  else:
890
    parser.error("Wrong number of arguments.")
891

    
892
  if not opts.yes_do_it:
893
    print ("Executing this script irreversibly destroys any Ganeti\n"
894
           "configuration on all nodes involved. If you really want\n"
895
           "to start testing, supply the --yes-do-it option.")
896
    sys.exit(1)
897

    
898
  qa_config.Load(config_file)
899

    
900
  primary = qa_config.GetMasterNode().primary
901
  qa_utils.StartMultiplexer(primary)
902
  print ("SSH command for primary node: %s" %
903
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
904
  print ("SSH command for other nodes: %s" %
905
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
906
  try:
907
    RunQa()
908
  finally:
909
    qa_utils.CloseMultiplexers()
910

    
911
if __name__ == "__main__":
912
  main()