qa_instance.py 56.5 KB
Newer Older
1 2 3
#
#

4
# Copyright (C) 2007, 2011, 2012, 2013 Google Inc.
Klaus Aehlig's avatar
Klaus Aehlig committed
5
# All rights reserved.
6
#
Klaus Aehlig's avatar
Klaus Aehlig committed
7 8 9
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
10
#
Klaus Aehlig's avatar
Klaus Aehlig committed
11 12
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
13
#
Klaus Aehlig's avatar
Klaus Aehlig committed
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
# IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 30 31 32 33 34


"""Instance related QA tests.

"""

35
import os
36
import re
Jose A. Lopes's avatar
Jose A. Lopes committed
37
import time
38

39
from ganeti import utils
Michael Hanselmann's avatar
Michael Hanselmann committed
40
from ganeti import constants
41
from ganeti import pathutils
42 43
from ganeti import query
from ganeti.netutils import IP4Address
44 45

import qa_config
46
import qa_daemon
Michael Hanselmann's avatar
Michael Hanselmann committed
47
import qa_utils
48 49
import qa_error

50
from qa_filters import stdout_of
51
from qa_utils import AssertCommand, AssertEqual, AssertIn
52
from qa_utils import InstanceCheck, INST_DOWN, INST_UP, FIRST_ARG, RETURN_VALUE
53 54 55 56 57
from qa_instance_utils import CheckSsconfInstanceList, \
                              CreateInstanceDrbd8, \
                              CreateInstanceByDiskTemplate, \
                              CreateInstanceByDiskTemplateOneNode, \
                              GetGenericAddParameters
58

59 60 61

def _GetDiskStatePath(disk):
  return "/sys/block/%s/device/state" % disk
62 63


64
def GetInstanceInfo(instance):
65
  """Return information about the actual state of an instance.
66

67 68
  @type instance: string
  @param instance: the instance name
69
  @return: a dictionary with the following keys:
70 71
      - "nodes": instance nodes, a list of strings
      - "volumes": instance volume IDs, a list of strings
72 73 74
      - "drbd-minors": DRBD minors used by the instance, a dictionary where
        keys are nodes, and values are lists of integers (or an empty
        dictionary for non-DRBD instances)
75 76
      - "disk-template": instance disk template
      - "storage-type": storage type associated with the instance disk template
77 78 79 80 81 82 83 84 85

  """
  node_elem = r"([^,()]+)(?:\s+\([^)]+\))?"
  # re_nodelist matches a list of nodes returned by gnt-instance info, e.g.:
  #  node1.fqdn
  #  node2.fqdn,node3.fqdn
  #  node4.fqdn (group mygroup, group UUID 01234567-abcd-0123-4567-0123456789ab)
  # FIXME This works with no more than 2 secondaries
  re_nodelist = re.compile(node_elem + "(?:," + node_elem + ")?$")
86 87

  info = qa_utils.GetObjectInfo(["gnt-instance", "info", instance])[0]
88
  nodes = []
89 90 91 92 93 94 95 96 97 98 99 100 101
  for nodeinfo in info["Nodes"]:
    if "primary" in nodeinfo:
      nodes.append(nodeinfo["primary"])
    elif "secondaries" in nodeinfo:
      nodestr = nodeinfo["secondaries"]
      if nodestr:
        m = re_nodelist.match(nodestr)
        if m:
          nodes.extend(filter(None, m.groups()))
        else:
          nodes.append(nodestr)

  re_drbdnode = re.compile(r"^([^\s,]+),\s+minor=([0-9]+)$")
102
  vols = []
103
  drbd_min = {}
104
  dtypes = []
105 106
  for (count, diskinfo) in enumerate(info["Disks"]):
    (dtype, _) = diskinfo["disk/%s" % count].split(",", 1)
107
    dtypes.append(dtype)
108
    if dtype == constants.DT_DRBD8:
109 110 111 112 113 114 115 116 117 118
      for child in diskinfo["child devices"]:
        vols.append(child["logical_id"])
      for key in ["nodeA", "nodeB"]:
        m = re_drbdnode.match(diskinfo[key])
        if not m:
          raise qa_error.Error("Cannot parse DRBD info: %s" % diskinfo[key])
        node = m.group(1)
        minor = int(m.group(2))
        minorlist = drbd_min.setdefault(node, [])
        minorlist.append(minor)
119
    elif dtype == constants.DT_PLAIN:
120
      vols.append(diskinfo["logical_id"])
121

122 123 124 125
  # TODO remove and modify calling sites
  disk_template = utils.GetDiskTemplateString(dtypes)
  storage_type = constants.MAP_DISK_TEMPLATE_STORAGE_TYPE[disk_template]

126
  assert nodes
127
  assert len(nodes) < 2 or vols
128 129 130 131
  return {
    "nodes": nodes,
    "volumes": vols,
    "drbd-minors": drbd_min,
132 133
    "disk-template": disk_template,
    "storage-type": storage_type,
134
    }
135 136


137 138
def _DestroyInstanceDisks(instance):
  """Remove all the backend disks of an instance.
139 140 141 142 143 144 145

  This is used to simulate HW errors (dead nodes, broken disks...); the
  configuration of the instance is not affected.
  @type instance: dictionary
  @param instance: the instance

  """
146
  info = GetInstanceInfo(instance.name)
147 148 149 150 151
  # FIXME: destruction/removal should be part of the disk class
  if info["storage-type"] == constants.ST_LVM_VG:
    vols = info["volumes"]
    for node in info["nodes"]:
      AssertCommand(["lvremove", "-f"] + vols, node=node)
152
  elif info["storage-type"] in (constants.ST_FILE, constants.ST_SHARED_FILE):
153
    # Note that this works for both file and sharedfile, and this is intended.
154 155 156
    storage_dir = qa_config.get("file-storage-dir",
                                pathutils.DEFAULT_FILE_STORAGE_DIR)
    idir = os.path.join(storage_dir, instance.name)
157
    for node in info["nodes"]:
158
      AssertCommand(["rm", "-rf", idir], node=node)
159 160
  elif info["storage-type"] == constants.ST_DISKLESS:
    pass
161 162


163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
def _GetInstanceFields(instance, fields):
  """Get the value of one or more fields of an instance.

  @type instance: string
  @param instance: instance name

  @type field: list of string
  @param field: name of the fields

  @rtype: list of string
  @return: value of the fields

  """
  master = qa_config.GetMasterNode()
  infocmd = utils.ShellQuoteArgs(["gnt-instance", "list", "--no-headers",
                                  "--separator=:", "--units", "m", "-o",
                                  ",".join(fields), instance])
  return tuple(qa_utils.GetCommandOutput(master.primary, infocmd)
               .strip()
               .split(":"))


185 186
def _GetInstanceField(instance, field):
  """Get the value of a field of an instance.
187 188 189 190 191

  @type instance: string
  @param instance: Instance name
  @type field: string
  @param field: Name of the field
192
  @rtype: string
193 194

  """
195
  return _GetInstanceFields(instance, [field])[0]
196 197 198 199 200 201 202 203 204 205 206 207 208


def _GetBoolInstanceField(instance, field):
  """Get the Boolean value of a field of an instance.

  @type instance: string
  @param instance: Instance name
  @type field: string
  @param field: Name of the field
  @rtype: bool

  """
  info_out = _GetInstanceField(instance, field)
209 210 211 212 213 214 215 216 217
  if info_out == "Y":
    return True
  elif info_out == "N":
    return False
  else:
    raise qa_error.Error("Field %s of instance %s has a non-Boolean value:"
                         " %s" % (field, instance, info_out))


218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
def _GetNumInstanceField(instance, field):
  """Get a numeric value of a field of an instance.

  @type instance: string
  @param instance: Instance name
  @type field: string
  @param field: Name of the field
  @rtype: int or float

  """
  info_out = _GetInstanceField(instance, field)
  try:
    ret = int(info_out)
  except ValueError:
    try:
      ret = float(info_out)
    except ValueError:
      raise qa_error.Error("Field %s of instance %s has a non-numeric value:"
                           " %s" % (field, instance, info_out))
  return ret


def GetInstanceSpec(instance, spec):
  """Return the current spec for the given parameter.

  @type instance: string
  @param instance: Instance name
  @type spec: string
246
  @param spec: one of the supported parameters: "memory-size", "cpu-count",
247 248 249 250 251 252 253
      "disk-count", "disk-size", "nic-count"
  @rtype: tuple
  @return: (minspec, maxspec); minspec and maxspec can be different only for
      memory and disk size

  """
  specmap = {
254
    "memory-size": ["be/minmem", "be/maxmem"],
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
    "cpu-count": ["vcpus"],
    "disk-count": ["disk.count"],
    "disk-size": ["disk.size/ "],
    "nic-count": ["nic.count"],
    }
  # For disks, first we need the number of disks
  if spec == "disk-size":
    (numdisk, _) = GetInstanceSpec(instance, "disk-count")
    fields = ["disk.size/%s" % k for k in range(0, numdisk)]
  else:
    assert spec in specmap, "%s not in %s" % (spec, specmap)
    fields = specmap[spec]
  values = [_GetNumInstanceField(instance, f) for f in fields]
  return (min(values), max(values))


271
def IsFailoverSupported(instance):
272
  return instance.disk_template in constants.DTS_MIRRORED
273 274 275


def IsMigrationSupported(instance):
276
  return instance.disk_template in constants.DTS_MIRRORED
277 278 279


def IsDiskReplacingSupported(instance):
280
  return instance.disk_template == constants.DT_DRBD8
281 282


283
def IsDiskSupported(instance):
284
  return instance.disk_template != constants.DT_DISKLESS
285 286


287
def TestInstanceAddWithPlainDisk(nodes, fail=False):
288
  """gnt-instance add -t plain"""
289
  if constants.DT_PLAIN in qa_config.GetEnabledDiskTemplates():
290
    instance = CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_PLAIN,
291 292 293 294
                                                    fail=fail)
    if not fail:
      qa_utils.RunInstanceCheck(instance, True)
    return instance
295 296


297
@InstanceCheck(None, INST_UP, RETURN_VALUE)
298
def TestInstanceAddWithDrbdDisk(nodes):
299
  """gnt-instance add -t drbd"""
300
  if constants.DT_DRBD8 in qa_config.GetEnabledDiskTemplates():
301
    return CreateInstanceDrbd8(nodes)
302 303


304 305 306 307
@InstanceCheck(None, INST_UP, RETURN_VALUE)
def TestInstanceAddFile(nodes):
  """gnt-instance add -t file"""
  assert len(nodes) == 1
308
  if constants.DT_FILE in qa_config.GetEnabledDiskTemplates():
309
    return CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_FILE)
310 311


312 313 314 315 316 317 318 319
@InstanceCheck(None, INST_UP, RETURN_VALUE)
def TestInstanceAddSharedFile(nodes):
  """gnt-instance add -t sharedfile"""
  assert len(nodes) == 1
  if constants.DT_SHARED_FILE in qa_config.GetEnabledDiskTemplates():
    return CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_SHARED_FILE)


320 321 322 323
@InstanceCheck(None, INST_UP, RETURN_VALUE)
def TestInstanceAddDiskless(nodes):
  """gnt-instance add -t diskless"""
  assert len(nodes) == 1
324
  if constants.DT_DISKLESS in qa_config.GetEnabledDiskTemplates():
325
    return CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_DISKLESS)
326 327


328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
@InstanceCheck(None, INST_UP, RETURN_VALUE)
def TestInstanceAddRADOSBlockDevice(nodes):
  """gnt-instance add -t rbd"""
  assert len(nodes) == 1
  if constants.DT_RBD in qa_config.GetEnabledDiskTemplates():
    return CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_RBD)


@InstanceCheck(None, INST_UP, RETURN_VALUE)
def TestInstanceAddGluster(nodes):
  """gnt-instance add -t gluster"""
  assert len(nodes) == 1
  if constants.DT_GLUSTER in qa_config.GetEnabledDiskTemplates():
    return CreateInstanceByDiskTemplateOneNode(nodes, constants.DT_GLUSTER)


344
@InstanceCheck(None, INST_DOWN, FIRST_ARG)
345 346
def TestInstanceRemove(instance):
  """gnt-instance remove"""
347
  AssertCommand(["gnt-instance", "remove", "-f", instance.name])
348 349


350
@InstanceCheck(INST_DOWN, INST_UP, FIRST_ARG)
351 352
def TestInstanceStartup(instance):
  """gnt-instance startup"""
353
  AssertCommand(["gnt-instance", "startup", instance.name])
354 355


356
@InstanceCheck(INST_UP, INST_DOWN, FIRST_ARG)
357 358
def TestInstanceShutdown(instance):
  """gnt-instance shutdown"""
359
  AssertCommand(["gnt-instance", "shutdown", instance.name])
360 361


362
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
363 364
def TestInstanceReboot(instance):
  """gnt-instance reboot"""
Iustin Pop's avatar
Iustin Pop committed
365
  options = qa_config.get("options", {})
366
  reboot_types = options.get("reboot-types", constants.REBOOT_TYPES)
367
  name = instance.name
368
  for rtype in reboot_types:
Iustin Pop's avatar
Iustin Pop committed
369
    AssertCommand(["gnt-instance", "reboot", "--type=%s" % rtype, name])
370

371
  AssertCommand(["gnt-instance", "shutdown", name])
372
  qa_utils.RunInstanceCheck(instance, False)
373 374 375
  AssertCommand(["gnt-instance", "reboot", name])

  master = qa_config.GetMasterNode()
376
  cmd = ["gnt-instance", "list", "--no-headers", "-o", "status", name]
377
  result_output = qa_utils.GetCommandOutput(master.primary,
378 379 380
                                            utils.ShellQuoteArgs(cmd))
  AssertEqual(result_output.strip(), constants.INSTST_RUNNING)

381

382
@InstanceCheck(INST_DOWN, INST_DOWN, FIRST_ARG)
Michael Hanselmann's avatar
Michael Hanselmann committed
383 384
def TestInstanceReinstall(instance):
  """gnt-instance reinstall"""
385 386 387 388
  if instance.disk_template == constants.DT_DISKLESS:
    print qa_utils.FormatInfo("Test not supported for diskless instances")
    return

389
  qa_storage = qa_config.get("qa-storage")
Jose A. Lopes's avatar
Jose A. Lopes committed
390

391 392 393 394 395 396 397 398 399
  if qa_storage is None:
    print qa_utils.FormatInfo("Test not supported because the additional QA"
                              " storage is not available")
  else:
    # Reinstall with OS image from QA storage
    url = "%s/busybox.img" % qa_storage
    AssertCommand(["gnt-instance", "reinstall",
                   "--os-parameters", "os-image=" + url,
                   "-f", instance.name])
Jose A. Lopes's avatar
Jose A. Lopes committed
400

401 402
    # Reinstall with OS image as local file on the node
    pnode = _GetInstanceField(instance.name, "pnode")
Jose A. Lopes's avatar
Jose A. Lopes committed
403

404 405 406
    cmd = ("wget -O busybox.img %s &> /dev/null &&"
           " echo $(pwd)/busybox.img") % url
    image = qa_utils.GetCommandOutput(pnode, cmd).strip()
Jose A. Lopes's avatar
Jose A. Lopes committed
407 408

    AssertCommand(["gnt-instance", "reinstall",
409
                   "--os-parameters", "os-image=" + image,
Jose A. Lopes's avatar
Jose A. Lopes committed
410 411
                   "-f", instance.name])

412
  # Reinstall non existing local file
Jose A. Lopes's avatar
Jose A. Lopes committed
413 414 415 416
  AssertCommand(["gnt-instance", "reinstall",
                 "--os-parameters", "os-image=NonExistantOsForQa",
                 "-f", instance.name], fail=True)

417
  # Reinstall non existing URL
Jose A. Lopes's avatar
Jose A. Lopes committed
418 419 420 421
  AssertCommand(["gnt-instance", "reinstall",
                 "--os-parameters", "os-image=http://NonExistantOsForQa",
                 "-f", instance.name], fail=True)

422
  # Reinstall using OS scripts
423
  AssertCommand(["gnt-instance", "reinstall", "-f", instance.name])
Michael Hanselmann's avatar
Michael Hanselmann committed
424

425 426 427
  # Test with non-existant OS definition
  AssertCommand(["gnt-instance", "reinstall", "-f",
                 "--os-type=NonExistantOsForQa",
428
                 instance.name],
429 430
                fail=True)

431 432 433 434 435 436 437 438 439 440
  # Test with existing OS but invalid variant
  AssertCommand(["gnt-instance", "reinstall", "-f", "-o", "debootstrap+ola",
                 instance.name],
                fail=True)

  # Test with existing OS but invalid variant
  AssertCommand(["gnt-instance", "reinstall", "-f", "-o", "debian-image+ola",
                 instance.name],
                fail=True)

Michael Hanselmann's avatar
Michael Hanselmann committed
441

442
@InstanceCheck(INST_DOWN, INST_DOWN, FIRST_ARG)
Iustin Pop's avatar
Iustin Pop committed
443 444 445 446 447 448 449
def TestInstanceRenameAndBack(rename_source, rename_target):
  """gnt-instance rename

  This must leave the instance with the original name, not the target
  name.

  """
450
  CheckSsconfInstanceList(rename_source)
451

Iustin Pop's avatar
Iustin Pop committed
452
  # first do a rename to a different actual name, expecting it to fail
453 454 455 456
  qa_utils.AddToEtcHosts(["meeeeh-not-exists", rename_target])
  try:
    AssertCommand(["gnt-instance", "rename", rename_source, rename_target],
                  fail=True)
457
    CheckSsconfInstanceList(rename_source)
458 459
  finally:
    qa_utils.RemoveFromEtcHosts(["meeeeh-not-exists", rename_target])
460

461
  info = GetInstanceInfo(rename_source)
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476

  # Check instance volume tags correctly updated. Note that this check is lvm
  # specific, so we skip it for non-lvm-based instances.
  # FIXME: This will need updating when instances will be able to have
  # different disks living on storage pools with etherogeneous storage types.
  # FIXME: This check should be put inside the disk/storage class themselves,
  # rather than explicitly called here.
  if info["storage-type"] == constants.ST_LVM_VG:
    # In the lvm world we can check for tags on the logical volume
    tags_cmd = ("lvs -o tags --noheadings %s | grep " %
                (" ".join(info["volumes"]), ))
  else:
    # Other storage types don't have tags, so we use an always failing command,
    # to make sure it never gets executed
    tags_cmd = "false"
477

Iustin Pop's avatar
Iustin Pop committed
478
  # and now rename instance to rename_target...
479
  AssertCommand(["gnt-instance", "rename", rename_source, rename_target])
480
  CheckSsconfInstanceList(rename_target)
481
  qa_utils.RunInstanceCheck(rename_source, False)
482
  qa_utils.RunInstanceCheck(rename_target, False)
483

484 485
  # NOTE: tags might not be the exactly as the instance name, due to
  # charset restrictions; hence the test might be flaky
486 487
  if (rename_source != rename_target and
      info["storage-type"] == constants.ST_LVM_VG):
488 489 490 491
    for node in info["nodes"]:
      AssertCommand(tags_cmd + rename_source, node=node, fail=True)
      AssertCommand(tags_cmd + rename_target, node=node, fail=False)

Iustin Pop's avatar
Iustin Pop committed
492 493
  # and back
  AssertCommand(["gnt-instance", "rename", rename_target, rename_source])
494
  CheckSsconfInstanceList(rename_source)
495
  qa_utils.RunInstanceCheck(rename_target, False)
496

497 498
  if (rename_source != rename_target and
      info["storage-type"] == constants.ST_LVM_VG):
499 500 501 502
    for node in info["nodes"]:
      AssertCommand(tags_cmd + rename_source, node=node, fail=False)
      AssertCommand(tags_cmd + rename_target, node=node, fail=True)

503

504
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
505 506
def TestInstanceFailover(instance):
  """gnt-instance failover"""
507 508 509 510 511
  if not IsFailoverSupported(instance):
    print qa_utils.FormatInfo("Instance doesn't support failover, skipping"
                              " test")
    return

512
  cmd = ["gnt-instance", "failover", "--force", instance.name]
513

Iustin Pop's avatar
Iustin Pop committed
514 515
  # failover ...
  AssertCommand(cmd)
516 517
  qa_utils.RunInstanceCheck(instance, True)

518
  # ... and back
Iustin Pop's avatar
Iustin Pop committed
519
  AssertCommand(cmd)
520

521

522
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
523
def TestInstanceMigrate(instance, toggle_always_failover=True):
524
  """gnt-instance migrate"""
525 526 527 528 529
  if not IsMigrationSupported(instance):
    print qa_utils.FormatInfo("Instance doesn't support migration, skipping"
                              " test")
    return

530
  cmd = ["gnt-instance", "migrate", "--force", instance.name]
531 532
  af_par = constants.BE_ALWAYS_FAILOVER
  af_field = "be/" + constants.BE_ALWAYS_FAILOVER
533
  af_init_val = _GetBoolInstanceField(instance.name, af_field)
534

Iustin Pop's avatar
Iustin Pop committed
535 536
  # migrate ...
  AssertCommand(cmd)
537
  # TODO: Verify the choice between failover and migration
538 539
  qa_utils.RunInstanceCheck(instance, True)

540 541 542 543
  # ... and back (possibly with always_failover toggled)
  if toggle_always_failover:
    AssertCommand(["gnt-instance", "modify", "-B",
                   ("%s=%s" % (af_par, not af_init_val)),
544
                   instance.name])
Iustin Pop's avatar
Iustin Pop committed
545
  AssertCommand(cmd)
546 547 548 549
  # TODO: Verify the choice between failover and migration
  qa_utils.RunInstanceCheck(instance, True)
  if toggle_always_failover:
    AssertCommand(["gnt-instance", "modify", "-B",
550
                   ("%s=%s" % (af_par, af_init_val)), instance.name])
551 552

  # TODO: Split into multiple tests
553
  AssertCommand(["gnt-instance", "shutdown", instance.name])
554
  qa_utils.RunInstanceCheck(instance, False)
555 556
  AssertCommand(cmd, fail=True)
  AssertCommand(["gnt-instance", "migrate", "--force", "--allow-failover",
557 558
                 instance.name])
  AssertCommand(["gnt-instance", "start", instance.name])
559
  AssertCommand(cmd)
560
  # @InstanceCheck enforces the check that the instance is running
561 562
  qa_utils.RunInstanceCheck(instance, True)

563 564 565
  AssertCommand(["gnt-instance", "modify", "-B",
                 ("%s=%s" %
                  (constants.BE_ALWAYS_FAILOVER, constants.VALUE_TRUE)),
566
                 instance.name])
567

568
  AssertCommand(cmd)
569
  qa_utils.RunInstanceCheck(instance, True)
570
  # TODO: Verify that a failover has been done instead of a migration
571 572

  # TODO: Verify whether the default value is restored here (not hardcoded)
573 574 575
  AssertCommand(["gnt-instance", "modify", "-B",
                 ("%s=%s" %
                  (constants.BE_ALWAYS_FAILOVER, constants.VALUE_FALSE)),
576
                 instance.name])
577

578
  AssertCommand(cmd)
579
  qa_utils.RunInstanceCheck(instance, True)
580 581


582 583
def TestInstanceInfo(instance):
  """gnt-instance info"""
584
  AssertCommand(["gnt-instance", "info", instance.name])
Michael Hanselmann's avatar
Michael Hanselmann committed
585 586


587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
def _TestKVMHotplug(instance):
  """Tests hotplug modification commands, noting that they

  """
  args_to_try = [
    ["--net", "-1:add", "--hotplug"],
    ["--net", "-1:modify,mac=aa:bb:cc:dd:ee:ff", "--hotplug", "--force"],
    ["--net", "-1:remove", "--hotplug"],
    ["--disk", "-1:add,size=1G", "--hotplug"],
    ["--disk", "-1:remove", "--hotplug"],
  ]
  for alist in args_to_try:
    _, stdout, stderr = \
      AssertCommand(["gnt-instance", "modify"] + alist + [instance.name])
    if "failed" in stdout or "failed" in stderr:
      raise qa_error.Error("Hotplugging command failed; please check output"
                           " for further information")


606
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
607 608
def TestInstanceModify(instance):
  """gnt-instance modify"""
609 610
  default_hv = qa_config.GetDefaultHypervisor()

611 612 613 614
  # Assume /sbin/init exists on all systems
  test_kernel = "/sbin/init"
  test_initrd = test_kernel

615 616
  orig_maxmem = qa_config.get(constants.BE_MAXMEM)
  orig_minmem = qa_config.get(constants.BE_MINMEM)
Iustin Pop's avatar
Iustin Pop committed
617
  #orig_bridge = qa_config.get("bridge", "xen-br0")
618

619
  args = [
620 621 622 623
    ["-B", "%s=128" % constants.BE_MINMEM],
    ["-B", "%s=128" % constants.BE_MAXMEM],
    ["-B", "%s=%s,%s=%s" % (constants.BE_MINMEM, orig_minmem,
                            constants.BE_MAXMEM, orig_maxmem)],
624 625 626
    ["-B", "%s=2" % constants.BE_VCPUS],
    ["-B", "%s=1" % constants.BE_VCPUS],
    ["-B", "%s=%s" % (constants.BE_VCPUS, constants.VALUE_DEFAULT)],
627 628
    ["-B", "%s=%s" % (constants.BE_ALWAYS_FAILOVER, constants.VALUE_TRUE)],
    ["-B", "%s=%s" % (constants.BE_ALWAYS_FAILOVER, constants.VALUE_DEFAULT)],
629 630 631 632

    # TODO: bridge tests
    #["--bridge", "xen-br1"],
    #["--bridge", orig_bridge],
633
    ]
634

635 636 637 638 639 640 641 642 643
  # Not all hypervisors support kernel_path(e.g, LXC)
  if default_hv in (constants.HT_XEN_PVM,
                    constants.HT_XEN_HVM,
                    constants.HT_KVM):
    args.extend([
      ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, test_kernel)],
      ["-H", "%s=%s" % (constants.HV_KERNEL_PATH, constants.VALUE_DEFAULT)],
      ])

644 645 646 647 648 649 650 651 652 653 654
  if default_hv == constants.HT_XEN_PVM:
    args.extend([
      ["-H", "%s=%s" % (constants.HV_INITRD_PATH, test_initrd)],
      ["-H", "no_%s" % (constants.HV_INITRD_PATH, )],
      ["-H", "%s=%s" % (constants.HV_INITRD_PATH, constants.VALUE_DEFAULT)],
      ])
  elif default_hv == constants.HT_XEN_HVM:
    args.extend([
      ["-H", "%s=acn" % constants.HV_BOOT_ORDER],
      ["-H", "%s=%s" % (constants.HV_BOOT_ORDER, constants.VALUE_DEFAULT)],
      ])
655 656
  elif default_hv == constants.HT_KVM and \
    qa_config.TestEnabled("instance-device-hotplug"):
657
    _TestKVMHotplug(instance)
658 659 660 661
  elif default_hv == constants.HT_LXC:
    args.extend([
      ["-H", "%s=0" % constants.HV_CPU_MASK],
      ["-H", "%s=%s" % (constants.HV_CPU_MASK, constants.VALUE_DEFAULT)],
Hrvoje Ribicic's avatar
Hrvoje Ribicic committed
662 663
      ["-H", "%s=0" % constants.HV_LXC_NUM_TTYS],
      ["-H", "%s=%s" % (constants.HV_LXC_NUM_TTYS, constants.VALUE_DEFAULT)],
664
      ])
665

Jose A. Lopes's avatar
Jose A. Lopes committed
666 667 668 669 670 671
  url = "http://example.com/busybox.img"
  args.extend([
      ["--os-parameters", "os-image=" + url],
      ["--os-parameters", "os-image=default"]
      ])

672
  for alist in args:
673
    AssertCommand(["gnt-instance", "modify"] + alist + [instance.name])
674 675

  # check no-modify
676
  AssertCommand(["gnt-instance", "modify", instance.name], fail=True)
677

678
  # Marking offline while instance is running must fail...
679
  AssertCommand(["gnt-instance", "modify", "--offline", instance.name],
680 681
                 fail=True)

682 683 684
  # ...while making it online fails too (needs to be offline first)
  AssertCommand(["gnt-instance", "modify", "--online", instance.name],
                 fail=True)
685 686


687 688 689 690 691 692 693 694 695 696 697
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
def TestInstanceModifyPrimaryAndBack(instance, currentnode, othernode):
  """gnt-instance modify --new-primary

  This will leave the instance on its original primary node, not other node.

  """
  if instance.disk_template != constants.DT_FILE:
    print qa_utils.FormatInfo("Test only supported for the file disk template")
    return

698 699
  cluster_name = qa_config.get("name")

700 701 702 703
  name = instance.name
  current = currentnode.primary
  other = othernode.primary

704 705
  filestorage = qa_config.get("file-storage-dir",
                              pathutils.DEFAULT_FILE_STORAGE_DIR)
706 707 708 709 710
  disk = os.path.join(filestorage, name)

  AssertCommand(["gnt-instance", "modify", "--new-primary=%s" % other, name],
                fail=True)
  AssertCommand(["gnt-instance", "shutdown", name])
711 712 713 714
  AssertCommand(["scp", "-oGlobalKnownHostsFile=%s" %
                 pathutils.SSH_KNOWN_HOSTS_FILE,
                 "-oCheckHostIp=no", "-oStrictHostKeyChecking=yes",
                 "-oHashKnownHosts=no", "-oHostKeyAlias=%s" % cluster_name,
715
                 "-r", disk, "%s:%s" % (other, filestorage)], node=current)
716 717 718 719 720 721 722 723 724 725
  AssertCommand(["gnt-instance", "modify", "--new-primary=%s" % other, name])
  AssertCommand(["gnt-instance", "startup", name])

  # and back
  AssertCommand(["gnt-instance", "shutdown", name])
  AssertCommand(["rm", "-rf", disk], node=other)
  AssertCommand(["gnt-instance", "modify", "--new-primary=%s" % current, name])
  AssertCommand(["gnt-instance", "startup", name])


726
@InstanceCheck(INST_DOWN, INST_DOWN, FIRST_ARG)
727 728
def TestInstanceStoppedModify(instance):
  """gnt-instance modify (stopped instance)"""
729
  name = instance.name
730

731 732
  # Instance was not marked offline; try marking it online once more
  AssertCommand(["gnt-instance", "modify", "--online", name])
733 734 735 736

  # Mark instance as offline
  AssertCommand(["gnt-instance", "modify", "--offline", name])

737 738 739 740 741 742 743 744 745 746
  # When the instance is offline shutdown should only work with --force,
  # while start should never work
  AssertCommand(["gnt-instance", "shutdown", name], fail=True)
  AssertCommand(["gnt-instance", "shutdown", "--force", name])
  AssertCommand(["gnt-instance", "start", name], fail=True)
  AssertCommand(["gnt-instance", "start", "--force", name], fail=True)

  # Also do offline to offline
  AssertCommand(["gnt-instance", "modify", "--offline", name])

747 748 749
  # And online again
  AssertCommand(["gnt-instance", "modify", "--online", name])

750

751
@InstanceCheck(INST_DOWN, INST_DOWN, FIRST_ARG)
752
def TestInstanceConvertDiskTemplate(instance, requested_conversions):
753
  """gnt-instance modify -t"""
754 755 756 757 758 759 760 761 762 763 764 765 766
  def _BuildConvertCommand(disk_template, node):
    cmd = ["gnt-instance", "modify", "-t", disk_template]
    if disk_template == constants.DT_DRBD8:
      cmd.extend(["-n", node])
    cmd.append(name)
    return cmd

  if len(requested_conversions) < 2:
    print qa_utils.FormatInfo("You must specify more than one convertible"
                              " disk templates in order to test the conversion"
                              " feature")
    return

767
  name = instance.name
768

769
  template = instance.disk_template
770
  if template in constants.DTS_NOT_CONVERTIBLE_FROM:
771 772 773
    print qa_utils.FormatInfo("Unsupported template %s, skipping conversion"
                              " test" % template)
    return
774

775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792
  inodes = qa_config.AcquireManyNodes(2)
  master = qa_config.GetMasterNode()

  snode = inodes[0].primary
  if master.primary == snode:
    snode = inodes[1].primary

  enabled_disk_templates = qa_config.GetEnabledDiskTemplates()

  for templ in requested_conversions:
    if (templ == template or
        templ not in enabled_disk_templates or
        templ in constants.DTS_NOT_CONVERTIBLE_TO):
      continue
    AssertCommand(_BuildConvertCommand(templ, snode))

  # Before we return, convert to the original template
  AssertCommand(_BuildConvertCommand(template, snode))
793 794


795 796 797 798 799 800 801
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
def TestInstanceModifyDisks(instance):
  """gnt-instance modify --disk"""
  if not IsDiskSupported(instance):
    print qa_utils.FormatInfo("Instance doesn't support disks, skipping test")
    return

802 803
  disk_conf = qa_config.GetDiskOptions()[-1]
  size = disk_conf.get("size")
804
  name = instance.name
805
  build_cmd = lambda arg: ["gnt-instance", "modify", "--disk", arg, name]
806 807 808 809 810 811 812 813 814 815 816 817
  if qa_config.AreSpindlesSupported():
    spindles = disk_conf.get("spindles")
    spindles_supported = True
  else:
    # Any number is good for spindles in this case
    spindles = 1
    spindles_supported = False
  AssertCommand(build_cmd("add:size=%s,spindles=%s" % (size, spindles)),
                fail=not spindles_supported)
  AssertCommand(build_cmd("add:size=%s" % size),
                fail=spindles_supported)
  # Exactly one of the above commands has succeded, so we need one remove
818 819 820
  AssertCommand(build_cmd("remove"))


821
@InstanceCheck(INST_DOWN, INST_DOWN, FIRST_ARG)
Iustin Pop's avatar
Iustin Pop committed
822 823
def TestInstanceGrowDisk(instance):
  """gnt-instance grow-disk"""
824 825 826 827
  if instance.disk_template == constants.DT_DISKLESS:
    print qa_utils.FormatInfo("Test not supported for diskless instances")
    return

828
  name = instance.name
829 830 831
  disks = qa_config.GetDiskOptions()
  all_size = [d.get("size") for d in disks]
  all_grow = [d.get("growth") for d in disks]
832

Iustin Pop's avatar
Iustin Pop committed
833 834 835 836
  if not all_grow:
    # missing disk sizes but instance grow disk has been enabled,
    # let's set fixed/nomimal growth
    all_grow = ["128M" for _ in all_size]
837

Iustin Pop's avatar
Iustin Pop committed
838 839 840 841 842 843 844 845 846 847 848 849 850
  for idx, (size, grow) in enumerate(zip(all_size, all_grow)):
    # succeed in grow by amount
    AssertCommand(["gnt-instance", "grow-disk", name, str(idx), grow])
    # fail in grow to the old size
    AssertCommand(["gnt-instance", "grow-disk", "--absolute", name, str(idx),
                   size], fail=True)
    # succeed to grow to old size + 2 * growth
    int_size = utils.ParseUnit(size)
    int_grow = utils.ParseUnit(grow)
    AssertCommand(["gnt-instance", "grow-disk", "--absolute", name, str(idx),
                   str(int_size + 2 * int_grow)])


851 852 853 854 855 856 857 858 859 860
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
def TestInstanceDeviceNames(instance):
  if instance.disk_template == constants.DT_DISKLESS:
    print qa_utils.FormatInfo("Test not supported for diskless instances")
    return

  name = instance.name
  for dev_type in ["disk", "net"]:
    if dev_type == "disk":
      options = ",size=512M"
861 862
      if qa_config.AreSpindlesSupported():
        options += ",spindles=1"
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
    else:
      options = ""
    # succeed in adding a device named 'test_device'
    AssertCommand(["gnt-instance", "modify",
                   "--%s=-1:add,name=test_device%s" % (dev_type, options),
                   name])
    # succeed in removing the 'test_device'
    AssertCommand(["gnt-instance", "modify",
                   "--%s=test_device:remove" % dev_type,
                   name])
    # fail to add two devices with the same name
    AssertCommand(["gnt-instance", "modify",
                   "--%s=-1:add,name=test_device%s" % (dev_type, options),
                   "--%s=-1:add,name=test_device%s" % (dev_type, options),
                   name], fail=True)
    # fail to add a device with invalid name
    AssertCommand(["gnt-instance", "modify",
                   "--%s=-1:add,name=2%s" % (dev_type, options),
                   name], fail=True)
  # Rename disks
  disks = qa_config.GetDiskOptions()
  disk_names = [d.get("name") for d in disks]
  for idx, disk_name in enumerate(disk_names):
    # Refer to disk by idx
    AssertCommand(["gnt-instance", "modify",
                   "--disk=%s:modify,name=renamed" % idx,
                   name])
    # Refer to by name and rename to original name
    AssertCommand(["gnt-instance", "modify",
                   "--disk=renamed:modify,name=%s" % disk_name,
                   name])
  if len(disks) >= 2:
    # fail in renaming to disks to the same name
    AssertCommand(["gnt-instance", "modify",
                   "--disk=0:modify,name=same_name",
                   "--disk=1:modify,name=same_name",
                   name], fail=True)


Michael Hanselmann's avatar
Michael Hanselmann committed
902 903
def TestInstanceList():
  """gnt-instance list"""
904
  qa_utils.GenericQueryTest("gnt-instance", query.INSTANCE_FIELDS.keys())
Michael Hanselmann's avatar
Michael Hanselmann committed
905 906


907 908 909 910 911
def TestInstanceListFields():
  """gnt-instance list-fields"""
  qa_utils.GenericQueryFieldsTest("gnt-instance", query.INSTANCE_FIELDS.keys())


912
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
913 914
def TestInstanceConsole(instance):
  """gnt-instance console"""
915
  AssertCommand(["gnt-instance", "console", "--show-cmd", instance.name])
916 917


918
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
919
def TestReplaceDisks(instance, curr_nodes, other_nodes):
920 921
  """gnt-instance replace-disks"""
  def buildcmd(args):
Iustin Pop's avatar
Iustin Pop committed
922
    cmd = ["gnt-instance", "replace-disks"]
923
    cmd.extend(args)
924
    cmd.append(instance.name)
925 926
    return cmd

927 928 929 930 931
  if not IsDiskReplacingSupported(instance):
    print qa_utils.FormatInfo("Instance doesn't support disk replacing,"
                              " skipping test")
    return

932 933 934 935 936 937
  # Currently all supported templates have one primary and one secondary node
  assert len(curr_nodes) == 2
  snode = curr_nodes[1]
  assert len(other_nodes) == 1
  othernode = other_nodes[0]

938 939
  options = qa_config.get("options", {})
  use_ialloc = options.get("use-iallocators", True)
Iustin Pop's avatar
Iustin Pop committed
940 941 942
  for data in [
    ["-p"],
    ["-s"],
943 944 945
    # A placeholder; the actual command choice depends on use_ialloc
    None,
    # Restore the original secondary
946
    ["--new-secondary=%s" % snode.primary],
Iustin Pop's avatar
Iustin Pop committed
947
    ]:
948 949 950 951
    if data is None:
      if use_ialloc:
        data = ["-I", constants.DEFAULT_IALLOCATOR_SHORTCUT]
      else:
952
        data = ["--new-secondary=%s" % othernode.primary]
Iustin Pop's avatar
Iustin Pop committed
953
    AssertCommand(buildcmd(data))
954

955
  AssertCommand(buildcmd(["-a"]))
956
  AssertCommand(["gnt-instance", "stop", instance.name])
957
  AssertCommand(buildcmd(["-a"]), fail=True)
958
  AssertCommand(["gnt-instance", "activate-disks", instance.name])
959
  AssertCommand(["gnt-instance", "activate-disks", "--wait-for-sync",
960
                 instance.name])
961
  AssertCommand(buildcmd(["-a"]))
962
  AssertCommand(["gnt-instance", "start", instance.name])
963

964

965 966 967 968 969 970 971 972 973 974 975 976
def _AssertRecreateDisks(cmdargs, instance, fail=False, check=True,
                         destroy=True):
  """Execute gnt-instance recreate-disks and check the result

  @param cmdargs: Arguments (instance name excluded)
  @param instance: Instance to operate on
  @param fail: True if the command is expected to fail
  @param check: If True and fail is False, check that the disks work
  @prama destroy: If True, destroy the old disks first

  """
  if destroy:
977
    _DestroyInstanceDisks(instance)
978
  AssertCommand((["gnt-instance", "recreate-disks"] + cmdargs +
979
                 [instance.name]), fail)
980 981
  if not fail and check:
    # Quick check that the disks are there
982
    AssertCommand(["gnt-instance", "activate-disks", instance.name])
983
    AssertCommand(["gnt-instance", "activate-disks", "--wait-for-sync",
984 985
                   instance.name])
    AssertCommand(["gnt-instance", "deactivate-disks", instance.name])
986

Bernardo Dal Seno's avatar
Bernardo Dal Seno committed
987

988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
def _BuildRecreateDisksOpts(en_disks, with_spindles, with_growth,
                            spindles_supported):
  if with_spindles:
    if spindles_supported:
      if with_growth:
        build_spindles_opt = (lambda disk:
                              ",spindles=%s" %
                              (disk["spindles"] + disk["spindles-growth"]))
      else:
        build_spindles_opt = (lambda disk:
                              ",spindles=%s" % disk["spindles"])
    else:
      build_spindles_opt = (lambda _: ",spindles=1")
  else:
    build_spindles_opt = (lambda _: "")
  if with_growth:
    build_size_opt = (lambda disk:
                      "size=%s" % (utils.ParseUnit(disk["size"]) +
                                   utils.ParseUnit(disk["growth"])))
  else:
    build_size_opt = (lambda disk: "size=%s" % disk["size"])
  build_disk_opt = (lambda (idx, disk):
                    "--disk=%s:%s%s" % (idx, build_size_opt(disk),
                                        build_spindles_opt(disk)))
  return map(build_disk_opt, en_disks)


1015
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
1016
def TestRecreateDisks(instance, inodes, othernodes):
1017 1018 1019
  """gnt-instance recreate-disks

  @param instance: Instance to work on
1020
  @param inodes: List of the current nodes of the instance
1021 1022 1023
  @param othernodes: list/tuple of nodes where to temporarily recreate disks

  """
1024 1025
  options = qa_config.get("options", {})
  use_ialloc = options.get("use-iallocators", True)
1026 1027
  other_seq = ":".join([n.primary for n in othernodes])
  orig_seq = ":".join([n.primary for n in inodes])
1028
  # These fail because the instance is running
1029
  _AssertRecreateDisks(["-n", other_seq], instance, fail=True, destroy=False)
1030 1031 1032 1033
  if use_ialloc:
    _AssertRecreateDisks(["-I", "hail"], instance, fail=True, destroy=False)
  else:
    _AssertRecreateDisks(["-n", other_seq], instance, fail=True, destroy=False)
1034
  AssertCommand(["gnt-instance", "stop", instance.name])
1035 1036
  # Disks exist: this should fail
  _AssertRecreateDisks([], instance, fail=True, destroy=False)
1037 1038 1039 1040
  # Unsupported spindles parameters: fail
  if not qa_config.AreSpindlesSupported():
    _AssertRecreateDisks(["--disk=0:spindles=2"], instance,
                         fail=True, destroy=False)
1041 1042 1043
  # Recreate disks in place
  _AssertRecreateDisks([], instance)
  # Move disks away
1044 1045 1046 1047 1048 1049 1050
  if use_ialloc:
    _AssertRecreateDisks(["-I", "hail"], instance)
    # Move disks somewhere else
    _AssertRecreateDisks(["-I", constants.DEFAULT_IALLOCATOR_SHORTCUT],
                         instance)
  else:
    _AssertRecreateDisks(["-n", other_seq], instance)
1051
  # Move disks back
1052
  _AssertRecreateDisks(["-n", orig_seq], instance)
1053
  # Recreate resized disks
1054 1055
  # One of the two commands fails because either spindles are given when they
  # should not or vice versa
1056
  alldisks = qa_config.GetDiskOptions()
1057 1058 1059 1060 1061 1062 1063 1064 1065
  spindles_supported = qa_config.AreSpindlesSupported()
  disk_opts = _BuildRecreateDisksOpts(enumerate(alldisks), True, True,
                                      spindles_supported)
  _AssertRecreateDisks(disk_opts, instance, destroy=True,
                       fail=not spindles_supported)
  disk_opts = _BuildRecreateDisksOpts(enumerate(alldisks), False, True,
                                      spindles_supported)
  _AssertRecreateDisks(disk_opts, instance, destroy=False,
                       fail=spindles_supported)
1066 1067
  # Recreate the disks one by one (with the original size)
  for (idx, disk) in enumerate(alldisks):
1068 1069
    # Only the first call should destroy all the disk
    destroy = (idx == 0)
1070 1071 1072 1073 1074 1075 1076 1077 1078
    # Again, one of the two commands is expected to fail
    disk_opts = _BuildRecreateDisksOpts([(idx, disk)], True, False,
                                        spindles_supported)
    _AssertRecreateDisks(disk_opts, instance, destroy=destroy, check=False,
                         fail=not spindles_supported)
    disk_opts = _BuildRecreateDisksOpts([(idx, disk)], False, False,
                                        spindles_supported)
    _AssertRecreateDisks(disk_opts, instance, destroy=False, check=False,
                         fail=spindles_supported)
1079
  # This and InstanceCheck decoration check that the disks are working
1080 1081
  AssertCommand(["gnt-instance", "reinstall", "-f", instance.name])
  AssertCommand(["gnt-instance", "start", instance.name])
1082 1083


1084
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
Michael Hanselmann's avatar
Michael Hanselmann committed
1085
def TestInstanceExport(instance, node):
1086
  """gnt-backup export -n ..."""
1087
  name = instance.name
1088 1089 1090
  options = ["gnt-backup", "export", "-n", node.primary]

  # For files and shared files, the --long-sleep option should be used
1091
  if instance.disk_template in [constants.DT_FILE, constants.DT_SHARED_FILE]:
1092 1093 1094
    options.append("--long-sleep")

  AssertCommand(options + [name])
Iustin Pop's avatar
Iustin Pop committed
1095
  return qa_utils.ResolveInstanceName(name)
Michael Hanselmann's avatar
Michael Hanselmann committed
1096 1097


1098
@InstanceCheck(None, INST_DOWN, FIRST_ARG)
1099 1100
def TestInstanceExportWithRemove(instance, node):
  """gnt-backup export --remove-instance"""
1101
  AssertCommand(["gnt-backup", "export", "-n", node.primary,
1102
                 "--remove-instance", instance.name])
1103 1104


1105
@InstanceCheck(INST_UP, INST_UP, FIRST_ARG)
1106 1107
def TestInstanceExportNoTarget(instance):
  """gnt-backup export (without target node, should fail)"""
1108
  AssertCommand(["gnt-backup", "export", instance.name], fail=True)
1109 1110


1111
@InstanceCheck(None, INST_DOWN, FIRST_ARG)
1112
def TestInstanceImport(newinst, node, expnode, name):
Michael Hanselmann's avatar
Michael Hanselmann committed
1113
  """gnt-backup import"""
1114
  templ = constants.DT_PLAIN
1115 1116
  if not qa_config.IsTemplateSupported(templ):
    return
Iustin Pop's avatar
Iustin Pop committed
1117
  cmd = (["gnt-backup", "import",
1118
          "--disk-template=%s" % templ,
Iustin Pop's avatar
Iustin Pop committed
1119
          "--no-ip-check",
1120
          "--src-node=%s" % expnode.primary,
1121
          "--src-dir=%s/%s" % (pathutils.EXPORT_DIR, name),
1122
          "--node=%s" % node.primary] +
1123
         GetGenericAddParameters(newinst, templ,
1124
                                  force_mac=constants.VALUE_GENERATE))
1125
  cmd.append(newinst.name)
Iustin Pop's avatar
Iustin Pop committed
1126
  AssertCommand(cmd)
1127
  newinst.SetDiskTemplate(templ)
Michael Hanselmann's avatar
Michael Hanselmann committed
1128 1129 1130 1131


def TestBackupList(expnode):
  """gnt-backup list"""