567732c07f8893d6a3dd7b9a1399ce29b69bde0e
[ganeti-local] / qa / ganeti-qa.py
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 sys
30 import datetime
31 import optparse
32
33 import qa_cluster
34 import qa_config
35 import qa_daemon
36 import qa_env
37 import qa_error
38 import qa_group
39 import qa_instance
40 import qa_network
41 import qa_node
42 import qa_os
43 import qa_job
44 import qa_rapi
45 import qa_tags
46 import qa_utils
47
48 from ganeti import utils
49 from ganeti import rapi # pylint: disable=W0611
50 from ganeti import constants
51
52 import ganeti.rapi.client # pylint: disable=W0611
53 from ganeti.rapi.client import UsesRapiClient
54
55
56 def _FormatHeader(line, end=72):
57   """Fill a line up to the end column.
58
59   """
60   line = "---- " + line + " "
61   line += "-" * (end - len(line))
62   line = line.rstrip()
63   return line
64
65
66 def _DescriptionOf(fn):
67   """Computes the description of an item.
68
69   """
70   if fn.__doc__:
71     desc = fn.__doc__.splitlines()[0].strip()
72   else:
73     desc = "%r" % fn
74
75   return desc.rstrip(".")
76
77
78 def RunTest(fn, *args, **kwargs):
79   """Runs a test after printing a header.
80
81   """
82
83   tstart = datetime.datetime.now()
84
85   desc = _DescriptionOf(fn)
86
87   print
88   print _FormatHeader("%s start %s" % (tstart, desc))
89
90   try:
91     retval = fn(*args, **kwargs)
92     return retval
93   finally:
94     tstop = datetime.datetime.now()
95     tdelta = tstop - tstart
96     print _FormatHeader("%s time=%s %s" % (tstop, tdelta, desc))
97
98
99 def RunTestIf(testnames, fn, *args, **kwargs):
100   """Runs a test conditionally.
101
102   @param testnames: either a single test name in the configuration
103       file, or a list of testnames (which will be AND-ed together)
104
105   """
106   if qa_config.TestEnabled(testnames):
107     RunTest(fn, *args, **kwargs)
108   else:
109     tstart = datetime.datetime.now()
110     desc = _DescriptionOf(fn)
111     # TODO: Formatting test names when non-string names are involved
112     print _FormatHeader("%s skipping %s, test(s) %s disabled" %
113                         (tstart, desc, testnames))
114
115
116 def RunEnvTests():
117   """Run several environment tests.
118
119   """
120   RunTestIf("env", qa_env.TestSshConnection)
121   RunTestIf("env", qa_env.TestIcmpPing)
122   RunTestIf("env", qa_env.TestGanetiCommands)
123
124
125 def SetupCluster(rapi_user, rapi_secret):
126   """Initializes the cluster.
127
128   @param rapi_user: Login user for RAPI
129   @param rapi_secret: Login secret for RAPI
130
131   """
132   RunTestIf("create-cluster", qa_cluster.TestClusterInit,
133             rapi_user, rapi_secret)
134   if not qa_config.TestEnabled("create-cluster"):
135     # If the cluster is already in place, we assume that exclusive-storage is
136     # already set according to the configuration
137     qa_config.SetExclusiveStorage(qa_config.get("exclusive-storage", False))
138
139   # Test on empty cluster
140   RunTestIf("node-list", qa_node.TestNodeList)
141   RunTestIf("instance-list", qa_instance.TestInstanceList)
142   RunTestIf("job-list", qa_job.TestJobList)
143
144   RunTestIf("create-cluster", qa_node.TestNodeAddAll)
145   if not qa_config.TestEnabled("create-cluster"):
146     # consider the nodes are already there
147     qa_node.MarkNodeAddedAll()
148
149   RunTestIf("test-jobqueue", qa_cluster.TestJobqueue)
150
151   # enable the watcher (unconditionally)
152   RunTest(qa_daemon.TestResumeWatcher)
153
154   RunTestIf("node-list", qa_node.TestNodeList)
155
156   # Test listing fields
157   RunTestIf("node-list", qa_node.TestNodeListFields)
158   RunTestIf("instance-list", qa_instance.TestInstanceListFields)
159   RunTestIf("job-list", qa_job.TestJobListFields)
160   RunTestIf("instance-export", qa_instance.TestBackupListFields)
161
162   RunTestIf("node-info", qa_node.TestNodeInfo)
163
164
165 def RunClusterTests():
166   """Runs tests related to gnt-cluster.
167
168   """
169   for test, fn in [
170     ("create-cluster", qa_cluster.TestClusterInitDisk),
171     ("cluster-renew-crypto", qa_cluster.TestClusterRenewCrypto),
172     ("cluster-verify", qa_cluster.TestClusterVerify),
173     ("cluster-reserved-lvs", qa_cluster.TestClusterReservedLvs),
174     # TODO: add more cluster modify tests
175     ("cluster-modify", qa_cluster.TestClusterModifyEmpty),
176     ("cluster-modify", qa_cluster.TestClusterModifyIPolicy),
177     ("cluster-modify", qa_cluster.TestClusterModifyISpecs),
178     ("cluster-modify", qa_cluster.TestClusterModifyBe),
179     ("cluster-modify", qa_cluster.TestClusterModifyDisk),
180     ("cluster-rename", qa_cluster.TestClusterRename),
181     ("cluster-info", qa_cluster.TestClusterVersion),
182     ("cluster-info", qa_cluster.TestClusterInfo),
183     ("cluster-info", qa_cluster.TestClusterGetmaster),
184     ("cluster-redist-conf", qa_cluster.TestClusterRedistConf),
185     (["cluster-copyfile", qa_config.NoVirtualCluster],
186      qa_cluster.TestClusterCopyfile),
187     ("cluster-command", qa_cluster.TestClusterCommand),
188     ("cluster-burnin", qa_cluster.TestClusterBurnin),
189     ("cluster-master-failover", qa_cluster.TestClusterMasterFailover),
190     ("cluster-master-failover",
191      qa_cluster.TestClusterMasterFailoverWithDrainedQueue),
192     (["cluster-oob", qa_config.NoVirtualCluster],
193      qa_cluster.TestClusterOob),
194     (qa_rapi.Enabled, qa_rapi.TestVersion),
195     (qa_rapi.Enabled, qa_rapi.TestEmptyCluster),
196     (qa_rapi.Enabled, qa_rapi.TestRapiQuery),
197     ]:
198     RunTestIf(test, fn)
199
200
201 def RunRepairDiskSizes():
202   """Run the repair disk-sizes test.
203
204   """
205   RunTestIf("cluster-repair-disk-sizes", qa_cluster.TestClusterRepairDiskSizes)
206
207
208 def RunOsTests():
209   """Runs all tests related to gnt-os.
210
211   """
212   os_enabled = ["os", qa_config.NoVirtualCluster]
213
214   if qa_config.TestEnabled(qa_rapi.Enabled):
215     rapi_getos = qa_rapi.GetOperatingSystems
216   else:
217     rapi_getos = None
218
219   for fn in [
220     qa_os.TestOsList,
221     qa_os.TestOsDiagnose,
222     ]:
223     RunTestIf(os_enabled, fn)
224
225   for fn in [
226     qa_os.TestOsValid,
227     qa_os.TestOsInvalid,
228     qa_os.TestOsPartiallyValid,
229     ]:
230     RunTestIf(os_enabled, fn, rapi_getos)
231
232   for fn in [
233     qa_os.TestOsModifyValid,
234     qa_os.TestOsModifyInvalid,
235     qa_os.TestOsStatesNonExisting,
236     ]:
237     RunTestIf(os_enabled, fn)
238
239
240 def RunCommonInstanceTests(instance):
241   """Runs a few tests that are common to all disk types.
242
243   """
244   RunTestIf("instance-shutdown", qa_instance.TestInstanceShutdown, instance)
245   RunTestIf(["instance-shutdown", "instance-console", qa_rapi.Enabled],
246             qa_rapi.TestRapiStoppedInstanceConsole, instance)
247   RunTestIf(["instance-shutdown", "instance-modify"],
248             qa_instance.TestInstanceStoppedModify, instance)
249   RunTestIf("instance-shutdown", qa_instance.TestInstanceStartup, instance)
250
251   # Test shutdown/start via RAPI
252   RunTestIf(["instance-shutdown", qa_rapi.Enabled],
253             qa_rapi.TestRapiInstanceShutdown, instance)
254   RunTestIf(["instance-shutdown", qa_rapi.Enabled],
255             qa_rapi.TestRapiInstanceStartup, instance)
256
257   RunTestIf("instance-list", qa_instance.TestInstanceList)
258
259   RunTestIf("instance-info", qa_instance.TestInstanceInfo, instance)
260
261   RunTestIf("instance-modify", qa_instance.TestInstanceModify, instance)
262   RunTestIf(["instance-modify", qa_rapi.Enabled],
263             qa_rapi.TestRapiInstanceModify, instance)
264
265   RunTestIf("instance-console", qa_instance.TestInstanceConsole, instance)
266   RunTestIf(["instance-console", qa_rapi.Enabled],
267             qa_rapi.TestRapiInstanceConsole, instance)
268
269   DOWN_TESTS = qa_config.Either([
270     "instance-reinstall",
271     "instance-rename",
272     "instance-grow-disk",
273     ])
274
275   # shutdown instance for any 'down' tests
276   RunTestIf(DOWN_TESTS, qa_instance.TestInstanceShutdown, instance)
277
278   # now run the 'down' state tests
279   RunTestIf("instance-reinstall", qa_instance.TestInstanceReinstall, instance)
280   RunTestIf(["instance-reinstall", qa_rapi.Enabled],
281             qa_rapi.TestRapiInstanceReinstall, instance)
282
283   if qa_config.TestEnabled("instance-rename"):
284     tgt_instance = qa_config.AcquireInstance()
285     try:
286       rename_source = instance.name
287       rename_target = tgt_instance.name
288       # perform instance rename to the same name
289       RunTest(qa_instance.TestInstanceRenameAndBack,
290               rename_source, rename_source)
291       RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
292                 rename_source, rename_source)
293       if rename_target is not None:
294         # perform instance rename to a different name, if we have one configured
295         RunTest(qa_instance.TestInstanceRenameAndBack,
296                 rename_source, rename_target)
297         RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceRenameAndBack,
298                   rename_source, rename_target)
299     finally:
300       tgt_instance.Release()
301
302   RunTestIf(["instance-grow-disk"], qa_instance.TestInstanceGrowDisk, instance)
303
304   # and now start the instance again
305   RunTestIf(DOWN_TESTS, qa_instance.TestInstanceStartup, instance)
306
307   RunTestIf("instance-reboot", qa_instance.TestInstanceReboot, instance)
308
309   RunTestIf("tags", qa_tags.TestInstanceTags, instance)
310
311   RunTestIf("cluster-verify", qa_cluster.TestClusterVerify)
312
313   RunTestIf(qa_rapi.Enabled, qa_rapi.TestInstance, instance)
314
315   # Lists instances, too
316   RunTestIf("node-list", qa_node.TestNodeList)
317
318   # Some jobs have been run, let's test listing them
319   RunTestIf("job-list", qa_job.TestJobList)
320
321
322 def RunCommonNodeTests():
323   """Run a few common node tests.
324
325   """
326   RunTestIf("node-volumes", qa_node.TestNodeVolumes)
327   RunTestIf("node-storage", qa_node.TestNodeStorage)
328   RunTestIf(["node-oob", qa_config.NoVirtualCluster], qa_node.TestOutOfBand)
329
330
331 def RunGroupListTests():
332   """Run tests for listing node groups.
333
334   """
335   RunTestIf("group-list", qa_group.TestGroupList)
336   RunTestIf("group-list", qa_group.TestGroupListFields)
337
338
339 def RunNetworkTests():
340   """Run tests for network management.
341
342   """
343   RunTestIf("network", qa_network.TestNetworkAddRemove)
344   RunTestIf("network", qa_network.TestNetworkConnect)
345
346
347 def RunGroupRwTests():
348   """Run tests for adding/removing/renaming groups.
349
350   """
351   RunTestIf("group-rwops", qa_group.TestGroupAddRemoveRename)
352   RunTestIf("group-rwops", qa_group.TestGroupAddWithOptions)
353   RunTestIf("group-rwops", qa_group.TestGroupModify)
354   RunTestIf(["group-rwops", qa_rapi.Enabled], qa_rapi.TestRapiNodeGroups)
355   RunTestIf(["group-rwops", "tags"], qa_tags.TestGroupTags,
356             qa_group.GetDefaultGroup())
357
358
359 def RunExportImportTests(instance, inodes):
360   """Tries to export and import the instance.
361
362   @type inodes: list of nodes
363   @param inodes: current nodes of the instance
364
365   """
366   if qa_config.TestEnabled("instance-export"):
367     RunTest(qa_instance.TestInstanceExportNoTarget, instance)
368
369     pnode = inodes[0]
370     expnode = qa_config.AcquireNode(exclude=pnode)
371     try:
372       name = RunTest(qa_instance.TestInstanceExport, instance, expnode)
373
374       RunTest(qa_instance.TestBackupList, expnode)
375
376       if qa_config.TestEnabled("instance-import"):
377         newinst = qa_config.AcquireInstance()
378         try:
379           RunTest(qa_instance.TestInstanceImport, newinst, pnode,
380                   expnode, name)
381           # Check if starting the instance works
382           RunTest(qa_instance.TestInstanceStartup, newinst)
383           RunTest(qa_instance.TestInstanceRemove, newinst)
384         finally:
385           newinst.Release()
386     finally:
387       expnode.Release()
388
389   if qa_config.TestEnabled([qa_rapi.Enabled, "inter-cluster-instance-move"]):
390     newinst = qa_config.AcquireInstance()
391     try:
392       tnode = qa_config.AcquireNode(exclude=inodes)
393       try:
394         RunTest(qa_rapi.TestInterClusterInstanceMove, instance, newinst,
395                 inodes, tnode)
396       finally:
397         tnode.Release()
398     finally:
399       newinst.Release()
400
401
402 def RunDaemonTests(instance):
403   """Test the ganeti-watcher script.
404
405   """
406   RunTest(qa_daemon.TestPauseWatcher)
407
408   RunTestIf("instance-automatic-restart",
409             qa_daemon.TestInstanceAutomaticRestart, instance)
410   RunTestIf("instance-consecutive-failures",
411             qa_daemon.TestInstanceConsecutiveFailures, instance)
412
413   RunTest(qa_daemon.TestResumeWatcher)
414
415
416 def RunHardwareFailureTests(instance, inodes):
417   """Test cluster internal hardware failure recovery.
418
419   """
420   RunTestIf("instance-failover", qa_instance.TestInstanceFailover, instance)
421   RunTestIf(["instance-failover", qa_rapi.Enabled],
422             qa_rapi.TestRapiInstanceFailover, instance)
423
424   RunTestIf("instance-migrate", qa_instance.TestInstanceMigrate, instance)
425   RunTestIf(["instance-migrate", qa_rapi.Enabled],
426             qa_rapi.TestRapiInstanceMigrate, instance)
427
428   if qa_config.TestEnabled("instance-replace-disks"):
429     # We just need alternative secondary nodes, hence "- 1"
430     othernodes = qa_config.AcquireManyNodes(len(inodes) - 1, exclude=inodes)
431     try:
432       RunTestIf(qa_rapi.Enabled, qa_rapi.TestRapiInstanceReplaceDisks, instance)
433       RunTest(qa_instance.TestReplaceDisks,
434               instance, inodes, othernodes)
435     finally:
436       qa_config.ReleaseManyNodes(othernodes)
437     del othernodes
438
439   if qa_config.TestEnabled("instance-recreate-disks"):
440     try:
441       acquirednodes = qa_config.AcquireManyNodes(len(inodes), exclude=inodes)
442       othernodes = acquirednodes
443     except qa_error.OutOfNodesError:
444       if len(inodes) > 1:
445         # If the cluster is not big enough, let's reuse some of the nodes, but
446         # with different roles. In this way, we can test a DRBD instance even on
447         # a 3-node cluster.
448         acquirednodes = [qa_config.AcquireNode(exclude=inodes)]
449         othernodes = acquirednodes + inodes[:-1]
450       else:
451         raise
452     try:
453       RunTest(qa_instance.TestRecreateDisks,
454               instance, inodes, othernodes)
455     finally:
456       qa_config.ReleaseManyNodes(acquirednodes)
457
458   if len(inodes) >= 2:
459     RunTestIf("node-evacuate", qa_node.TestNodeEvacuate, inodes[0], inodes[1])
460     RunTestIf("node-failover", qa_node.TestNodeFailover, inodes[0], inodes[1])
461
462
463 def RunExclusiveStorageTests():
464   """Test exclusive storage."""
465   if not qa_config.TestEnabled("cluster-exclusive-storage"):
466     return
467
468   node = qa_config.AcquireNode()
469   try:
470     old_es = qa_cluster.TestSetExclStorCluster(False)
471     qa_node.TestExclStorSingleNode(node)
472
473     qa_cluster.TestSetExclStorCluster(True)
474     qa_cluster.TestExclStorSharedPv(node)
475
476     if qa_config.TestEnabled("instance-add-plain-disk"):
477       # Make sure that the cluster doesn't have any pre-existing problem
478       qa_cluster.AssertClusterVerify()
479
480       # Create and allocate instances
481       instance1 = qa_instance.TestInstanceAddWithPlainDisk([node])
482       try:
483         instance2 = qa_instance.TestInstanceAddWithPlainDisk([node])
484         try:
485           # cluster-verify checks that disks are allocated correctly
486           qa_cluster.AssertClusterVerify()
487
488           # Remove instances
489           qa_instance.TestInstanceRemove(instance2)
490           qa_instance.TestInstanceRemove(instance1)
491         finally:
492           instance2.Release()
493       finally:
494         instance1.Release()
495
496     if qa_config.TestEnabled("instance-add-drbd-disk"):
497       snode = qa_config.AcquireNode()
498       try:
499         qa_cluster.TestSetExclStorCluster(False)
500         instance = qa_instance.TestInstanceAddWithDrbdDisk([node, snode])
501         try:
502           qa_cluster.TestSetExclStorCluster(True)
503           exp_err = [constants.CV_EINSTANCEUNSUITABLENODE]
504           qa_cluster.AssertClusterVerify(fail=True, errors=exp_err)
505           qa_instance.TestInstanceRemove(instance)
506         finally:
507           instance.Release()
508       finally:
509         snode.Release()
510     qa_cluster.TestSetExclStorCluster(old_es)
511   finally:
512     node.Release()
513
514
515 def _BuildSpecDict(par, mn, st, mx):
516   return {par: {"min": mn, "std": st, "max": mx}}
517
518
519 def TestIPolicyPlainInstance():
520   """Test instance policy interaction with instances"""
521   params = ["mem-size", "cpu-count", "disk-count", "disk-size", "nic-count"]
522   if not qa_config.IsTemplateSupported(constants.DT_PLAIN):
523     print "Template %s not supported" % constants.DT_PLAIN
524     return
525
526   # This test assumes that the group policy is empty
527   (_, old_specs) = qa_cluster.TestClusterSetISpecs({})
528   node = qa_config.AcquireNode()
529   try:
530     # Log of policy changes, list of tuples: (change, policy_violated)
531     history = []
532     instance = qa_instance.TestInstanceAddWithPlainDisk([node])
533     try:
534       policyerror = [constants.CV_EINSTANCEPOLICY]
535       for par in params:
536         qa_cluster.AssertClusterVerify()
537         (iminval, imaxval) = qa_instance.GetInstanceSpec(instance.name, par)
538         # Some specs must be multiple of 4
539         new_spec = _BuildSpecDict(par, imaxval + 4, imaxval + 4, imaxval + 4)
540         history.append((new_spec, True))
541         qa_cluster.TestClusterSetISpecs(new_spec)
542         qa_cluster.AssertClusterVerify(warnings=policyerror)
543         if iminval > 0:
544           # Some specs must be multiple of 4
545           if iminval >= 4:
546             upper = iminval - 4
547           else:
548             upper = iminval - 1
549           new_spec = _BuildSpecDict(par, 0, upper, upper)
550           history.append((new_spec, True))
551           qa_cluster.TestClusterSetISpecs(new_spec)
552           qa_cluster.AssertClusterVerify(warnings=policyerror)
553         qa_cluster.TestClusterSetISpecs(old_specs)
554         history.append((old_specs, False))
555       qa_instance.TestInstanceRemove(instance)
556     finally:
557       instance.Release()
558
559     # Now we replay the same policy changes, and we expect that the instance
560     # cannot be created for the cases where we had a policy violation above
561     for (change, failed) in history:
562       qa_cluster.TestClusterSetISpecs(change)
563       if failed:
564         qa_instance.TestInstanceAddWithPlainDisk([node], fail=True)
565       # Instance creation with no policy violation has been tested already
566   finally:
567     node.Release()
568
569
570 def RunInstanceTests():
571   """Create and exercise instances."""
572   instance_tests = [
573     ("instance-add-plain-disk", constants.DT_PLAIN,
574      qa_instance.TestInstanceAddWithPlainDisk, 1),
575     ("instance-add-drbd-disk", constants.DT_DRBD8,
576      qa_instance.TestInstanceAddWithDrbdDisk, 2),
577     ("instance-add-diskless", constants.DT_DISKLESS,
578      qa_instance.TestInstanceAddDiskless, 1),
579   ]
580
581   for (test_name, templ, create_fun, num_nodes) in instance_tests:
582     if (qa_config.TestEnabled(test_name) and
583         qa_config.IsTemplateSupported(templ)):
584       inodes = qa_config.AcquireManyNodes(num_nodes)
585       try:
586         instance = RunTest(create_fun, inodes)
587         try:
588           RunTestIf("cluster-epo", qa_cluster.TestClusterEpo)
589           RunDaemonTests(instance)
590           for node in inodes:
591             RunTestIf("haskell-confd", qa_node.TestNodeListDrbd, node)
592           if len(inodes) > 1:
593             RunTestIf("group-rwops", qa_group.TestAssignNodesIncludingSplit,
594                       constants.INITIAL_NODE_GROUP_NAME,
595                       inodes[0].primary, inodes[1].primary)
596           if qa_config.TestEnabled("instance-convert-disk"):
597             RunTest(qa_instance.TestInstanceShutdown, instance)
598             RunTest(qa_instance.TestInstanceConvertDiskToPlain,
599                     instance, inodes)
600             RunTest(qa_instance.TestInstanceStartup, instance)
601           RunCommonInstanceTests(instance)
602           RunGroupListTests()
603           RunExportImportTests(instance, inodes)
604           RunHardwareFailureTests(instance, inodes)
605           RunRepairDiskSizes()
606           RunTest(qa_instance.TestInstanceRemove, instance)
607         finally:
608           instance.Release()
609         del instance
610       finally:
611         qa_config.ReleaseManyNodes(inodes)
612       qa_cluster.AssertClusterVerify()
613
614
615 def RunQa():
616   """Main QA body.
617
618   """
619   rapi_user = "ganeti-qa"
620   rapi_secret = utils.GenerateSecret()
621
622   RunEnvTests()
623   SetupCluster(rapi_user, rapi_secret)
624
625   # Load RAPI certificate
626   qa_rapi.Setup(rapi_user, rapi_secret)
627
628   RunClusterTests()
629   RunOsTests()
630
631   RunTestIf("tags", qa_tags.TestClusterTags)
632
633   RunCommonNodeTests()
634   RunGroupListTests()
635   RunGroupRwTests()
636   RunNetworkTests()
637
638   # The master shouldn't be readded or put offline; "delay" needs a non-master
639   # node to test
640   pnode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
641   try:
642     RunTestIf("node-readd", qa_node.TestNodeReadd, pnode)
643     RunTestIf("node-modify", qa_node.TestNodeModify, pnode)
644     RunTestIf("delay", qa_cluster.TestDelay, pnode)
645   finally:
646     pnode.Release()
647
648   # Make sure the cluster is clean before running instance tests
649   qa_cluster.AssertClusterVerify()
650
651   pnode = qa_config.AcquireNode()
652   try:
653     RunTestIf("tags", qa_tags.TestNodeTags, pnode)
654
655     if qa_rapi.Enabled():
656       RunTest(qa_rapi.TestNode, pnode)
657
658       if qa_config.TestEnabled("instance-add-plain-disk"):
659         for use_client in [True, False]:
660           rapi_instance = RunTest(qa_rapi.TestRapiInstanceAdd, pnode,
661                                   use_client)
662           try:
663             if qa_config.TestEnabled("instance-plain-rapi-common-tests"):
664               RunCommonInstanceTests(rapi_instance)
665             RunTest(qa_rapi.TestRapiInstanceRemove, rapi_instance, use_client)
666           finally:
667             rapi_instance.Release()
668           del rapi_instance
669
670   finally:
671     pnode.Release()
672
673   config_list = [
674     ("default-instance-tests", lambda: None, lambda _: None),
675     ("exclusive-storage-instance-tests",
676      lambda: qa_cluster.TestSetExclStorCluster(True),
677      qa_cluster.TestSetExclStorCluster),
678   ]
679   for (conf_name, setup_conf_f, restore_conf_f) in config_list:
680     if qa_config.TestEnabled(conf_name):
681       oldconf = setup_conf_f()
682       RunInstanceTests()
683       restore_conf_f(oldconf)
684
685   pnode = qa_config.AcquireNode()
686   try:
687     if qa_config.TestEnabled(["instance-add-plain-disk", "instance-export"]):
688       for shutdown in [False, True]:
689         instance = RunTest(qa_instance.TestInstanceAddWithPlainDisk, [pnode])
690         try:
691           expnode = qa_config.AcquireNode(exclude=pnode)
692           try:
693             if shutdown:
694               # Stop instance before exporting and removing it
695               RunTest(qa_instance.TestInstanceShutdown, instance)
696             RunTest(qa_instance.TestInstanceExportWithRemove, instance, expnode)
697             RunTest(qa_instance.TestBackupList, expnode)
698           finally:
699             expnode.Release()
700         finally:
701           instance.Release()
702         del expnode
703         del instance
704       qa_cluster.AssertClusterVerify()
705
706   finally:
707     pnode.Release()
708
709   RunExclusiveStorageTests()
710   RunTestIf(["cluster-instance-policy", "instance-add-plain-disk"],
711             TestIPolicyPlainInstance)
712
713   # Test removing instance with offline drbd secondary
714   if qa_config.TestEnabled(["instance-remove-drbd-offline",
715                             "instance-add-drbd-disk"]):
716     # Make sure the master is not put offline
717     snode = qa_config.AcquireNode(exclude=qa_config.GetMasterNode())
718     try:
719       pnode = qa_config.AcquireNode(exclude=snode)
720       try:
721         instance = qa_instance.TestInstanceAddWithDrbdDisk([pnode, snode])
722         set_offline = lambda node: qa_node.MakeNodeOffline(node, "yes")
723         set_online = lambda node: qa_node.MakeNodeOffline(node, "no")
724         RunTest(qa_instance.TestRemoveInstanceOfflineNode, instance, snode,
725                 set_offline, set_online)
726       finally:
727         pnode.Release()
728     finally:
729       snode.Release()
730     qa_cluster.AssertClusterVerify()
731
732   RunTestIf("create-cluster", qa_node.TestNodeRemoveAll)
733
734   RunTestIf("cluster-destroy", qa_cluster.TestClusterDestroy)
735
736
737 @UsesRapiClient
738 def main():
739   """Main program.
740
741   """
742   parser = optparse.OptionParser(usage="%prog [options] <config-file>")
743   parser.add_option("--yes-do-it", dest="yes_do_it",
744                     action="store_true",
745                     help="Really execute the tests")
746   (opts, args) = parser.parse_args()
747
748   if len(args) == 1:
749     (config_file, ) = args
750   else:
751     parser.error("Wrong number of arguments.")
752
753   if not opts.yes_do_it:
754     print ("Executing this script irreversibly destroys any Ganeti\n"
755            "configuration on all nodes involved. If you really want\n"
756            "to start testing, supply the --yes-do-it option.")
757     sys.exit(1)
758
759   qa_config.Load(config_file)
760
761   primary = qa_config.GetMasterNode().primary
762   qa_utils.StartMultiplexer(primary)
763   print ("SSH command for primary node: %s" %
764          utils.ShellQuoteArgs(qa_utils.GetSSHCommand(primary, "")))
765   print ("SSH command for other nodes: %s" %
766          utils.ShellQuoteArgs(qa_utils.GetSSHCommand("NODE", "")))
767   try:
768     RunQa()
769   finally:
770     qa_utils.CloseMultiplexers()
771
772 if __name__ == "__main__":
773   main()