Statistics
| Branch: | Tag: | Revision:

root / qa / ganeti-qa.py @ 94f06b98

History | View | Annotate | Download (29.8 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 not in
441
           [constants.DT_FILE, constants.DT_SHARED_FILE])):
442
    newinst = qa_config.AcquireInstance()
443
    try:
444
      tnode = qa_config.AcquireNode(exclude=inodes)
445
      try:
446
        RunTest(qa_rapi.TestInterClusterInstanceMove, instance, newinst,
447
                inodes, tnode)
448
      finally:
449
        tnode.Release()
450
    finally:
451
      newinst.Release()
452

    
453

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

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

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

    
465
  RunTest(qa_daemon.TestResumeWatcher)
466

    
467

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

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

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

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

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

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

    
515

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

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

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

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

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

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

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

    
567

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

    
577

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

    
590

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

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

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

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

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

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

    
679

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

    
703

    
704
def RunInstanceTests():
705
  """Create and exercise instances."""
706

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

    
748

    
749
def RunMonitoringTests():
750
  if qa_config.TestEnabled("mon-collector"):
751
    RunTest(qa_monitoring.TestInstStatusCollector)
752

    
753

    
754
def RunQa():
755
  """Main QA body.
756

757
  """
758
  rapi_user = "ganeti-qa"
759

    
760
  RunEnvTests()
761
  rapi_secret = SetupCluster(rapi_user)
762

    
763
  if qa_rapi.Enabled():
764
    # Load RAPI certificate
765
    qa_rapi.Setup(rapi_user, rapi_secret)
766

    
767
  RunClusterTests()
768
  RunOsTests()
769

    
770
  RunTestIf("tags", qa_tags.TestClusterTags)
771

    
772
  RunCommonNodeTests()
773
  RunGroupListTests()
774
  RunGroupRwTests()
775
  RunNetworkTests()
776

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

    
787
  # Make sure the cluster is clean before running instance tests
788
  qa_cluster.AssertClusterVerify()
789

    
790
  pnode = qa_config.AcquireNode()
791
  try:
792
    RunTestIf("tags", qa_tags.TestNodeTags, pnode)
793

    
794
    if qa_rapi.Enabled():
795
      RunTest(qa_rapi.TestNode, pnode)
796

    
797
      if (qa_config.TestEnabled("instance-add-plain-disk")
798
          and qa_config.IsTemplateSupported(constants.DT_PLAIN)):
799
        for use_client in [True, False]:
800
          rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
801
                                  use_client)
802
          try:
803
            if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
804
              RunCommonInstanceTests(rapi_instance, [pnode])
805
            RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
806
          finally:
807
            rapi_instance.Release()
808
          del rapi_instance
809

    
810
  finally:
811
    pnode.Release()
812

    
813
  config_list = [
814
    ("default-instance-tests", lambda: None, lambda _: None),
815
    (IsExclusiveStorageInstanceTestEnabled,
816
     lambda: qa_cluster.TestSetExclStorCluster(True),
817
     qa_cluster.TestSetExclStorCluster),
818
  ]
819
  for (conf_name, setup_conf_f, restore_conf_f) in config_list:
820
    if qa_config.TestEnabled(conf_name):
821
      oldconf = setup_conf_f()
822
      RunInstanceTests()
823
      restore_conf_f(oldconf)
824

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

    
846
  finally:
847
    pnode.Release()
848

    
849
  RunTestIf("cluster-upgrade", qa_cluster.TestUpgrade)
850

    
851
  RunExclusiveStorageTests()
852
  RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
853
            TestIPolicyPlainInstance)
854

    
855
  RunTestIf(
856
    "instance-add-restricted-by-disktemplates",
857
    qa_instance.TestInstanceCreationRestrictedByDiskTemplates)
858

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

    
878
  RunMonitoringTests()
879

    
880
  RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)
881

    
882
  RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)
883

    
884

    
885
@UsesRapiClient
886
def main():
887
  """Main program.
888

889
  """
890
  parser = optparse.OptionParser(usage="%prog [options] <config-file>")
891
  parser.add_option("--yes-do-it", dest="yes_do_it",
892
                    action="store_true",
893
                    help="Really execute the tests")
894
  (opts, args) = parser.parse_args()
895

    
896
  if len(args) == 1:
897
    (config_file, ) = args
898
  else:
899
    parser.error("Wrong number of arguments.")
900

    
901
  if not opts.yes_do_it:
902
    print ("Executing this script irreversibly destroys any Ganeti\n"
903
           "configuration on all nodes involved. If you really want\n"
904
           "to start testing, supply the --yes-do-it option.")
905
    sys.exit(1)
906

    
907
  qa_config.Load(config_file)
908

    
909
  primary = qa_config.GetMasterNode().primary
910
  qa_utils.StartMultiplexer(primary)
911
  print ("SSH command for primary node: %s" %
912
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
913
  print ("SSH command for other nodes: %s" %
914
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
915
  try:
916
    RunQa()
917
  finally:
918
    qa_utils.CloseMultiplexers()
919

    
920
if __name__ == "__main__":
921
  main()