Simplify QA commands
[ganeti-local] / qa / qa_instance.py
1 #
2 #
3
4 # Copyright (C) 2007 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 """Instance related QA tests.
23
24 """
25
26 import re
27 import time
28
29 from ganeti import utils
30 from ganeti import constants
31
32 import qa_config
33 import qa_utils
34 import qa_error
35
36 from qa_utils import AssertIn, AssertCommand
37
38
39 def _GetDiskStatePath(disk):
40   return "/sys/block/%s/device/state" % disk
41
42
43 def _GetGenericAddParameters():
44   params = ['-B', '%s=%s' % (constants.BE_MEMORY, qa_config.get('mem'))]
45   for idx, size in enumerate(qa_config.get('disk')):
46     params.extend(["--disk", "%s:size=%s" % (idx, size)])
47   return params
48
49
50 def _DiskTest(node, disk_template):
51   instance = qa_config.AcquireInstance()
52   try:
53     cmd = (['gnt-instance', 'add',
54             '--os-type=%s' % qa_config.get('os'),
55             '--disk-template=%s' % disk_template,
56             '--node=%s' % node] +
57            _GetGenericAddParameters())
58     cmd.append(instance['name'])
59
60     AssertCommand(cmd)
61
62     _CheckSsconfInstanceList(instance["name"])
63
64     return instance
65   except:
66     qa_config.ReleaseInstance(instance)
67     raise
68
69
70 def TestInstanceAddWithPlainDisk(node):
71   """gnt-instance add -t plain"""
72   return _DiskTest(node['primary'], 'plain')
73
74
75 def TestInstanceAddWithDrbdDisk(node, node2):
76   """gnt-instance add -t drbd"""
77   return _DiskTest("%s:%s" % (node['primary'], node2['primary']),
78                    'drbd')
79
80
81 def TestInstanceRemove(instance):
82   """gnt-instance remove"""
83   AssertCommand(["gnt-instance", "remove", "-f", instance["name"]])
84
85   qa_config.ReleaseInstance(instance)
86
87
88 def TestInstanceStartup(instance):
89   """gnt-instance startup"""
90   AssertCommand(["gnt-instance", "startup", instance["name"]])
91
92
93 def TestInstanceShutdown(instance):
94   """gnt-instance shutdown"""
95   AssertCommand(["gnt-instance", "shutdown", instance["name"]])
96
97
98 def TestInstanceReboot(instance):
99   """gnt-instance reboot"""
100   options = qa_config.get('options', {})
101   reboot_types = options.get("reboot-types", constants.REBOOT_TYPES)
102   name = instance["name"]
103   for rtype in reboot_types:
104     AssertCommand(["gnt-instance", "reboot", "--type=%s" % rtype, name])
105
106
107 def TestInstanceReinstall(instance):
108   """gnt-instance reinstall"""
109   AssertCommand(["gnt-instance", "reinstall", "-f", instance["name"]])
110
111
112 def _ReadSsconfInstanceList():
113   """Reads ssconf_instance_list from the master node.
114
115   """
116   master = qa_config.GetMasterNode()
117
118   cmd = ["cat", utils.PathJoin(constants.DATA_DIR,
119                                "ssconf_%s" % constants.SS_INSTANCE_LIST)]
120
121   return qa_utils.GetCommandOutput(master["primary"],
122                                    utils.ShellQuoteArgs(cmd)).splitlines()
123
124
125 def _CheckSsconfInstanceList(instance):
126   """Checks if a certain instance is in the ssconf instance list.
127
128   @type instance: string
129   @param instance: Instance name
130
131   """
132   AssertIn(qa_utils.ResolveInstanceName(instance),
133            _ReadSsconfInstanceList())
134
135
136 def TestInstanceRename(instance, rename_target):
137   """gnt-instance rename"""
138   rename_source = instance['name']
139
140   for name1, name2 in [(rename_source, rename_target),
141                        (rename_target, rename_source)]:
142     _CheckSsconfInstanceList(name1)
143     AssertCommand(["gnt-instance", "rename", name1, name2])
144     _CheckSsconfInstanceList(name2)
145
146
147 def TestInstanceFailover(instance):
148   """gnt-instance failover"""
149   cmd = ['gnt-instance', 'failover', '--force', instance['name']]
150   # failover ...
151   AssertCommand(cmd)
152   # ... and back
153   AssertCommand(cmd)
154
155
156 def TestInstanceMigrate(instance):
157   """gnt-instance migrate"""
158   cmd = ["gnt-instance", "migrate", "--force", instance["name"]]
159   # migrate ...
160   AssertCommand(cmd)
161   # ... and back
162   AssertCommand(cmd)
163
164
165 def TestInstanceInfo(instance):
166   """gnt-instance info"""
167   AssertCommand(["gnt-instance", "info", instance["name"]])
168
169
170 def TestInstanceModify(instance):
171   """gnt-instance modify"""
172   # Assume /sbin/init exists on all systems
173   test_kernel = "/sbin/init"
174   test_initrd = test_kernel
175
176   orig_memory = qa_config.get('mem')
177   #orig_bridge = qa_config.get("bridge", "xen-br0")
178   args = [
179     ["-B", "%s=128" % constants.BE_MEMORY],
180     ["-B", "%s=%s" % (constants.BE_MEMORY, orig_memory)],
181     ["-B", "%s=2" % constants.BE_VCPUS],
182     ["-B", "%s=1" % constants.BE_VCPUS],
183     ["-B", "%s=%s" % (constants.BE_VCPUS, constants.VALUE_DEFAULT)],
184
185     ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, test_kernel)],
186     ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, constants.VALUE_DEFAULT)],
187     ["-H", "%s=%s" % (constants.HV_INITRD_PATH, test_initrd)],
188     ["-H", "no_%s" % (constants.HV_INITRD_PATH, )],
189     ["-H", "%s=%s" % (constants.HV_INITRD_PATH, constants.VALUE_DEFAULT)],
190
191     # TODO: bridge tests
192     #["--bridge", "xen-br1"],
193     #["--bridge", orig_bridge],
194
195     # TODO: Do these tests only with xen-hvm
196     #["-H", "%s=acn" % constants.HV_BOOT_ORDER],
197     #["-H", "%s=%s" % (constants.HV_BOOT_ORDER, constants.VALUE_DEFAULT)],
198     ]
199   for alist in args:
200     AssertCommand(["gnt-instance", "modify"] + alist + [instance["name"]])
201
202   # check no-modify
203   AssertCommand(["gnt-instance", "modify", instance["name"]], fail=True)
204
205
206 def TestInstanceConvertDisk(instance, snode):
207   """gnt-instance modify -t"""
208   name = instance["name"]
209   AssertCommand(["gnt-instance", "modify", "-t", "plain", name])
210   AssertCommand(["gnt-instance", "modify", "-t", "drbd",
211                  "-n", snode["primary"], name])
212
213
214 def TestInstanceList():
215   """gnt-instance list"""
216   AssertCommand(["gnt-instance", "list"])
217
218
219 def TestInstanceConsole(instance):
220   """gnt-instance console"""
221   AssertCommand(["gnt-instance", "console", "--show-cmd", instance["name"]])
222
223
224 def TestReplaceDisks(instance, pnode, snode, othernode):
225   """gnt-instance replace-disks"""
226   def buildcmd(args):
227     cmd = ['gnt-instance', 'replace-disks']
228     cmd.extend(args)
229     cmd.append(instance["name"])
230     return cmd
231
232   for data in [
233     ["-p"],
234     ["-s"],
235     ["--new-secondary=%s" % othernode["primary"]],
236     # and restore
237     ["--new-secondary=%s" % snode["primary"]],
238     ]:
239     AssertCommand(buildcmd(data))
240
241
242 def TestInstanceExport(instance, node):
243   """gnt-backup export -n ..."""
244   name = instance["name"]
245   AssertCommand(["gnt-backup", "export", "-n", node["primary"], name])
246   return qa_utils.ResolveInstanceName(name)
247
248
249 def TestInstanceExportWithRemove(instance, node):
250   """gnt-backup export --remove-instance"""
251   AssertCommand(["gnt-backup", "export", "-n", node["primary"],
252                  "--remove-instance", instance["name"]])
253
254
255 def TestInstanceExportNoTarget(instance):
256   """gnt-backup export (without target node, should fail)"""
257   AssertCommand(["gnt-backup", "export", instance["name"]], fail=True)
258
259
260 def TestInstanceImport(node, newinst, expnode, name):
261   """gnt-backup import"""
262   cmd = (['gnt-backup', 'import',
263           '--disk-template=plain',
264           '--no-ip-check',
265           '--net', '0:mac=generate',
266           '--src-node=%s' % expnode['primary'],
267           '--src-dir=%s/%s' % (constants.EXPORT_DIR, name),
268           '--node=%s' % node['primary']] +
269          _GetGenericAddParameters())
270   cmd.append(newinst['name'])
271   AssertCommand(cmd)
272
273
274 def TestBackupList(expnode):
275   """gnt-backup list"""
276   AssertCommand(["gnt-backup", "list", "--node=%s" % expnode["primary"]])
277
278
279 def _TestInstanceDiskFailure(instance, node, node2, onmaster):
280   """Testing disk failure."""
281   master = qa_config.GetMasterNode()
282   sq = utils.ShellQuoteArgs
283
284   instance_full = qa_utils.ResolveInstanceName(instance["name"])
285   node_full = qa_utils.ResolveNodeName(node)
286   node2_full = qa_utils.ResolveNodeName(node2)
287
288   print qa_utils.FormatInfo("Getting physical disk names")
289   cmd = ['gnt-node', 'volumes', '--separator=|', '--no-headers',
290          '--output=node,phys,instance',
291          node['primary'], node2['primary']]
292   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
293
294   # Get physical disk names
295   re_disk = re.compile(r'^/dev/([a-z]+)\d+$')
296   node2disk = {}
297   for line in output.splitlines():
298     (node_name, phys, inst) = line.split('|')
299     if inst == instance_full:
300       if node_name not in node2disk:
301         node2disk[node_name] = []
302
303       m = re_disk.match(phys)
304       if not m:
305         raise qa_error.Error("Unknown disk name format: %s" % phys)
306
307       name = m.group(1)
308       if name not in node2disk[node_name]:
309         node2disk[node_name].append(name)
310
311   if [node2_full, node_full][int(onmaster)] not in node2disk:
312     raise qa_error.Error("Couldn't find physical disks used on"
313                          " %s node" % ["secondary", "master"][int(onmaster)])
314
315   print qa_utils.FormatInfo("Checking whether nodes have ability to stop"
316                             " disks")
317   for node_name, disks in node2disk.iteritems():
318     cmds = []
319     for disk in disks:
320       cmds.append(sq(["test", "-f", _GetDiskStatePath(disk)]))
321     AssertCommand(" && ".join(cmds), node=node_name)
322
323   print qa_utils.FormatInfo("Getting device paths")
324   cmd = ['gnt-instance', 'activate-disks', instance['name']]
325   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
326   devpath = []
327   for line in output.splitlines():
328     (_, _, tmpdevpath) = line.split(':')
329     devpath.append(tmpdevpath)
330   print devpath
331
332   print qa_utils.FormatInfo("Getting drbd device paths")
333   cmd = ['gnt-instance', 'info', instance['name']]
334   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
335   pattern = (r'\s+-\s+sd[a-z]+,\s+type:\s+drbd8?,\s+.*$'
336              r'\s+primary:\s+(/dev/drbd\d+)\s+')
337   drbddevs = re.findall(pattern, output, re.M)
338   print drbddevs
339
340   halted_disks = []
341   try:
342     print qa_utils.FormatInfo("Deactivating disks")
343     cmds = []
344     for name in node2disk[[node2_full, node_full][int(onmaster)]]:
345       halted_disks.append(name)
346       cmds.append(sq(["echo", "offline"]) + " >%s" % _GetDiskStatePath(name))
347     AssertCommand(" && ".join(cmds), node=[node2, node][int(onmaster)])
348
349     print qa_utils.FormatInfo("Write to disks and give some time to notice"
350                               " to notice the problem")
351     cmds = []
352     for disk in devpath:
353       cmds.append(sq(["dd", "count=1", "bs=512", "conv=notrunc",
354                       "if=%s" % disk, "of=%s" % disk]))
355     for _ in (0, 1, 2):
356       AssertCommand(" && ".join(cmds), node=node)
357       time.sleep(3)
358
359     print qa_utils.FormatInfo("Debugging info")
360     for name in drbddevs:
361       AssertCommand(["drbdsetup", name, "show"], node=node)
362
363     AssertCommand(["gnt-instance", "info", instance["name"]])
364
365   finally:
366     print qa_utils.FormatInfo("Activating disks again")
367     cmds = []
368     for name in halted_disks:
369       cmds.append(sq(["echo", "running"]) + " >%s" % _GetDiskStatePath(name))
370     AssertCommand("; ".join(cmds), node=[node2, node][int(onmaster)])
371
372   if onmaster:
373     for name in drbddevs:
374       AssertCommand(["drbdsetup", name, "detach"], node=node)
375   else:
376     for name in drbddevs:
377       AssertCommand(["drbdsetup", name, "disconnect"], node=node2)
378
379   # TODO
380   #AssertCommand(["vgs"], [node2, node][int(onmaster)])
381
382   print qa_utils.FormatInfo("Making sure disks are up again")
383   AssertCommand(["gnt-instance", "replace-disks", instance["name"]])
384
385   print qa_utils.FormatInfo("Restarting instance")
386   AssertCommand(["gnt-instance", "shutdown", instance["name"]])
387   AssertCommand(["gnt-instance", "startup", instance["name"]])
388
389   AssertCommand(["gnt-cluster", "verify"])
390
391
392 def TestInstanceMasterDiskFailure(instance, node, node2):
393   """Testing disk failure on master node."""
394   print qa_utils.FormatError("Disk failure on primary node cannot be"
395                              " tested due to potential crashes.")
396   # The following can cause crashes, thus it's disabled until fixed
397   #return _TestInstanceDiskFailure(instance, node, node2, True)
398
399
400 def TestInstanceSecondaryDiskFailure(instance, node, node2):
401   """Testing disk failure on secondary node."""
402   return _TestInstanceDiskFailure(instance, node, node2, False)