Simplify instance rename qa test
[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(rename_source, rename_target):
137   """gnt-instance rename"""
138   _CheckSsconfInstanceList(rename_source)
139   AssertCommand(["gnt-instance", "rename", rename_source, rename_target])
140   _CheckSsconfInstanceList(rename_target)
141
142
143 def TestInstanceFailover(instance):
144   """gnt-instance failover"""
145   cmd = ['gnt-instance', 'failover', '--force', instance['name']]
146   # failover ...
147   AssertCommand(cmd)
148   # ... and back
149   AssertCommand(cmd)
150
151
152 def TestInstanceMigrate(instance):
153   """gnt-instance migrate"""
154   cmd = ["gnt-instance", "migrate", "--force", instance["name"]]
155   # migrate ...
156   AssertCommand(cmd)
157   # ... and back
158   AssertCommand(cmd)
159
160
161 def TestInstanceInfo(instance):
162   """gnt-instance info"""
163   AssertCommand(["gnt-instance", "info", instance["name"]])
164
165
166 def TestInstanceModify(instance):
167   """gnt-instance modify"""
168   # Assume /sbin/init exists on all systems
169   test_kernel = "/sbin/init"
170   test_initrd = test_kernel
171
172   orig_memory = qa_config.get('mem')
173   #orig_bridge = qa_config.get("bridge", "xen-br0")
174   args = [
175     ["-B", "%s=128" % constants.BE_MEMORY],
176     ["-B", "%s=%s" % (constants.BE_MEMORY, orig_memory)],
177     ["-B", "%s=2" % constants.BE_VCPUS],
178     ["-B", "%s=1" % constants.BE_VCPUS],
179     ["-B", "%s=%s" % (constants.BE_VCPUS, constants.VALUE_DEFAULT)],
180
181     ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, test_kernel)],
182     ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, constants.VALUE_DEFAULT)],
183     ["-H", "%s=%s" % (constants.HV_INITRD_PATH, test_initrd)],
184     ["-H", "no_%s" % (constants.HV_INITRD_PATH, )],
185     ["-H", "%s=%s" % (constants.HV_INITRD_PATH, constants.VALUE_DEFAULT)],
186
187     # TODO: bridge tests
188     #["--bridge", "xen-br1"],
189     #["--bridge", orig_bridge],
190
191     # TODO: Do these tests only with xen-hvm
192     #["-H", "%s=acn" % constants.HV_BOOT_ORDER],
193     #["-H", "%s=%s" % (constants.HV_BOOT_ORDER, constants.VALUE_DEFAULT)],
194     ]
195   for alist in args:
196     AssertCommand(["gnt-instance", "modify"] + alist + [instance["name"]])
197
198   # check no-modify
199   AssertCommand(["gnt-instance", "modify", instance["name"]], fail=True)
200
201
202 def TestInstanceConvertDisk(instance, snode):
203   """gnt-instance modify -t"""
204   name = instance["name"]
205   AssertCommand(["gnt-instance", "modify", "-t", "plain", name])
206   AssertCommand(["gnt-instance", "modify", "-t", "drbd",
207                  "-n", snode["primary"], name])
208
209
210 def TestInstanceList():
211   """gnt-instance list"""
212   AssertCommand(["gnt-instance", "list"])
213
214
215 def TestInstanceConsole(instance):
216   """gnt-instance console"""
217   AssertCommand(["gnt-instance", "console", "--show-cmd", instance["name"]])
218
219
220 def TestReplaceDisks(instance, pnode, snode, othernode):
221   """gnt-instance replace-disks"""
222   def buildcmd(args):
223     cmd = ['gnt-instance', 'replace-disks']
224     cmd.extend(args)
225     cmd.append(instance["name"])
226     return cmd
227
228   for data in [
229     ["-p"],
230     ["-s"],
231     ["--new-secondary=%s" % othernode["primary"]],
232     # and restore
233     ["--new-secondary=%s" % snode["primary"]],
234     ]:
235     AssertCommand(buildcmd(data))
236
237
238 def TestInstanceExport(instance, node):
239   """gnt-backup export -n ..."""
240   name = instance["name"]
241   AssertCommand(["gnt-backup", "export", "-n", node["primary"], name])
242   return qa_utils.ResolveInstanceName(name)
243
244
245 def TestInstanceExportWithRemove(instance, node):
246   """gnt-backup export --remove-instance"""
247   AssertCommand(["gnt-backup", "export", "-n", node["primary"],
248                  "--remove-instance", instance["name"]])
249
250
251 def TestInstanceExportNoTarget(instance):
252   """gnt-backup export (without target node, should fail)"""
253   AssertCommand(["gnt-backup", "export", instance["name"]], fail=True)
254
255
256 def TestInstanceImport(node, newinst, expnode, name):
257   """gnt-backup import"""
258   cmd = (['gnt-backup', 'import',
259           '--disk-template=plain',
260           '--no-ip-check',
261           '--net', '0:mac=generate',
262           '--src-node=%s' % expnode['primary'],
263           '--src-dir=%s/%s' % (constants.EXPORT_DIR, name),
264           '--node=%s' % node['primary']] +
265          _GetGenericAddParameters())
266   cmd.append(newinst['name'])
267   AssertCommand(cmd)
268
269
270 def TestBackupList(expnode):
271   """gnt-backup list"""
272   AssertCommand(["gnt-backup", "list", "--node=%s" % expnode["primary"]])
273
274
275 def _TestInstanceDiskFailure(instance, node, node2, onmaster):
276   """Testing disk failure."""
277   master = qa_config.GetMasterNode()
278   sq = utils.ShellQuoteArgs
279
280   instance_full = qa_utils.ResolveInstanceName(instance["name"])
281   node_full = qa_utils.ResolveNodeName(node)
282   node2_full = qa_utils.ResolveNodeName(node2)
283
284   print qa_utils.FormatInfo("Getting physical disk names")
285   cmd = ['gnt-node', 'volumes', '--separator=|', '--no-headers',
286          '--output=node,phys,instance',
287          node['primary'], node2['primary']]
288   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
289
290   # Get physical disk names
291   re_disk = re.compile(r'^/dev/([a-z]+)\d+$')
292   node2disk = {}
293   for line in output.splitlines():
294     (node_name, phys, inst) = line.split('|')
295     if inst == instance_full:
296       if node_name not in node2disk:
297         node2disk[node_name] = []
298
299       m = re_disk.match(phys)
300       if not m:
301         raise qa_error.Error("Unknown disk name format: %s" % phys)
302
303       name = m.group(1)
304       if name not in node2disk[node_name]:
305         node2disk[node_name].append(name)
306
307   if [node2_full, node_full][int(onmaster)] not in node2disk:
308     raise qa_error.Error("Couldn't find physical disks used on"
309                          " %s node" % ["secondary", "master"][int(onmaster)])
310
311   print qa_utils.FormatInfo("Checking whether nodes have ability to stop"
312                             " disks")
313   for node_name, disks in node2disk.iteritems():
314     cmds = []
315     for disk in disks:
316       cmds.append(sq(["test", "-f", _GetDiskStatePath(disk)]))
317     AssertCommand(" && ".join(cmds), node=node_name)
318
319   print qa_utils.FormatInfo("Getting device paths")
320   cmd = ['gnt-instance', 'activate-disks', instance['name']]
321   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
322   devpath = []
323   for line in output.splitlines():
324     (_, _, tmpdevpath) = line.split(':')
325     devpath.append(tmpdevpath)
326   print devpath
327
328   print qa_utils.FormatInfo("Getting drbd device paths")
329   cmd = ['gnt-instance', 'info', instance['name']]
330   output = qa_utils.GetCommandOutput(master['primary'], sq(cmd))
331   pattern = (r'\s+-\s+sd[a-z]+,\s+type:\s+drbd8?,\s+.*$'
332              r'\s+primary:\s+(/dev/drbd\d+)\s+')
333   drbddevs = re.findall(pattern, output, re.M)
334   print drbddevs
335
336   halted_disks = []
337   try:
338     print qa_utils.FormatInfo("Deactivating disks")
339     cmds = []
340     for name in node2disk[[node2_full, node_full][int(onmaster)]]:
341       halted_disks.append(name)
342       cmds.append(sq(["echo", "offline"]) + " >%s" % _GetDiskStatePath(name))
343     AssertCommand(" && ".join(cmds), node=[node2, node][int(onmaster)])
344
345     print qa_utils.FormatInfo("Write to disks and give some time to notice"
346                               " to notice the problem")
347     cmds = []
348     for disk in devpath:
349       cmds.append(sq(["dd", "count=1", "bs=512", "conv=notrunc",
350                       "if=%s" % disk, "of=%s" % disk]))
351     for _ in (0, 1, 2):
352       AssertCommand(" && ".join(cmds), node=node)
353       time.sleep(3)
354
355     print qa_utils.FormatInfo("Debugging info")
356     for name in drbddevs:
357       AssertCommand(["drbdsetup", name, "show"], node=node)
358
359     AssertCommand(["gnt-instance", "info", instance["name"]])
360
361   finally:
362     print qa_utils.FormatInfo("Activating disks again")
363     cmds = []
364     for name in halted_disks:
365       cmds.append(sq(["echo", "running"]) + " >%s" % _GetDiskStatePath(name))
366     AssertCommand("; ".join(cmds), node=[node2, node][int(onmaster)])
367
368   if onmaster:
369     for name in drbddevs:
370       AssertCommand(["drbdsetup", name, "detach"], node=node)
371   else:
372     for name in drbddevs:
373       AssertCommand(["drbdsetup", name, "disconnect"], node=node2)
374
375   # TODO
376   #AssertCommand(["vgs"], [node2, node][int(onmaster)])
377
378   print qa_utils.FormatInfo("Making sure disks are up again")
379   AssertCommand(["gnt-instance", "replace-disks", instance["name"]])
380
381   print qa_utils.FormatInfo("Restarting instance")
382   AssertCommand(["gnt-instance", "shutdown", instance["name"]])
383   AssertCommand(["gnt-instance", "startup", instance["name"]])
384
385   AssertCommand(["gnt-cluster", "verify"])
386
387
388 def TestInstanceMasterDiskFailure(instance, node, node2):
389   """Testing disk failure on master node."""
390   print qa_utils.FormatError("Disk failure on primary node cannot be"
391                              " tested due to potential crashes.")
392   # The following can cause crashes, thus it's disabled until fixed
393   #return _TestInstanceDiskFailure(instance, node, node2, True)
394
395
396 def TestInstanceSecondaryDiskFailure(instance, node, node2):
397   """Testing disk failure on secondary node."""
398   return _TestInstanceDiskFailure(instance, node, node2, False)