gnt-instance 55.5 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/usr/bin/python
#

# Copyright (C) 2006, 2007 Google Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


22 23 24 25
# pylint: disable-msg=W0401,W0614
# W0401: Wildcard import ganeti.cli
# W0614: Unused import %s from wildcard import (since we need cli)

Iustin Pop's avatar
Iustin Pop committed
26 27
import sys
import os
28
import itertools
29
import simplejson
Iustin Pop's avatar
Iustin Pop committed
30 31 32 33
from optparse import make_option
from cStringIO import StringIO

from ganeti.cli import *
34
from ganeti import cli
Iustin Pop's avatar
Iustin Pop committed
35 36 37
from ganeti import opcodes
from ganeti import constants
from ganeti import utils
38 39 40 41 42 43 44 45 46
from ganeti import errors


_SHUTDOWN_CLUSTER = "cluster"
_SHUTDOWN_NODES_BOTH = "nodes"
_SHUTDOWN_NODES_PRI = "nodes-pri"
_SHUTDOWN_NODES_SEC = "nodes-sec"
_SHUTDOWN_INSTANCES = "instances"

47

48 49
_VALUE_TRUE = "true"

50
#: default list of options for L{ListInstances}
51
_LIST_DEF_FIELDS = [
52
  "name", "hypervisor", "os", "pnode", "status", "oper_ram",
53 54
  ]

55

56
def _ExpandMultiNames(mode, names, client=None):
57 58 59 60
  """Expand the given names using the passed mode.

  For _SHUTDOWN_CLUSTER, all instances will be returned. For
  _SHUTDOWN_NODES_PRI/SEC, all instances having those nodes as
61
  primary/secondary will be returned. For _SHUTDOWN_NODES_BOTH, all
62 63 64 65
  instances having those nodes as either primary or secondary will be
  returned. For _SHUTDOWN_INSTANCES, the given instances will be
  returned.

66 67 68 69 70 71 72 73 74 75 76 77
  @param mode: one of L{_SHUTDOWN_CLUSTER}, L{_SHUTDOWN_NODES_BOTH},
      L{_SHUTDOWN_NODES_PRI}, L{_SHUTDOWN_NODES_SEC} or
      L{_SHUTDOWN_INSTANCES}
  @param names: a list of names; for cluster, it must be empty,
      and for node and instance it must be a list of valid item
      names (short names are valid as usual, e.g. node1 instead of
      node1.example.com)
  @rtype: list
  @return: the list of names after the expansion
  @raise errors.ProgrammerError: for unknown selection type
  @raise errors.OpPrereqError: for invalid input parameters

78
  """
79 80
  if client is None:
    client = GetClient()
81 82 83
  if mode == _SHUTDOWN_CLUSTER:
    if names:
      raise errors.OpPrereqError("Cluster filter mode takes no arguments")
84
    idata = client.QueryInstances([], ["name"], False)
85 86 87 88 89 90 91
    inames = [row[0] for row in idata]

  elif mode in (_SHUTDOWN_NODES_BOTH,
                _SHUTDOWN_NODES_PRI,
                _SHUTDOWN_NODES_SEC):
    if not names:
      raise errors.OpPrereqError("No node names passed")
92
    ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"],
93
                              False)
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    ipri = [row[1] for row in ndata]
    pri_names = list(itertools.chain(*ipri))
    isec = [row[2] for row in ndata]
    sec_names = list(itertools.chain(*isec))
    if mode == _SHUTDOWN_NODES_BOTH:
      inames = pri_names + sec_names
    elif mode == _SHUTDOWN_NODES_PRI:
      inames = pri_names
    elif mode == _SHUTDOWN_NODES_SEC:
      inames = sec_names
    else:
      raise errors.ProgrammerError("Unhandled shutdown type")

  elif mode == _SHUTDOWN_INSTANCES:
    if not names:
      raise errors.OpPrereqError("No instance names passed")
110
    idata = client.QueryInstances(names, ["name"], False)
111 112 113 114 115 116
    inames = [row[0] for row in idata]

  else:
    raise errors.OpPrereqError("Unknown mode '%s'" % mode)

  return inames
Iustin Pop's avatar
Iustin Pop committed
117 118


119
def _ConfirmOperation(inames, text, extra=""):
120 121 122 123 124
  """Ask the user to confirm an operation on a list of instances.

  This function is used to request confirmation for doing an operation
  on a given list of instances.

125 126 127 128 129 130 131 132
  @type inames: list
  @param inames: the list of names that we display when
      we ask for confirmation
  @type text: str
  @param text: the operation that the user should confirm
      (e.g. I{shutdown} or I{startup})
  @rtype: boolean
  @return: True or False depending on user's confirmation.
133 134 135

  """
  count = len(inames)
136 137
  msg = ("The %s will operate on %d instances.\n%s"
         "Do you want to continue?" % (text, count, extra))
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
  affected = ("\nAffected instances:\n" +
              "\n".join(["  %s" % name for name in inames]))

  choices = [('y', True, 'Yes, execute the %s' % text),
             ('n', False, 'No, abort the %s' % text)]

  if count > 20:
    choices.insert(1, ('v', 'v', 'View the list of affected instances'))
    ask = msg
  else:
    ask = msg + affected

  choice = AskUser(ask, choices)
  if choice == 'v':
    choices.pop(1)
153
    choice = AskUser(msg + affected, choices)
154 155 156
  return choice


157 158 159 160 161 162
def _EnsureInstancesExist(client, names):
  """Check for and ensure the given instance names exist.

  This function will raise an OpPrereqError in case they don't
  exist. Otherwise it will exit cleanly.

Iustin Pop's avatar
Iustin Pop committed
163
  @type client: L{ganeti.luxi.Client}
164 165 166 167 168 169 170 171
  @param client: the client to use for the query
  @type names: list
  @param names: the list of instance names to query
  @raise errors.OpPrereqError: in case any instance is missing

  """
  # TODO: change LUQueryInstances to that it actually returns None
  # instead of raising an exception, or devise a better mechanism
172
  result = client.QueryInstances(names, ["name"], False)
173 174 175 176 177
  for orig_name, row in zip(names, result):
    if row[0] is None:
      raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name)


Iustin Pop's avatar
Iustin Pop committed
178
def ListInstances(opts, args):
Oleksiy Mishchenko's avatar
Oleksiy Mishchenko committed
179
  """List instances and their properties.
Iustin Pop's avatar
Iustin Pop committed
180

181 182 183 184 185 186
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should be an empty list
  @rtype: int
  @return: the desired exit code

Iustin Pop's avatar
Iustin Pop committed
187 188
  """
  if opts.output is None:
189 190 191
    selected_fields = _LIST_DEF_FIELDS
  elif opts.output.startswith("+"):
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
Iustin Pop's avatar
Iustin Pop committed
192 193 194
  else:
    selected_fields = opts.output.split(",")

195
  output = GetClient().QueryInstances(args, selected_fields, opts.do_locking)
Iustin Pop's avatar
Iustin Pop committed
196 197

  if not opts.no_headers:
198 199 200
    headers = {
      "name": "Instance", "os": "OS", "pnode": "Primary_node",
      "snodes": "Secondary_Nodes", "admin_state": "Autostart",
Iustin Pop's avatar
Iustin Pop committed
201
      "oper_state": "Running",
202
      "oper_ram": "Memory", "disk_template": "Disk_template",
203
      "ip": "IP_address", "mac": "MAC_address",
204
      "nic_mode": "NIC_Mode", "nic_link": "NIC_Link",
Iustin Pop's avatar
Iustin Pop committed
205
      "bridge": "Bridge",
206
      "sda_size": "Disk/0", "sdb_size": "Disk/1",
207
      "disk_usage": "DiskUsage",
208
      "status": "Status", "tags": "Tags",
209
      "network_port": "Network_port",
210 211 212 213 214 215 216 217
      "hv/kernel_path": "Kernel_path",
      "hv/initrd_path": "Initrd_path",
      "hv/boot_order": "HVM_boot_order",
      "hv/acpi": "HVM_ACPI",
      "hv/pae": "HVM_PAE",
      "hv/cdrom_image_path": "HVM_CDROM_image_path",
      "hv/nic_type": "HVM_NIC_type",
      "hv/disk_type": "HVM_Disk_type",
218
      "hv/vnc_bind_address": "VNC_bind_address",
219
      "serial_no": "SerialNo", "hypervisor": "Hypervisor",
220
      "hvparams": "Hypervisor_parameters",
Iustin Pop's avatar
Iustin Pop committed
221 222
      "be/memory": "Configured_memory",
      "be/vcpus": "VCPUs",
223
      "vcpus": "VCPUs",
224
      "be/auto_balance": "Auto_balance",
Iustin Pop's avatar
Iustin Pop committed
225 226
      "disk.count": "Disks", "disk.sizes": "Disk_sizes",
      "nic.count": "NICs", "nic.ips": "NIC_IPs",
227
      "nic.modes": "NIC_modes", "nic.links": "NIC_links",
Iustin Pop's avatar
Iustin Pop committed
228
      "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
229
      }
230 231 232
  else:
    headers = None

233
  unitfields = ["be/memory", "oper_ram", "sd(a|b)_size", "disk\.size/.*"]
234
  numfields = ["be/memory", "oper_ram", "sd(a|b)_size", "be/vcpus",
Iustin Pop's avatar
Iustin Pop committed
235
               "serial_no", "(disk|nic)\.count", "disk\.size/.*"]
236

237 238
  list_type_fields = ("tags", "disk.sizes", "nic.macs", "nic.ips",
                      "nic.modes", "nic.links", "nic.bridges")
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  # change raw values to nicer strings
  for row in output:
    for idx, field in enumerate(selected_fields):
      val = row[idx]
      if field == "snodes":
        val = ",".join(val) or "-"
      elif field == "admin_state":
        if val:
          val = "yes"
        else:
          val = "no"
      elif field == "oper_state":
        if val is None:
          val = "(node down)"
        elif val: # True
          val = "running"
        else:
          val = "stopped"
      elif field == "oper_ram":
        if val is None:
          val = "(node down)"
      elif field == "sda_size" or field == "sdb_size":
        if val is None:
          val = "N/A"
263
      elif field in list_type_fields:
Iustin Pop's avatar
Iustin Pop committed
264
        val = ",".join(str(item) for item in val)
265 266
      elif val is None:
        val = "-"
267 268
      row[idx] = str(val)

269 270
  data = GenerateTable(separator=opts.separator, headers=headers,
                       fields=selected_fields, unitfields=unitfields,
271
                       numfields=numfields, data=output, units=opts.units)
272 273

  for line in data:
274
    ToStdout(line)
Iustin Pop's avatar
Iustin Pop committed
275 276 277 278 279 280 281

  return 0


def AddInstance(opts, args):
  """Add an instance to the cluster.

282 283 284 285 286
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the new instance name
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
287 288 289 290

  """
  instance = args[0]

291 292
  (pnode, snode) = SplitNodeOption(opts.node)

293 294 295 296
  hypervisor = None
  hvparams = {}
  if opts.hypervisor:
    hypervisor, hvparams = opts.hypervisor
297

298 299 300 301 302 303
  if opts.nics:
    try:
      nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
    except ValueError, err:
      raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
    nics = [{}] * nic_max
304
    for nidx, ndict in opts.nics:
305
      nidx = int(nidx)
306 307 308
      if not isinstance(ndict, dict):
        msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
        raise errors.OpPrereqError(msg)
309
      nics[nidx] = ndict
Iustin Pop's avatar
Iustin Pop committed
310 311 312
  elif opts.no_nics:
    # no nics
    nics = []
313 314 315 316
  else:
    # default of one nic, all auto
    nics = [{}]

Iustin Pop's avatar
Iustin Pop committed
317
  if opts.disk_template == constants.DT_DISKLESS:
318
    if opts.disks or opts.sd_size is not None:
Iustin Pop's avatar
Iustin Pop committed
319 320 321
      raise errors.OpPrereqError("Diskless instance but disk"
                                 " information passed")
    disks = []
322
  else:
323
    if not opts.disks and not opts.sd_size:
Iustin Pop's avatar
Iustin Pop committed
324
      raise errors.OpPrereqError("No disk information specified")
325 326 327 328 329
    if opts.disks and opts.sd_size is not None:
      raise errors.OpPrereqError("Please use either the '--disk' or"
                                 " '-s' option")
    if opts.sd_size is not None:
      opts.disks = [(0, {"size": opts.sd_size})]
330 331 332 333 334 335 336
    try:
      disk_max = max(int(didx[0])+1 for didx in opts.disks)
    except ValueError, err:
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
    disks = [{}] * disk_max
    for didx, ddict in opts.disks:
      didx = int(didx)
337 338 339 340
      if not isinstance(ddict, dict):
        msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
        raise errors.OpPrereqError(msg)
      elif "size" not in ddict:
341 342 343 344 345 346 347 348
        raise errors.OpPrereqError("Missing size for disk %d" % didx)
      try:
        ddict["size"] = utils.ParseUnit(ddict["size"])
      except ValueError, err:
        raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
                                   (didx, err))
      disks[didx] = ddict

349
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
350
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
351

Iustin Pop's avatar
Iustin Pop committed
352
  op = opcodes.OpCreateInstance(instance_name=instance,
353
                                disks=disks,
Iustin Pop's avatar
Iustin Pop committed
354
                                disk_template=opts.disk_template,
355
                                nics=nics,
Iustin Pop's avatar
Iustin Pop committed
356
                                mode=constants.INSTANCE_CREATE,
357
                                os_type=opts.os, pnode=pnode,
Iustin Pop's avatar
Iustin Pop committed
358
                                snode=snode,
359
                                start=opts.start, ip_check=opts.ip_check,
360
                                wait_for_sync=opts.wait_for_sync,
361 362
                                hypervisor=hypervisor,
                                hvparams=hvparams,
Iustin Pop's avatar
Iustin Pop committed
363
                                beparams=opts.beparams,
364
                                iallocator=opts.iallocator,
365 366
                                file_storage_dir=opts.file_storage_dir,
                                file_driver=opts.file_driver,
367
                                )
368

369
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
370 371 372
  return 0


373
def BatchCreate(opts, args):
374 375 376 377 378 379
  """Create instances using a definition file.

  This function reads a json file with instances defined
  in the form::

    {"instance-name":{
380
      "disk_size": [20480],
381 382 383 384
      "template": "drbd",
      "backend": {
        "memory": 512,
        "vcpus": 1 },
385
      "os": "debootstrap",
386 387 388 389 390 391 392 393 394 395 396 397 398
      "primary_node": "firstnode",
      "secondary_node": "secondnode",
      "iallocator": "dumb"}
    }

  Note that I{primary_node} and I{secondary_node} have precedence over
  I{iallocator}.

  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain one element, the json filename
  @rtype: int
  @return: the desired exit code
399 400

  """
401
  _DEFAULT_SPECS = {"disk_size": [20 * 1024],
402 403 404 405
                    "backend": {},
                    "iallocator": None,
                    "primary_node": None,
                    "secondary_node": None,
406
                    "nics": None,
407 408 409
                    "start": True,
                    "ip_check": True,
                    "hypervisor": None,
Iustin Pop's avatar
Iustin Pop committed
410
                    "hvparams": {},
411 412 413 414 415
                    "file_storage_dir": None,
                    "file_driver": 'loop'}

  def _PopulateWithDefaults(spec):
    """Returns a new hash combined with default values."""
416 417 418
    mydict = _DEFAULT_SPECS.copy()
    mydict.update(spec)
    return mydict
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

  def _Validate(spec):
    """Validate the instance specs."""
    # Validate fields required under any circumstances
    for required_field in ('os', 'template'):
      if required_field not in spec:
        raise errors.OpPrereqError('Required field "%s" is missing.' %
                                   required_field)
    # Validate special fields
    if spec['primary_node'] is not None:
      if (spec['template'] in constants.DTS_NET_MIRROR and
          spec['secondary_node'] is None):
        raise errors.OpPrereqError('Template requires secondary node, but'
                                   ' there was no secondary provided.')
    elif spec['iallocator'] is None:
      raise errors.OpPrereqError('You have to provide at least a primary_node'
                                 ' or an iallocator.')

Iustin Pop's avatar
Iustin Pop committed
437 438
    if (spec['hvparams'] and
        not isinstance(spec['hvparams'], dict)):
439 440 441 442
      raise errors.OpPrereqError('Hypervisor parameters must be a dict.')

  json_filename = args[0]
  try:
Iustin Pop's avatar
Iustin Pop committed
443
    fd = open(json_filename, 'r')
444 445
    instance_data = simplejson.load(fd)
    fd.close()
Iustin Pop's avatar
Iustin Pop committed
446 447 448
  except Exception, err:
    ToStderr("Can't parse the instance definition file: %s" % str(err))
    return 1
449

450 451
  jex = JobExecutor()

452 453 454
  # Iterate over the instances and do:
  #  * Populate the specs with default value
  #  * Validate the instance specs
455 456 457
  i_names = utils.NiceSort(instance_data.keys())
  for name in i_names:
    specs = instance_data[name]
458 459 460
    specs = _PopulateWithDefaults(specs)
    _Validate(specs)

Iustin Pop's avatar
Iustin Pop committed
461 462
    hypervisor = specs['hypervisor']
    hvparams = specs['hvparams']
463

464 465 466 467 468 469 470 471 472 473
    disks = []
    for elem in specs['disk_size']:
      try:
        size = utils.ParseUnit(elem)
      except ValueError, err:
        raise errors.OpPrereqError("Invalid disk size '%s' for"
                                   " instance %s: %s" %
                                   (elem, name, err))
      disks.append({"size": size})

474 475 476
    utils.ForceDictType(specs['backend'], constants.BES_PARAMETER_TYPES)
    utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)

477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
    tmp_nics = []
    for field in ('ip', 'mac', 'mode', 'link', 'bridge'):
      if field in specs:
        if not tmp_nics:
          tmp_nics.append({})
        tmp_nics[0][field] = specs[field]

    if specs['nics'] is not None and tmp_nics:
      raise errors.OpPrereqError("'nics' list incompatible with using"
                                 " individual nic fields as well")
    elif specs['nics'] is not None:
      tmp_nics = specs['nics']
    elif not tmp_nics:
      tmp_nics = [{}]

492
    op = opcodes.OpCreateInstance(instance_name=name,
493
                                  disks=disks,
494 495 496 497 498
                                  disk_template=specs['template'],
                                  mode=constants.INSTANCE_CREATE,
                                  os_type=specs['os'],
                                  pnode=specs['primary_node'],
                                  snode=specs['secondary_node'],
499
                                  nics=tmp_nics,
500 501 502 503 504 505 506 507 508 509
                                  start=specs['start'],
                                  ip_check=specs['ip_check'],
                                  wait_for_sync=True,
                                  iallocator=specs['iallocator'],
                                  hypervisor=hypervisor,
                                  hvparams=hvparams,
                                  beparams=specs['backend'],
                                  file_storage_dir=specs['file_storage_dir'],
                                  file_driver=specs['file_driver'])

510 511 512
    jex.QueueJob(name, op)
  # we never want to wait, just show the submitted job IDs
  jex.WaitOrShow(False)
513 514 515 516

  return 0


517 518 519
def ReinstallInstance(opts, args):
  """Reinstall an instance.

520 521 522 523 524 525
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the name of the
      instance to be reinstalled
  @rtype: int
  @return: the desired exit code
526 527

  """
528 529 530 531 532 533 534
  # first, compute the desired name list
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES

  inames = _ExpandMultiNames(opts.multi_mode, args)
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
535

536
  # second, if requested, ask for an OS
537 538 539 540 541
  if opts.select_os is True:
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
    result = SubmitOpCode(op)

    if not result:
542
      ToStdout("Can't get the OS list")
543 544
      return 1

545
    ToStdout("Available OS templates:")
546 547 548
    number = 0
    choices = []
    for entry in result:
549
      ToStdout("%3s: %s", number, entry[0])
550 551 552 553
      choices.append(("%s" % number, entry[0], entry[0]))
      number = number + 1

    choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
554
    selected = AskUser("Enter OS template number (or x to abort):",
555 556 557
                       choices)

    if selected == 'exit':
558
      ToStderr("User aborted reinstall, exiting")
559 560
      return 1

561
    os_name = selected
562
  else:
563
    os_name = opts.os
564

565 566 567 568 569 570 571
  # third, get confirmation: multi-reinstall requires --force-multi
  # *and* --force, single-reinstall just --force
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
  if multi_on:
    warn_msg = "Note: this will remove *all* data for the below instances!\n"
    if not ((opts.force_multi and opts.force) or
            _ConfirmOperation(inames, "reinstall", extra=warn_msg)):
572
      return 1
573 574 575
  else:
    if not opts.force:
      usertext = ("This will reinstall the instance %s and remove"
Iustin Pop's avatar
Iustin Pop committed
576
                  " all data. Continue?") % inames[0]
577 578 579 580 581 582 583 584
      if not AskUser(usertext):
        return 1

  jex = JobExecutor(verbose=multi_on)
  for instance_name in inames:
    op = opcodes.OpReinstallInstance(instance_name=instance_name,
                                     os_type=os_name)
    jex.QueueJob(instance_name, op)
585

586
  jex.WaitOrShow(not opts.submit_only)
587 588 589
  return 0


Iustin Pop's avatar
Iustin Pop committed
590 591 592
def RemoveInstance(opts, args):
  """Remove an instance.

593 594 595 596 597 598
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the name of
      the instance to be removed
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
599 600 601 602

  """
  instance_name = args[0]
  force = opts.force
603
  cl = GetClient()
Iustin Pop's avatar
Iustin Pop committed
604 605

  if not force:
606 607
    _EnsureInstancesExist(cl, [instance_name])

Iustin Pop's avatar
Iustin Pop committed
608 609 610
    usertext = ("This will remove the volumes of the instance %s"
                " (including mirrors), thus removing all the data"
                " of the instance. Continue?") % instance_name
611
    if not AskUser(usertext):
Iustin Pop's avatar
Iustin Pop committed
612 613
      return 1

Iustin Pop's avatar
Iustin Pop committed
614 615
  op = opcodes.OpRemoveInstance(instance_name=instance_name,
                                ignore_failures=opts.ignore_failures)
616
  SubmitOrSend(op, opts, cl=cl)
Iustin Pop's avatar
Iustin Pop committed
617 618 619
  return 0


620
def RenameInstance(opts, args):
Guido Trotter's avatar
Guido Trotter committed
621
  """Rename an instance.
622

623 624 625 626 627 628
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain two elements, the old and the
      new instance names
  @rtype: int
  @return: the desired exit code
629 630 631 632 633

  """
  op = opcodes.OpRenameInstance(instance_name=args[0],
                                new_name=args[1],
                                ignore_ip=opts.ignore_ip)
634
  SubmitOrSend(op, opts)
635 636 637
  return 0


Iustin Pop's avatar
Iustin Pop committed
638 639 640 641
def ActivateDisks(opts, args):
  """Activate an instance's disks.

  This serves two purposes:
642 643
    - it allows (as long as the instance is not running)
      mounting the disks and modifying them from the node
Iustin Pop's avatar
Iustin Pop committed
644 645
    - it repairs inactive secondary drbds

646 647 648 649 650 651
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code

Iustin Pop's avatar
Iustin Pop committed
652 653 654
  """
  instance_name = args[0]
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
655
  disks_info = SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
656
  for host, iname, nname in disks_info:
657
    ToStdout("%s:%s:%s", host, iname, nname)
Iustin Pop's avatar
Iustin Pop committed
658 659 660 661
  return 0


def DeactivateDisks(opts, args):
662
  """Deactivate an instance's disks..
Iustin Pop's avatar
Iustin Pop committed
663 664 665 666

  This function takes the instance name, looks for its primary node
  and the tries to shutdown its block devices on that node.

667 668 669 670 671 672
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code

Iustin Pop's avatar
Iustin Pop committed
673 674 675
  """
  instance_name = args[0]
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
676
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
677 678 679
  return 0


Iustin Pop's avatar
Iustin Pop committed
680
def GrowDisk(opts, args):
681
  """Grow an instance's disks.
Iustin Pop's avatar
Iustin Pop committed
682

683 684 685 686 687 688
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain two elements, the instance name
      whose disks we grow and the disk name, e.g. I{sda}
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
689 690 691 692

  """
  instance = args[0]
  disk = args[1]
693 694 695 696
  try:
    disk = int(disk)
  except ValueError, err:
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err))
Iustin Pop's avatar
Iustin Pop committed
697
  amount = utils.ParseUnit(args[2])
698 699
  op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
                          wait_for_sync=opts.wait_for_sync)
700
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
701 702 703
  return 0


Iustin Pop's avatar
Iustin Pop committed
704
def StartupInstance(opts, args):
705
  """Startup instances.
Iustin Pop's avatar
Iustin Pop committed
706

707 708 709 710 711 712 713 714 715 716
  Depending on the options given, this will start one or more
  instances.

  @param opts: the command line options selected by the user
  @type args: list
  @param args: the instance or node names based on which we
      create the final selection (in conjunction with the
      opts argument)
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
717 718

  """
719
  cl = GetClient()
720 721
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
722
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
723 724
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
725 726 727 728
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
  if not (opts.force_multi or not multi_on
          or _ConfirmOperation(inames, "startup")):
    return 1
729
  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
730 731
  for name in inames:
    op = opcodes.OpStartupInstance(instance_name=name,
732
                                   force=opts.force)
733 734 735 736 737
    # do not add these parameters to the opcode unless they're defined
    if opts.hvparams:
      op.hvparams = opts.hvparams
    if opts.beparams:
      op.beparams = opts.beparams
738 739
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
Iustin Pop's avatar
Iustin Pop committed
740 741
  return 0

742

743
def RebootInstance(opts, args):
744 745 746 747
  """Reboot instance(s).

  Depending on the parameters given, this will reboot one or more
  instances.
748

749 750 751 752 753 754 755
  @param opts: the command line options selected by the user
  @type args: list
  @param args: the instance or node names based on which we
      create the final selection (in conjunction with the
      opts argument)
  @rtype: int
  @return: the desired exit code
756 757

  """
758
  cl = GetClient()
759 760
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
761
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
762 763
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
764 765 766 767
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
  if not (opts.force_multi or not multi_on
          or _ConfirmOperation(inames, "reboot")):
    return 1
768
  jex = JobExecutor(verbose=multi_on, cl=cl)
769 770 771 772
  for name in inames:
    op = opcodes.OpRebootInstance(instance_name=name,
                                  reboot_type=opts.reboot_type,
                                  ignore_secondaries=opts.ignore_secondaries)
773 774
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
775
  return 0
Iustin Pop's avatar
Iustin Pop committed
776

777

Iustin Pop's avatar
Iustin Pop committed
778 779 780
def ShutdownInstance(opts, args):
  """Shutdown an instance.

781 782 783 784 785 786 787
  @param opts: the command line options selected by the user
  @type args: list
  @param args: the instance or node names based on which we
      create the final selection (in conjunction with the
      opts argument)
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
788 789

  """
790
  cl = GetClient()
791 792
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
793
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
794 795
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
796 797 798 799
  multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
  if not (opts.force_multi or not multi_on
          or _ConfirmOperation(inames, "shutdown")):
    return 1
800 801

  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
802 803
  for name in inames:
    op = opcodes.OpShutdownInstance(instance_name=name)
804 805
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
Iustin Pop's avatar
Iustin Pop committed
806 807 808 809 810 811
  return 0


def ReplaceDisks(opts, args):
  """Replace the disks of an instance

812 813 814 815 816
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
817 818 819

  """
  instance_name = args[0]
820
  new_2ndary = opts.new_secondary
821
  iallocator = opts.iallocator
822
  if opts.disks is None:
823
    disks = []
824
  else:
825 826 827 828
    try:
      disks = [int(i) for i in opts.disks.split(",")]
    except ValueError, err:
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
829 830 831 832 833 834
  cnt = [opts.on_primary, opts.on_secondary,
         new_2ndary is not None, iallocator is not None].count(True)
  if cnt != 1:
    raise errors.OpPrereqError("One and only one of the -p, -s, -n and -i"
                               " options must be passed")
  elif opts.on_primary:
835
    mode = constants.REPLACE_DISK_PRI
836
  elif opts.on_secondary:
837
    mode = constants.REPLACE_DISK_SEC
838 839 840
  elif new_2ndary is not None or iallocator is not None:
    # replace secondary
    mode = constants.REPLACE_DISK_CHG
841 842

  op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
843 844
                              remote_node=new_2ndary, mode=mode,
                              iallocator=iallocator)
845
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
846 847 848 849 850 851 852 853 854
  return 0


def FailoverInstance(opts, args):
  """Failover an instance.

  The failover is done by shutting it down on its present node and
  starting it on the secondary.

855 856 857 858 859
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
860 861

  """
862
  cl = GetClient()
863 864
  instance_name = args[0]
  force = opts.force
Iustin Pop's avatar
Iustin Pop committed
865

866
  if not force:
867 868
    _EnsureInstancesExist(cl, [instance_name])

869 870 871 872 873
    usertext = ("Failover will happen to image %s."
                " This requires a shutdown of the instance. Continue?" %
                (instance_name,))
    if not AskUser(usertext):
      return 1
Iustin Pop's avatar
Iustin Pop committed
874

875 876
  op = opcodes.OpFailoverInstance(instance_name=instance_name,
                                  ignore_consistency=opts.ignore_consistency)
877
  SubmitOrSend(op, opts, cl=cl)
878
  return 0
Iustin Pop's avatar
Iustin Pop committed
879 880


881 882 883 884 885
def MigrateInstance(opts, args):
  """Migrate an instance.

  The migrate is done without shutdown.

Iustin Pop's avatar
Iustin Pop committed
886 887 888 889 890
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code
891 892

  """
893
  cl = GetClient()
894 895 896 897
  instance_name = args[0]
  force = opts.force

  if not force:
898 899
    _EnsureInstancesExist(cl, [instance_name])

900 901 902 903 904 905 906 907 908 909 910 911 912 913 914
    if opts.cleanup:
      usertext = ("Instance %s will be recovered from a failed migration."
                  " Note that the migration procedure (including cleanup)" %
                  (instance_name,))
    else:
      usertext = ("Instance %s will be migrated. Note that migration" %
                  (instance_name,))
    usertext += (" is **experimental** in this version."
                " This might impact the instance if anything goes wrong."
                " Continue?")
    if not AskUser(usertext):
      return 1

  op = opcodes.OpMigrateInstance(instance_name=instance_name, live=opts.live,
                                 cleanup=opts.cleanup)
915
  SubmitOpCode(op, cl=cl)
916 917 918
  return 0


Iustin Pop's avatar
Iustin Pop committed
919 920 921
def ConnectToInstanceConsole(opts, args):
  """Connect to the console of an instance.

922 923 924 925 926
  @param opts: the command line options selected by the user
  @type args: list
  @param args: should contain only one element, the instance name
  @rtype: int
  @return: the desired exit code
Iustin Pop's avatar
Iustin Pop committed
927 928 929 930 931

  """
  instance_name = args[0]

  op = opcodes.OpConnectConsole(instance_name=instance_name)
932
  cmd = SubmitOpCode(op)
933 934

  if opts.show_command:
935
    ToStdout("%s", utils.ShellQuoteArgs(cmd))
936 937 938 939
  else:
    try:
      os.execvp(cmd[0], cmd)
    finally:
940
      ToStderr("Can't run console command %s with arguments:\n'%s'",
941
               cmd[0], " ".join(cmd))
942
      os._exit(1)
Iustin Pop's avatar
Iustin Pop committed
943 944


945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966
def _FormatLogicalID(dev_type, logical_id):
  """Formats the logical_id of a disk.

  """
  if dev_type == constants.LD_DRBD8:
    node_a, node_b, port, minor_a, minor_b, key = logical_id
    data = [
      ("nodeA", "%s, minor=%s" % (node_a, minor_a)),
      ("nodeB", "%s, minor=%s" % (node_b, minor_b)),
      ("port", port),
      ("auth key", key),
      ]
  elif dev_type == constants.LD_LV:
    vg_name, lv_name = logical_id
    data = ["%s/%s" % (vg_name, lv_name)]
  else:
    data = [str(logical_id)]

  return data


def _FormatBlockDevInfo(idx, top_level, dev, static):
Iustin Pop's avatar
Iustin Pop committed
967 968
  """Show block device information.

969
  This is only used by L{ShowInstanceConfig}, but it's too big to be
Iustin Pop's avatar
Iustin Pop committed
970 971
  left for an inline definition.

972 973 974 975
  @type idx: int
  @param idx: the index of the current disk
  @type top_level: boolean
  @param top_level: if this a top-level disk?
976 977 978 979 980
  @type dev: dict
  @param dev: dictionary with disk information
  @type static: boolean
  @param static: wheter the device information doesn't contain
      runtime information but only static data
981 982
  @return: a list of either strings, tuples or lists
      (which should be formatted at a higher indent level)
983

Iustin Pop's avatar
Iustin Pop committed
984
  """
985
  def helper(dtype, status):
986 987 988 989 990 991
    """Format one line for physical device status.

    @type dtype: str
    @param dtype: a constant from the L{constants.LDS_BLOCK} set
    @type status: tuple
    @param status: a tuple as returned from L{backend.FindBlockDevice}
992
    @return: the string representing the status
993 994

    """
Iustin Pop's avatar
Iustin Pop committed
995
    if not status:
996 997
      return "not active"
    txt = ""
998
    (path, major, minor, syncp, estt, degr, ldisk_status) = status
999 1000
    if major is None:
      m