Statistics
| Branch: | Tag: | Revision:

root / qa / ganeti-qa.py @ b24b52d9

History | View | Annotate | Download (30.1 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_monitoring
42
import qa_network
43
import qa_node
44
import qa_os
45
import qa_job
46
import qa_rapi
47
import qa_tags
48
import qa_utils
49

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

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

    
59

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

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

    
69

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

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

    
79
  return desc.rstrip(".")
80

    
81

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

85
  """
86

    
87
  tstart = datetime.datetime.now()
88

    
89
  desc = _DescriptionOf(fn)
90

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

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

    
102

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

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

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

    
119

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

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

    
128

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

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

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

    
153

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

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

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

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

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

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

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

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

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

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

    
197
  return rapi_secret
198

    
199

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

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

    
238

    
239
def RunRepairDiskSizes():
240
  """Run the repair disk-sizes test.
241

242
  """
243
  RunTestIf("cluster-repair-disk-sizes", qa_cluster.TestClusterRepairDiskSizes)
244

    
245

    
246
def RunOsTests():
247
  """Runs all tests related to gnt-os.
248

249
  """
250
  os_enabled = ["os", qa_config.NoVirtualCluster]
251

    
252
  if qa_config.TestEnabled(qa_rapi.Enabled):
253
    rapi_getos = qa_rapi.GetOperatingSystems
254
  else:
255
    rapi_getos = None
256

    
257
  for fn in [
258
    qa_os.TestOsList,
259
    qa_os.TestOsDiagnose,
260
    ]:
261
    RunTestIf(os_enabled, fn)
262

    
263
  for fn in [
264
    qa_os.TestOsValid,
265
    qa_os.TestOsInvalid,
266
    qa_os.TestOsPartiallyValid,
267
    ]:
268
    RunTestIf(os_enabled, fn, rapi_getos)
269

    
270
  for fn in [
271
    qa_os.TestOsModifyValid,
272
    qa_os.TestOsModifyInvalid,
273
    qa_os.TestOsStatesNonExisting,
274
    ]:
275
    RunTestIf(os_enabled, fn)
276

    
277

    
278
def RunCommonInstanceTests(instance, inst_nodes):
279
  """Runs a few tests that are common to all disk types.
280

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

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

    
295
  RunTestIf("instance-list", qa_instance.TestInstanceList)
296

    
297
  RunTestIf("instance-info", qa_instance.TestInstanceInfo, instance)
298

    
299
  RunTestIf("instance-modify", qa_instance.TestInstanceModify, instance)
300
  RunTestIf(["instance-modify", qa_rapi.Enabled],
301
            qa_rapi.TestRapiInstanceModify, instance)
302

    
303
  RunTestIf("instance-console", qa_instance.TestInstanceConsole, instance)
304
  RunTestIf(["instance-console", qa_rapi.Enabled],
305
            qa_rapi.TestRapiInstanceConsole, instance)
306

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

    
315
  # shutdown instance for any 'down' tests
316
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceShutdown, instance)
317

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

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

    
342
  RunTestIf(["instance-grow-disk"], qa_instance.TestInstanceGrowDisk, instance)
343

    
344
  # and now start the instance again
345
  RunTestIf(DOWN_TESTS, qa_instance.TestInstanceStartup, instance)
346

    
347
  RunTestIf("instance-reboot", qa_instance.TestInstanceReboot, instance)
348

    
349
  RunTestIf("tags", qa_tags.TestInstanceTags, instance)
350

    
351
  if instance.disk_template == constants.DT_DRBD8:
352
    RunTestIf("cluster-verify",
353
              qa_cluster.TestClusterVerifyDisksBrokenDRBD, instance, inst_nodes)
354
  RunTestIf("cluster-verify", qa_cluster.TestClusterVerify)
355

    
356
  RunTestIf(qa_rapi.Enabled, qa_rapi.TestInstance, instance)
357

    
358
  # Lists instances, too
359
  RunTestIf("node-list", qa_node.TestNodeList)
360

    
361
  # Some jobs have been run, let's test listing them
362
  RunTestIf("job-list", qa_job.TestJobList)
363

    
364

    
365
def RunCommonNodeTests():
366
  """Run a few common node tests.
367

368
  """
369
  RunTestIf("node-volumes", qa_node.TestNodeVolumes)
370
  RunTestIf("node-storage", qa_node.TestNodeStorage)
371
  RunTestIf(["node-oob", qa_config.NoVirtualCluster], qa_node.TestOutOfBand)
372

    
373

    
374
def RunGroupListTests():
375
  """Run tests for listing node groups.
376

377
  """
378
  RunTestIf("group-list", qa_group.TestGroupList)
379
  RunTestIf("group-list", qa_group.TestGroupListFields)
380

    
381

    
382
def RunNetworkTests():
383
  """Run tests for network management.
384

385
  """
386
  RunTestIf("network", qa_network.TestNetworkAddRemove)
387
  RunTestIf("network", qa_network.TestNetworkConnect)
388

    
389

    
390
def RunGroupRwTests():
391
  """Run tests for adding/removing/renaming groups.
392

393
  """
394
  RunTestIf("group-rwops", qa_group.TestGroupAddRemoveRename)
395
  RunTestIf("group-rwops", qa_group.TestGroupAddWithOptions)
396
  RunTestIf("group-rwops", qa_group.TestGroupModify)
397
  RunTestIf(["group-rwops", qa_rapi.Enabled], qa_rapi.TestRapiNodeGroups)
398
  RunTestIf(["group-rwops", "tags"], qa_tags.TestGroupTags,
399
            qa_group.GetDefaultGroup())
400

    
401

    
402
def RunExportImportTests(instance, inodes):
403
  """Tries to export and import the instance.
404

405
  @type inodes: list of nodes
406
  @param inodes: current nodes of the instance
407

408
  """
409
  # FIXME: export explicitly bails out on file based storage. other non-lvm
410
  # based storage types are untested, though. Also note that import could still
411
  # work, but is deeply embedded into the "export" case.
412
  if (qa_config.TestEnabled("instance-export") and
413
      instance.disk_template not in [constants.DT_FILE,
414
                                     constants.DT_SHARED_FILE]):
415
    RunTest(qa_instance.TestInstanceExportNoTarget, instance)
416

    
417
    pnode = inodes[0]
418
    expnode = qa_config.AcquireNode(exclude=pnode)
419
    try:
420
      name = RunTest(qa_instance.TestInstanceExport, instance, expnode)
421

    
422
      RunTest(qa_instance.TestBackupList, expnode)
423

    
424
      if qa_config.TestEnabled("instance-import"):
425
        newinst = qa_config.AcquireInstance()
426
        try:
427
          RunTest(qa_instance.TestInstanceImport, newinst, pnode,
428
                  expnode, name)
429
          # Check if starting the instance works
430
          RunTest(qa_instance.TestInstanceStartup, newinst)
431
          RunTest(qa_instance.TestInstanceRemove, newinst)
432
        finally:
433
          newinst.Release()
434
    finally:
435
      expnode.Release()
436

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

    
452

    
453
def RunDaemonTests(instance):
454
  """Test the ganeti-watcher script.
455

456
  """
457
  RunTest(qa_daemon.TestPauseWatcher)
458

    
459
  RunTestIf("instance-automatic-restart",
460
            qa_daemon.TestInstanceAutomaticRestart, instance)
461
  RunTestIf("instance-consecutive-failures",
462
            qa_daemon.TestInstanceConsecutiveFailures, instance)
463

    
464
  RunTest(qa_daemon.TestResumeWatcher)
465

    
466

    
467
def RunHardwareFailureTests(instance, inodes):
468
  """Test cluster internal hardware failure recovery.
469

470
  """
471
  RunTestIf("instance-failover", qa_instance.TestInstanceFailover, instance)
472
  RunTestIf(["instance-failover", qa_rapi.Enabled],
473
            qa_rapi.TestRapiInstanceFailover, instance)
474

    
475
  RunTestIf("instance-migrate", qa_instance.TestInstanceMigrate, instance)
476
  RunTestIf(["instance-migrate", qa_rapi.Enabled],
477
            qa_rapi.TestRapiInstanceMigrate, instance)
478

    
479
  if qa_config.TestEnabled("instance-replace-disks"):
480
    # We just need alternative secondary nodes, hence "- 1"
481
    othernodes = qa_config.AcquireManyNodes(len(inodes) - 1, exclude=inodes)
482
    try:
483
      RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceReplaceDisks, instance)
484
      RunTest(qa_instance.TestReplaceDisks,
485
              instance, inodes, othernodes)
486
    finally:
487
      qa_config.ReleaseManyNodes(othernodes)
488
    del othernodes
489

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

    
509
  if len(inodes) >= 2:
510
    RunTestIf("node-evacuate", qa_node.TestNodeEvacuate, inodes[0], inodes[1])
511
    RunTestIf("node-failover", qa_node.TestNodeFailover, inodes[0], inodes[1])
512
    RunTestIf("node-migrate", qa_node.TestNodeMigrate, inodes[0], inodes[1])
513

    
514

    
515
def RunExclusiveStorageTests():
516
  """Test exclusive storage."""
517
  if not qa_config.TestEnabled("cluster-exclusive-storage"):
518
    return
519

    
520
  node = qa_config.AcquireNode()
521
  try:
522
    old_es = qa_cluster.TestSetExclStorCluster(False)
523
    qa_node.TestExclStorSingleNode(node)
524

    
525
    qa_cluster.TestSetExclStorCluster(True)
526
    qa_cluster.TestExclStorSharedPv(node)
527

    
528
    if qa_config.TestEnabled("instance-add-plain-disk"):
529
      # Make sure that the cluster doesn't have any pre-existing problem
530
      qa_cluster.AssertClusterVerify()
531

    
532
      # Create and allocate instances
533
      instance1 = qa_instance.TestInstanceAddWithPlainDisk([node])
534
      try:
535
        instance2 = qa_instance.TestInstanceAddWithPlainDisk([node])
536
        try:
537
          # cluster-verify checks that disks are allocated correctly
538
          qa_cluster.AssertClusterVerify()
539

    
540
          # Remove instances
541
          qa_instance.TestInstanceRemove(instance2)
542
          qa_instance.TestInstanceRemove(instance1)
543
        finally:
544
          instance2.Release()
545
      finally:
546
        instance1.Release()
547

    
548
    if qa_config.TestEnabled("instance-add-drbd-disk"):
549
      snode = qa_config.AcquireNode()
550
      try:
551
        qa_cluster.TestSetExclStorCluster(False)
552
        instance = qa_instance.TestInstanceAddWithDrbdDisk([node, snode])
553
        try:
554
          qa_cluster.TestSetExclStorCluster(True)
555
          exp_err = [constants.CV_EINSTANCEUNSUITABLENODE]
556
          qa_cluster.AssertClusterVerify(fail=True, errors=exp_err)
557
          qa_instance.TestInstanceRemove(instance)
558
        finally:
559
          instance.Release()
560
      finally:
561
        snode.Release()
562
    qa_cluster.TestSetExclStorCluster(old_es)
563
  finally:
564
    node.Release()
565

    
566

    
567
def _BuildSpecDict(par, mn, st, mx):
568
  return {
569
    constants.ISPECS_MINMAX: [{
570
      constants.ISPECS_MIN: {par: mn},
571
      constants.ISPECS_MAX: {par: mx},
572
      }],
573
    constants.ISPECS_STD: {par: st},
574
    }
575

    
576

    
577
def _BuildDoubleSpecDict(index, par, mn, st, mx):
578
  new_spec = {
579
    constants.ISPECS_MINMAX: [{}, {}],
580
    }
581
  if st is not None:
582
    new_spec[constants.ISPECS_STD] = {par: st}
583
  new_spec[constants.ISPECS_MINMAX][index] = {
584
    constants.ISPECS_MIN: {par: mn},
585
    constants.ISPECS_MAX: {par: mx},
586
    }
587
  return new_spec
588

    
589

    
590
def TestIPolicyPlainInstance():
591
  """Test instance policy interaction with instances"""
592
  params = ["memory-size", "cpu-count", "disk-count", "disk-size", "nic-count"]
593
  if not qa_config.IsTemplateSupported(constants.DT_PLAIN):
594
    print "Template %s not supported" % constants.DT_PLAIN
595
    return
596

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

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

    
653
      # Apply the changes, and check policy violations after each change
654
      qa_cluster.AssertClusterVerify()
655
      for (new_specs, diff_specs, failed) in history:
656
        qa_cluster.TestClusterSetISpecs(new_specs=new_specs,
657
                                        diff_specs=diff_specs)
658
        if failed:
659
          qa_cluster.AssertClusterVerify(warnings=policyerror)
660
        else:
661
          qa_cluster.AssertClusterVerify()
662

    
663
      qa_instance.TestInstanceRemove(instance)
664
    finally:
665
      instance.Release()
666

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

    
678

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

    
702

    
703
def RunInstanceTests():
704
  """Create and exercise instances."""
705
  instance_tests = [
706
    ("instance-add-plain-disk", constants.DT_PLAIN,
707
     qa_instance.TestInstanceAddWithPlainDisk, 1),
708
    ("instance-add-drbd-disk", constants.DT_DRBD8,
709
     qa_instance.TestInstanceAddWithDrbdDisk, 2),
710
    ("instance-add-diskless", constants.DT_DISKLESS,
711
     qa_instance.TestInstanceAddDiskless, 1),
712
    ("instance-add-file", constants.DT_FILE,
713
     qa_instance.TestInstanceAddFile, 1),
714
    ("instance-add-shared-file", constants.DT_SHARED_FILE,
715
     qa_instance.TestInstanceAddSharedFile, 1),
716
    ]
717

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

    
758

    
759
def RunMonitoringTests():
760
  if qa_config.TestEnabled("mon-collector"):
761
    RunTest(qa_monitoring.TestInstStatusCollector)
762

    
763

    
764
def RunQa():
765
  """Main QA body.
766

767
  """
768
  rapi_user = "ganeti-qa"
769

    
770
  RunEnvTests()
771
  rapi_secret = SetupCluster(rapi_user)
772

    
773
  if qa_rapi.Enabled():
774
    # Load RAPI certificate
775
    qa_rapi.Setup(rapi_user, rapi_secret)
776

    
777
  RunClusterTests()
778
  RunOsTests()
779

    
780
  RunTestIf("tags", qa_tags.TestClusterTags)
781

    
782
  RunCommonNodeTests()
783
  RunGroupListTests()
784
  RunGroupRwTests()
785
  RunNetworkTests()
786

    
787
  # The master shouldn't be readded or put offline; "delay" needs a non-master
788
  # node to test
789
  pnode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
790
  try:
791
    RunTestIf("node-readd", qa_node.TestNodeReadd, pnode)
792
    RunTestIf("node-modify", qa_node.TestNodeModify, pnode)
793
    RunTestIf("delay", qa_cluster.TestDelay, pnode)
794
  finally:
795
    pnode.Release()
796

    
797
  # Make sure the cluster is clean before running instance tests
798
  qa_cluster.AssertClusterVerify()
799

    
800
  pnode = qa_config.AcquireNode()
801
  try:
802
    RunTestIf("tags", qa_tags.TestNodeTags, pnode)
803

    
804
    if qa_rapi.Enabled():
805
      RunTest(qa_rapi.TestNode, pnode)
806

    
807
      if qa_config.TestEnabled("instance-add-plain-disk"):
808
        for use_client in [True, False]:
809
          rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
810
                                  use_client)
811
          try:
812
            if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
813
              RunCommonInstanceTests(rapi_instance, [pnode])
814
            RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
815
          finally:
816
            rapi_instance.Release()
817
          del rapi_instance
818

    
819
  finally:
820
    pnode.Release()
821

    
822
  config_list = [
823
    ("default-instance-tests", lambda: None, lambda _: None),
824
    (IsExclusiveStorageInstanceTestEnabled,
825
     lambda: qa_cluster.TestSetExclStorCluster(True),
826
     qa_cluster.TestSetExclStorCluster),
827
  ]
828
  for (conf_name, setup_conf_f, restore_conf_f) in config_list:
829
    if qa_config.TestEnabled(conf_name):
830
      oldconf = setup_conf_f()
831
      RunInstanceTests()
832
      restore_conf_f(oldconf)
833

    
834
  pnode = qa_config.AcquireNode()
835
  try:
836
    if qa_config.TestEnabled(["instance-add-plain-disk", "instance-export"]):
837
      for shutdown in [False, True]:
838
        instance = RunTest(qa_instance.TestInstanceAddWithPlainDisk, [pnode])
839
        try:
840
          expnode = qa_config.AcquireNode(exclude=pnode)
841
          try:
842
            if shutdown:
843
              # Stop instance before exporting and removing it
844
              RunTest(qa_instance.TestInstanceShutdown, instance)
845
            RunTest(qa_instance.TestInstanceExportWithRemove, instance, expnode)
846
            RunTest(qa_instance.TestBackupList, expnode)
847
          finally:
848
            expnode.Release()
849
        finally:
850
          instance.Release()
851
        del expnode
852
        del instance
853
      qa_cluster.AssertClusterVerify()
854

    
855
  finally:
856
    pnode.Release()
857

    
858
  RunExclusiveStorageTests()
859
  RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
860
            TestIPolicyPlainInstance)
861

    
862
  RunTestIf(
863
    "instance-add-restricted-by-disktemplates",
864
    qa_instance.TestInstanceCreationRestrictedByDiskTemplates)
865

    
866
  # Test removing instance with offline drbd secondary
867
  if qa_config.TestEnabled(["instance-remove-drbd-offline",
868
                            "instance-add-drbd-disk"]):
869
    # Make sure the master is not put offline
870
    snode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
871
    try:
872
      pnode = qa_config.AcquireNode(exclude=snode)
873
      try:
874
        instance = qa_instance.TestInstanceAddWithDrbdDisk([pnode, snode])
875
        set_offline = lambda node: qa_node.MakeNodeOffline(node, "yes")
876
        set_online = lambda node: qa_node.MakeNodeOffline(node, "no")
877
        RunTest(qa_instance.TestRemoveInstanceOfflineNode, instance, snode,
878
                set_offline, set_online)
879
      finally:
880
        pnode.Release()
881
    finally:
882
      snode.Release()
883
    qa_cluster.AssertClusterVerify()
884

    
885
  RunMonitoringTests()
886

    
887
  RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)
888

    
889
  RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)
890

    
891

    
892
@UsesRapiClient
893
def main():
894
  """Main program.
895

896
  """
897
  parser = optparse.OptionParser(usage="%prog [options] <config-file>")
898
  parser.add_option("--yes-do-it", dest="yes_do_it",
899
                    action="store_true",
900
                    help="Really execute the tests")
901
  (opts, args) = parser.parse_args()
902

    
903
  if len(args) == 1:
904
    (config_file, ) = args
905
  else:
906
    parser.error("Wrong number of arguments.")
907

    
908
  if not opts.yes_do_it:
909
    print ("Executing this script irreversibly destroys any Ganeti\n"
910
           "configuration on all nodes involved. If you really want\n"
911
           "to start testing, supply the --yes-do-it option.")
912
    sys.exit(1)
913

    
914
  qa_config.Load(config_file)
915

    
916
  primary = qa_config.GetMasterNode().primary
917
  qa_utils.StartMultiplexer(primary)
918
  print ("SSH command for primary node: %s" %
919
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
920
  print ("SSH command for other nodes: %s" %
921
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
922
  try:
923
    RunQa()
924
  finally:
925
    qa_utils.CloseMultiplexers()
926

    
927
if __name__ == "__main__":
928
  main()