Statistics
| Branch: | Tag: | Revision:

root / qa / ganeti-qa.py @ 2ee9171a

History | View | Annotate | Download (30.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
  RunTestIf("test-jobqueue", qa_job.TestJobCancellation)
184

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

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

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

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

    
198
  return rapi_secret
199

    
200

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

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

    
239

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

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

    
246

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

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

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

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

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

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

    
278

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
365

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

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

    
374

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

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

    
382

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

386
  """
387
  RunTestIf("network", qa_network.TestNetworkAddRemove)
388
  RunTestIf("network", qa_network.TestNetworkConnect)
389
  RunTestIf(["network", "tags"], qa_network.TestNetworkTags)
390

    
391

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

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

    
403

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

407
  @type inodes: list of nodes
408
  @param inodes: current nodes of the instance
409

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

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

    
424
      RunTest(qa_instance.TestBackupList, expnode)
425

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

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

    
455

    
456
def RunDaemonTests(instance):
457
  """Test the ganeti-watcher script.
458

459
  """
460
  RunTest(qa_daemon.TestPauseWatcher)
461

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

    
467
  RunTest(qa_daemon.TestResumeWatcher)
468

    
469

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

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

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

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

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

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

    
517

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

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

    
528
    qa_cluster.TestSetExclStorCluster(True)
529
    qa_cluster.TestExclStorSharedPv(node)
530

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

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

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

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

    
569

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

    
579

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

    
592

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

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

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

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

    
666
      qa_instance.TestInstanceRemove(instance)
667
    finally:
668
      instance.Release()
669

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

    
681

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

    
705

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

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

    
761

    
762
def RunMonitoringTests():
763
  if qa_config.TestEnabled("mon-collector"):
764
    RunTest(qa_monitoring.TestInstStatusCollector)
765

    
766

    
767
def RunQa():
768
  """Main QA body.
769

770
  """
771
  rapi_user = "ganeti-qa"
772

    
773
  RunEnvTests()
774
  rapi_secret = SetupCluster(rapi_user)
775

    
776
  if qa_rapi.Enabled():
777
    # Load RAPI certificate
778
    qa_rapi.Setup(rapi_user, rapi_secret)
779

    
780
  RunClusterTests()
781
  RunOsTests()
782

    
783
  RunTestIf("tags", qa_tags.TestClusterTags)
784

    
785
  RunCommonNodeTests()
786
  RunGroupListTests()
787
  RunGroupRwTests()
788
  RunNetworkTests()
789

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

    
800
  # Make sure the cluster is clean before running instance tests
801
  qa_cluster.AssertClusterVerify()
802

    
803
  pnode = qa_config.AcquireNode()
804
  try:
805
    RunTestIf("tags", qa_tags.TestNodeTags, pnode)
806

    
807
    if qa_rapi.Enabled():
808
      RunTest(qa_rapi.TestNode, pnode)
809

    
810
      if (qa_config.TestEnabled("instance-add-plain-disk")
811
          and qa_config.IsTemplateSupported(constants.DT_PLAIN)):
812
        # Normal instance allocation via RAPI
813
        for use_client in [True, False]:
814
          rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
815
                                  use_client)
816
          try:
817
            if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
818
              RunCommonInstanceTests(rapi_instance, [pnode])
819
            RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
820
          finally:
821
            rapi_instance.Release()
822
          del rapi_instance
823

    
824
        # Multi-instance allocation
825
        rapi_instance_one, rapi_instance_two = \
826
          RunTest(qa_rapi.TestRapiInstanceMultiAlloc, pnode)
827

    
828
        try:
829
          RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance_one, True)
830
          RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance_two, True)
831
        finally:
832
          rapi_instance_one.Release()
833
          rapi_instance_two.Release()
834
  finally:
835
    pnode.Release()
836

    
837
  config_list = [
838
    ("default-instance-tests", lambda: None, lambda _: None),
839
    (IsExclusiveStorageInstanceTestEnabled,
840
     lambda: qa_cluster.TestSetExclStorCluster(True),
841
     qa_cluster.TestSetExclStorCluster),
842
  ]
843
  for (conf_name, setup_conf_f, restore_conf_f) in config_list:
844
    if qa_config.TestEnabled(conf_name):
845
      oldconf = setup_conf_f()
846
      RunInstanceTests()
847
      restore_conf_f(oldconf)
848

    
849
  pnode = qa_config.AcquireNode()
850
  try:
851
    if qa_config.TestEnabled(["instance-add-plain-disk", "instance-export"]):
852
      for shutdown in [False, True]:
853
        instance = RunTest(qa_instance.TestInstanceAddWithPlainDisk, [pnode])
854
        try:
855
          expnode = qa_config.AcquireNode(exclude=pnode)
856
          try:
857
            if shutdown:
858
              # Stop instance before exporting and removing it
859
              RunTest(qa_instance.TestInstanceShutdown, instance)
860
            RunTest(qa_instance.TestInstanceExportWithRemove, instance, expnode)
861
            RunTest(qa_instance.TestBackupList, expnode)
862
          finally:
863
            expnode.Release()
864
        finally:
865
          instance.Release()
866
        del expnode
867
        del instance
868
      qa_cluster.AssertClusterVerify()
869

    
870
  finally:
871
    pnode.Release()
872

    
873
  RunExclusiveStorageTests()
874
  RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
875
            TestIPolicyPlainInstance)
876

    
877
  RunTestIf(
878
    "instance-add-restricted-by-disktemplates",
879
    qa_instance.TestInstanceCreationRestrictedByDiskTemplates)
880

    
881
  # Test removing instance with offline drbd secondary
882
  if qa_config.TestEnabled(["instance-remove-drbd-offline",
883
                            "instance-add-drbd-disk"]):
884
    # Make sure the master is not put offline
885
    snode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
886
    try:
887
      pnode = qa_config.AcquireNode(exclude=snode)
888
      try:
889
        instance = qa_instance.TestInstanceAddWithDrbdDisk([pnode, snode])
890
        set_offline = lambda node: qa_node.MakeNodeOffline(node, "yes")
891
        set_online = lambda node: qa_node.MakeNodeOffline(node, "no")
892
        RunTest(qa_instance.TestRemoveInstanceOfflineNode, instance, snode,
893
                set_offline, set_online)
894
      finally:
895
        pnode.Release()
896
    finally:
897
      snode.Release()
898
    qa_cluster.AssertClusterVerify()
899

    
900
  RunMonitoringTests()
901

    
902
  RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)
903

    
904
  RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)
905

    
906

    
907
@UsesRapiClient
908
def main():
909
  """Main program.
910

911
  """
912
  parser = optparse.OptionParser(usage="%prog [options] <config-file>")
913
  parser.add_option("--yes-do-it", dest="yes_do_it",
914
                    action="store_true",
915
                    help="Really execute the tests")
916
  (opts, args) = parser.parse_args()
917

    
918
  if len(args) == 1:
919
    (config_file, ) = args
920
  else:
921
    parser.error("Wrong number of arguments.")
922

    
923
  if not opts.yes_do_it:
924
    print ("Executing this script irreversibly destroys any Ganeti\n"
925
           "configuration on all nodes involved. If you really want\n"
926
           "to start testing, supply the --yes-do-it option.")
927
    sys.exit(1)
928

    
929
  qa_config.Load(config_file)
930

    
931
  primary = qa_config.GetMasterNode().primary
932
  qa_utils.StartMultiplexer(primary)
933
  print ("SSH command for primary node: %s" %
934
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
935
  print ("SSH command for other nodes: %s" %
936
         utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
937
  try:
938
    RunQa()
939
  finally:
940
    qa_utils.CloseMultiplexers()
941

    
942
if __name__ == "__main__":
943
  main()