gnt-instance 52.8 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
120
121
122
123
124
def _ConfirmOperation(inames, text):
  """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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152

  """
  count = len(inames)
  msg = ("The %s will operate on %d instances.\n"
         "Do you want to continue?" % (text, count))
  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
163
164
165
166
167
168
169
170
171
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.

  @type client: L{luxi.Client}
  @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",
Iustin Pop's avatar
Iustin Pop committed
204
      "bridge": "Bridge",
205
      "sda_size": "Disk/0", "sdb_size": "Disk/1",
206
      "disk_usage": "DiskUsage",
207
      "status": "Status", "tags": "Tags",
208
      "network_port": "Network_port",
209
210
211
212
213
214
215
216
      "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",
217
      "hv/vnc_bind_address": "VNC_bind_address",
218
      "serial_no": "SerialNo", "hypervisor": "Hypervisor",
219
      "hvparams": "Hypervisor_parameters",
Iustin Pop's avatar
Iustin Pop committed
220
221
      "be/memory": "Configured_memory",
      "be/vcpus": "VCPUs",
222
      "be/auto_balance": "Auto_balance",
Iustin Pop's avatar
Iustin Pop committed
223
224
225
      "disk.count": "Disks", "disk.sizes": "Disk_sizes",
      "nic.count": "NICs", "nic.ips": "NIC_IPs",
      "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
226
      }
227
228
229
  else:
    headers = None

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

Iustin Pop's avatar
Iustin Pop committed
234
235
  list_type_fields = ("tags", "disk.sizes",
                      "nic.macs", "nic.ips", "nic.bridges")
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
  # 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"
260
      elif field in list_type_fields:
Iustin Pop's avatar
Iustin Pop committed
261
        val = ",".join(str(item) for item in val)
262
263
      elif val is None:
        val = "-"
264
265
      row[idx] = str(val)

266
267
  data = GenerateTable(separator=opts.separator, headers=headers,
                       fields=selected_fields, unitfields=unitfields,
268
                       numfields=numfields, data=output, units=opts.units)
269
270

  for line in data:
271
    ToStdout(line)
Iustin Pop's avatar
Iustin Pop committed
272
273
274
275
276
277
278

  return 0


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

279
280
281
282
283
  @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
284
285
286
287

  """
  instance = args[0]

288
289
  (pnode, snode) = SplitNodeOption(opts.node)

290
291
292
293
  hypervisor = None
  hvparams = {}
  if opts.hypervisor:
    hypervisor, hvparams = opts.hypervisor
294

295
296
297
298
299
300
  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
301
    for nidx, ndict in opts.nics:
302
303
      nidx = int(nidx)
      nics[nidx] = ndict
Iustin Pop's avatar
Iustin Pop committed
304
305
306
  elif opts.no_nics:
    # no nics
    nics = []
307
308
309
310
  else:
    # default of one nic, all auto
    nics = [{}]

Iustin Pop's avatar
Iustin Pop committed
311
  if opts.disk_template == constants.DT_DISKLESS:
312
    if opts.disks or opts.sd_size is not None:
Iustin Pop's avatar
Iustin Pop committed
313
314
315
      raise errors.OpPrereqError("Diskless instance but disk"
                                 " information passed")
    disks = []
316
  else:
317
    if not opts.disks and not opts.sd_size:
Iustin Pop's avatar
Iustin Pop committed
318
      raise errors.OpPrereqError("No disk information specified")
319
320
321
322
323
    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})]
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
    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)
      if "size" not in ddict:
        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

340
  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
341
  utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
342

Iustin Pop's avatar
Iustin Pop committed
343
  op = opcodes.OpCreateInstance(instance_name=instance,
344
                                disks=disks,
Iustin Pop's avatar
Iustin Pop committed
345
                                disk_template=opts.disk_template,
346
                                nics=nics,
Iustin Pop's avatar
Iustin Pop committed
347
                                mode=constants.INSTANCE_CREATE,
348
                                os_type=opts.os, pnode=pnode,
Iustin Pop's avatar
Iustin Pop committed
349
                                snode=snode,
350
                                start=opts.start, ip_check=opts.ip_check,
351
                                wait_for_sync=opts.wait_for_sync,
352
353
                                hypervisor=hypervisor,
                                hvparams=hvparams,
Iustin Pop's avatar
Iustin Pop committed
354
                                beparams=opts.beparams,
355
                                iallocator=opts.iallocator,
356
357
                                file_storage_dir=opts.file_storage_dir,
                                file_driver=opts.file_driver,
358
                                )
359

360
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
361
362
363
  return 0


364
def BatchCreate(opts, args):
365
366
367
368
369
370
  """Create instances using a definition file.

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

    {"instance-name":{
371
      "disk_size": [20480],
372
373
374
375
      "template": "drbd",
      "backend": {
        "memory": 512,
        "vcpus": 1 },
376
      "os": "debootstrap",
377
378
379
380
381
382
383
384
385
386
387
388
389
      "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
390
391

  """
392
  _DEFAULT_SPECS = {"disk_size": [20 * 1024],
393
394
395
396
397
398
399
400
401
402
                    "backend": {},
                    "iallocator": None,
                    "primary_node": None,
                    "secondary_node": None,
                    "ip": 'none',
                    "mac": 'auto',
                    "bridge": None,
                    "start": True,
                    "ip_check": True,
                    "hypervisor": None,
Iustin Pop's avatar
Iustin Pop committed
403
                    "hvparams": {},
404
405
406
407
408
                    "file_storage_dir": None,
                    "file_driver": 'loop'}

  def _PopulateWithDefaults(spec):
    """Returns a new hash combined with default values."""
409
410
411
    mydict = _DEFAULT_SPECS.copy()
    mydict.update(spec)
    return mydict
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429

  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
430
431
    if (spec['hvparams'] and
        not isinstance(spec['hvparams'], dict)):
432
433
434
435
      raise errors.OpPrereqError('Hypervisor parameters must be a dict.')

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

  # Iterate over the instances and do:
  #  * Populate the specs with default value
  #  * Validate the instance specs
446
447
448
  i_names = utils.NiceSort(instance_data.keys())
  for name in i_names:
    specs = instance_data[name]
449
450
451
    specs = _PopulateWithDefaults(specs)
    _Validate(specs)

Iustin Pop's avatar
Iustin Pop committed
452
453
    hypervisor = specs['hypervisor']
    hvparams = specs['hvparams']
454

455
456
457
458
459
460
461
462
463
464
465
466
    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})

    nic0 = {'ip': specs['ip'], 'bridge': specs['bridge'], 'mac': specs['mac']}

467
468
469
    utils.ForceDictType(specs['backend'], constants.BES_PARAMETER_TYPES)
    utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)

470
    op = opcodes.OpCreateInstance(instance_name=name,
471
                                  disks=disks,
472
473
474
475
476
                                  disk_template=specs['template'],
                                  mode=constants.INSTANCE_CREATE,
                                  os_type=specs['os'],
                                  pnode=specs['primary_node'],
                                  snode=specs['secondary_node'],
477
                                  nics=[nic0],
478
479
480
481
482
483
484
485
486
487
                                  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'])

488
    ToStdout("%s: %s", name, cli.SendJob([op]))
489
490
491
492

  return 0


493
494
495
def ReinstallInstance(opts, args):
  """Reinstall an instance.

496
497
498
499
500
501
  @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
502
503
504
505

  """
  instance_name = args[0]

506
507
508
509
510
  if opts.select_os is True:
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
    result = SubmitOpCode(op)

    if not result:
511
      ToStdout("Can't get the OS list")
512
513
      return 1

514
    ToStdout("Available OS templates:")
515
516
517
    number = 0
    choices = []
    for entry in result:
518
      ToStdout("%3s: %s", number, entry[0])
519
520
521
522
      choices.append(("%s" % number, entry[0], entry[0]))
      number = number + 1

    choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
523
    selected = AskUser("Enter OS template number (or x to abort):",
524
525
526
                       choices)

    if selected == 'exit':
527
      ToStdout("User aborted reinstall, exiting")
528
529
      return 1

530
    os_name = selected
531
  else:
532
    os_name = opts.os
533

534
  if not opts.force:
535
536
    usertext = ("This will reinstall the instance %s and remove"
                " all data. Continue?") % instance_name
537
    if not AskUser(usertext):
538
539
      return 1

540
  op = opcodes.OpReinstallInstance(instance_name=instance_name,
541
                                   os_type=os_name)
542
  SubmitOrSend(op, opts)
543
544
545
546

  return 0


Iustin Pop's avatar
Iustin Pop committed
547
548
549
def RemoveInstance(opts, args):
  """Remove an instance.

550
551
552
553
554
555
  @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
556
557
558
559

  """
  instance_name = args[0]
  force = opts.force
560
  cl = GetClient()
Iustin Pop's avatar
Iustin Pop committed
561
562

  if not force:
563
564
    _EnsureInstancesExist(cl, [instance_name])

Iustin Pop's avatar
Iustin Pop committed
565
566
567
    usertext = ("This will remove the volumes of the instance %s"
                " (including mirrors), thus removing all the data"
                " of the instance. Continue?") % instance_name
568
    if not AskUser(usertext):
Iustin Pop's avatar
Iustin Pop committed
569
570
      return 1

Iustin Pop's avatar
Iustin Pop committed
571
572
  op = opcodes.OpRemoveInstance(instance_name=instance_name,
                                ignore_failures=opts.ignore_failures)
573
  SubmitOrSend(op, opts, cl=cl)
Iustin Pop's avatar
Iustin Pop committed
574
575
576
  return 0


577
def RenameInstance(opts, args):
Guido Trotter's avatar
Guido Trotter committed
578
  """Rename an instance.
579

580
581
582
583
584
585
  @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
586
587
588
589
590

  """
  op = opcodes.OpRenameInstance(instance_name=args[0],
                                new_name=args[1],
                                ignore_ip=opts.ignore_ip)
591
  SubmitOrSend(op, opts)
592
593
594
  return 0


Iustin Pop's avatar
Iustin Pop committed
595
596
597
598
def ActivateDisks(opts, args):
  """Activate an instance's disks.

  This serves two purposes:
599
600
    - 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
601
602
    - it repairs inactive secondary drbds

603
604
605
606
607
608
  @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
609
610
611
  """
  instance_name = args[0]
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
612
  disks_info = SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
613
  for host, iname, nname in disks_info:
614
    ToStdout("%s:%s:%s", host, iname, nname)
Iustin Pop's avatar
Iustin Pop committed
615
616
617
618
  return 0


def DeactivateDisks(opts, args):
619
  """Deactivate an instance's disks..
Iustin Pop's avatar
Iustin Pop committed
620
621
622
623

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

624
625
626
627
628
629
  @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
630
631
632
  """
  instance_name = args[0]
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
633
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
634
635
636
  return 0


Iustin Pop's avatar
Iustin Pop committed
637
def GrowDisk(opts, args):
638
  """Grow an instance's disks.
Iustin Pop's avatar
Iustin Pop committed
639

640
641
642
643
644
645
  @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
646
647
648
649

  """
  instance = args[0]
  disk = args[1]
650
651
652
653
  try:
    disk = int(disk)
  except ValueError, err:
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err))
Iustin Pop's avatar
Iustin Pop committed
654
  amount = utils.ParseUnit(args[2])
655
656
  op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
                          wait_for_sync=opts.wait_for_sync)
657
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
658
659
660
  return 0


Iustin Pop's avatar
Iustin Pop committed
661
def StartupInstance(opts, args):
662
  """Startup instances.
Iustin Pop's avatar
Iustin Pop committed
663

664
665
666
667
668
669
670
671
672
673
  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
674
675

  """
676
  cl = GetClient()
677
678
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
679
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
680
681
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
682
683
684
685
  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
686
  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
687
688
  for name in inames:
    op = opcodes.OpStartupInstance(instance_name=name,
689
                                   force=opts.force)
690
691
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
Iustin Pop's avatar
Iustin Pop committed
692
693
  return 0

694

695
def RebootInstance(opts, args):
696
697
698
699
  """Reboot instance(s).

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

701
702
703
704
705
706
707
  @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
708
709

  """
710
  cl = GetClient()
711
712
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
713
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
714
715
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
716
717
718
719
  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
720
  jex = JobExecutor(verbose=multi_on, cl=cl)
721
722
723
724
  for name in inames:
    op = opcodes.OpRebootInstance(instance_name=name,
                                  reboot_type=opts.reboot_type,
                                  ignore_secondaries=opts.ignore_secondaries)
725
726
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
727
  return 0
Iustin Pop's avatar
Iustin Pop committed
728

729

Iustin Pop's avatar
Iustin Pop committed
730
731
732
def ShutdownInstance(opts, args):
  """Shutdown an instance.

733
734
735
736
737
738
739
  @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
740
741

  """
742
  cl = GetClient()
743
744
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
745
  inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
746
747
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
748
749
750
751
  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
752
753

  jex = cli.JobExecutor(verbose=multi_on, cl=cl)
754
755
  for name in inames:
    op = opcodes.OpShutdownInstance(instance_name=name)
756
757
    jex.QueueJob(name, op)
  jex.WaitOrShow(not opts.submit_only)
Iustin Pop's avatar
Iustin Pop committed
758
759
760
761
762
763
  return 0


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

764
765
766
767
768
  @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
769
770
771

  """
  instance_name = args[0]
772
  new_2ndary = opts.new_secondary
773
  iallocator = opts.iallocator
774
  if opts.disks is None:
775
    disks = []
776
  else:
777
778
779
780
    try:
      disks = [int(i) for i in opts.disks.split(",")]
    except ValueError, err:
      raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
781
782
783
784
785
786
  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:
787
    mode = constants.REPLACE_DISK_PRI
788
  elif opts.on_secondary:
789
    mode = constants.REPLACE_DISK_SEC
790
791
792
  elif new_2ndary is not None or iallocator is not None:
    # replace secondary
    mode = constants.REPLACE_DISK_CHG
793
794

  op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
795
796
                              remote_node=new_2ndary, mode=mode,
                              iallocator=iallocator)
797
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
798
799
800
801
802
803
804
805
806
  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.

807
808
809
810
811
  @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
812
813

  """
814
  cl = GetClient()
815
816
  instance_name = args[0]
  force = opts.force
Iustin Pop's avatar
Iustin Pop committed
817

818
  if not force:
819
820
    _EnsureInstancesExist(cl, [instance_name])

821
822
823
824
825
    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
826

827
828
  op = opcodes.OpFailoverInstance(instance_name=instance_name,
                                  ignore_consistency=opts.ignore_consistency)
829
  SubmitOrSend(op, opts, cl=cl)
830
  return 0
Iustin Pop's avatar
Iustin Pop committed
831
832


833
834
835
836
837
def MigrateInstance(opts, args):
  """Migrate an instance.

  The migrate is done without shutdown.

Iustin Pop's avatar
Iustin Pop committed
838
839
840
841
842
  @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
843
844

  """
845
  cl = GetClient()
846
847
848
849
  instance_name = args[0]
  force = opts.force

  if not force:
850
851
    _EnsureInstancesExist(cl, [instance_name])

852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
    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)
867
  SubmitOpCode(op, cl=cl)
868
869
870
  return 0


Iustin Pop's avatar
Iustin Pop committed
871
872
873
def ConnectToInstanceConsole(opts, args):
  """Connect to the console of an instance.

874
875
876
877
878
  @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
879
880
881
882
883

  """
  instance_name = args[0]

  op = opcodes.OpConnectConsole(instance_name=instance_name)
884
  cmd = SubmitOpCode(op)
885
886

  if opts.show_command:
887
    ToStdout("%s", utils.ShellQuoteArgs(cmd))
888
889
890
891
  else:
    try:
      os.execvp(cmd[0], cmd)
    finally:
892
      ToStderr("Can't run console command %s with arguments:\n'%s'",
893
               cmd[0], " ".join(cmd))
894
      os._exit(1)
Iustin Pop's avatar
Iustin Pop committed
895
896


897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
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
919
920
  """Show block device information.

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

924
925
926
927
  @type idx: int
  @param idx: the index of the current disk
  @type top_level: boolean
  @param top_level: if this a top-level disk?
928
929
930
931
932
  @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
933
934
  @return: a list of either strings, tuples or lists
      (which should be formatted at a higher indent level)
935

Iustin Pop's avatar
Iustin Pop committed
936
  """
937
  def helper(dtype, status):
938
939
940
941
942
943
    """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}
944
    @return: the string representing the status
945
946

    """
Iustin Pop's avatar
Iustin Pop committed
947
    if not status:
948
949
950
951
952
      return "not active"
    txt = ""
    (path, major, minor, syncp, estt, degr, ldisk) = status
    if major is None:
      major_string = "N/A"
Iustin Pop's avatar
Iustin Pop committed
953
    else:
954
      major_string = str(major)
955

956
957
958
959
960
961
962
963
964
965
966
    if minor is None:
      minor_string = "N/A"
    else:
      minor_string = str(minor)

    txt += ("%s (%s:%s)" % (path, major_string, minor_string))
    if dtype in (constants.LD_DRBD8, ):
      if syncp is not None:
        sync_text = "*RECOVERING* %5.2f%%," % syncp
        if estt:
          sync_text += " ETA %ds" % estt
967
        else:
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
          sync_text += " ETA unknown"
      else:
        sync_text = "in sync"
      if degr:
        degr_text = "*DEGRADED*"
      else:
        degr_text = "ok"
      if ldisk:
        ldisk_text = " *MISSING DISK*"
      else:
        ldisk_text = ""
      txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
    elif dtype == constants.LD_LV:
      if ldisk:
        ldisk_text = " *FAILED* (failed drive?)"
      else:
        ldisk_text = ""
      txt += ldisk_text
    return txt

  # the header
  if top_level:
    if dev["iv_name"] is not None:
      txt = dev["iv_name"]
    else:
      txt = "disk %d" % idx
Iustin Pop's avatar
Iustin Pop committed
994
  else:
995
996
997
998
999
    txt = "child %d" % idx
  d1 = ["- %s: %s" % (txt, dev["dev_type"])]
  data = []
  if top_level:
    data.append(("access mode", dev["mode"]))
Iustin Pop's avatar
Iustin Pop committed
1000
  if dev["logical_id"] is not None:
1001
1002
1003
1004
1005
1006
1007
1008
    try:
      l_id = _FormatLogicalID(dev["dev_type"], dev["logical_id"])
    except ValueError:
      l_id = [str(dev["logical_id"])]
    if len(l_id) == 1:
      data.append(("logical_id", l_id[0]))
    else:
      data.extend(l_id)
Iustin Pop's avatar
Iustin Pop committed
1009
  elif dev["physical_id"] is not None:
1010
1011
    data.append("physical_id:")
    data.append([dev["physical_id"]])
1012
  if not static:
1013
    data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1014
  if dev["sstatus"] and not static:
1015
    data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
Iustin Pop's avatar
Iustin Pop committed
1016
1017

  if dev["children"]:
1018
1019
1020
1021
1022
    data.append("child devices:")
    for c_idx, child in enumerate(dev["children"]):
      data.append(_FormatBlockDevInfo(c_idx, False, child, static))
  d1.append(data)
  return d1
Iustin Pop's avatar
Iustin Pop committed
1023
1024


1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
def _FormatList(buf, data, indent_level):
  """Formats a list of data at a given indent level.

  If the element of the list is:
    - a string, it is simply formatted as is
    - a tuple, it will be split into key, value and the all the
      values in a list will be aligned all at the same start column
    - a list, will be recursively formatted

  @type buf: StringIO
  @param buf: the buffer into which we write the output
  @param data: the list to format
  @type indent_level: int
  @param indent_level: the indent level to format at

  """
  max_tlen = max([len(elem[0]) for elem in data
                 if isinstance(elem, tuple)] or [0])
  for elem in data:
    if isinstance(elem, basestring):
      buf.write("%*s%s\n" % (2*indent_level, "", elem))
    elif isinstance(elem, tuple):
      key, value = elem
      spacer = "%*s" % (max_tlen - len(key), "")
      buf.write("%*s%s:%s %s\n" % (2*indent_level, "", key, spacer, value))
    elif isinstance(elem, list):
      _FormatList(buf, elem, indent_level+1)

Iustin Pop's avatar
Iustin Pop committed
1053
1054
1055
def ShowInstanceConfig(opts, args):
  """Compute instance run-time status.

1056
1057
1058
1059
1060
1061
1062
  @param opts: the command line options selected by the user
  @type args: list
  @param args: either an empty list, and then we query all
      instances, or should contain a list of instance names
  @rtype: int
  @return: the desired exit code

Iustin Pop's avatar
Iustin Pop committed
1063
  """
Guido Trotter's avatar
Guido Trotter committed
1064
1065
1066
1067
1068
1069
1070
1071
1072
  if not args and not opts.show_all:
    ToStderr("No instance selected."
             " Please pass in --all if you want to query all instances.\n"
             "Note that this can take a long time on a big cluster.")
    return 1
  elif args and opts.show_all:
    ToStderr("Cannot use --all if you specify instance names.")
    return 1

Iustin Pop's avatar
Iustin Pop committed
1073
  retcode = 0
1074
  op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
Iustin Pop's avatar
Iustin Pop committed
1075
1076
  result = SubmitOpCode(op)
  if not result:
1077
    ToStdout("No instances.")
Iustin Pop's avatar
Iustin Pop committed
1078
1079
1080
1081
1082
1083
1084
    return 1

  buf = StringIO()
  retcode = 0
  for instance_name in result:
    instance = result[instance_name]
    buf.write("Instance name: %s\n" % instance["name"])
1085
1086
1087
1088
1089
1090
    buf.write("State: configured to be %s" % instance["config_state"])
    if not opts.static:
      buf.write(", actual state is %s" % instance["run_state"])
    buf.write("\n")
    ##buf.write("Considered for memory checks in cluster verify: %s\n" %
    ##          instance["auto_balance"])
Iustin Pop's avatar
Iustin Pop committed
1091
1092
1093
1094
    buf.write("  Nodes:\n")
    buf.write("    - primary: %s\n" % instance["pnode"])
    buf.write("    - secondaries: %s\n" % ", ".join(instance["snodes"]))
    buf.write("  Operating system: %s\n" % instance["os"])
1095
1096
    if instance.has_key("network_port"):
      buf.write("  Allocated network port: %s\n" % instance["network_port"])
1097
    buf.write("  Hypervisor: %s\n" % instance["hypervisor"])
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112

    # custom VNC console information
    vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS,
                                                 None)
    if vnc_bind_address:
      port = instance["network_port"]
      display = int(port) - constants.VNC_BASE_PORT
      if display > 0 and vnc_bind_address == constants.BIND_ADDRESS_GLOBAL:
        vnc_console_port = "%s:%s (display %s)" % (instance["pnode"],
                                                   port,
                                                   display)
      elif display > 0 and utils.IsValidIP(vnc_bind_address):
        vnc_console_port = ("%s:%s (node %s) (display %s)" %
                             (vnc_bind_address, port,
                              instance["pnode"], display))
1113
      else:
1114
1115
1116
        # vnc bind address is a file
        vnc_console_port = "%s:%s" % (instance["pnode"],
                                      vnc_bind_address)
1117
1118
      buf.write("    - console connection: vnc to %s\n" % vnc_console_port)

1119
    for key in instance["hv_actual"]:
1120
1121
      if key in instance["hv_instance"]:
        val = instance["hv_instance"][key]
1122
      else:
1123
        val = "default (%s)" % instance["hv_actual"][key]
1124
      buf.write("    - %s: %s\n" % (key, val))
Iustin Pop's avatar
Iustin Pop committed
1125
    buf.write("  Hardware:\n")
Iustin Pop's avatar
Iustin Pop committed
1126
1127
1128
1129
    buf.write("    - VCPUs: %d\n" %
              instance["be_actual"][constants.BE_VCPUS])
    buf.write("    - memory: %dMiB\n" %
              instance["be_actual"][constants.BE_MEMORY])
1130
1131
1132
1133
    buf.write("    - NICs:\n")
    for idx, (mac, ip, bridge) in enumerate(instance["nics"]):
      buf.write("      - nic/%d: MAC: %s, IP: %s, bridge: %s\n" %
                (idx, mac, ip, bridge))
1134
    buf.write("  Disks:\n")
Iustin Pop's avatar
Iustin Pop committed
1135

1136
1137
    for idx, device in enumerate(instance["disks"]):
      _FormatList(buf, _FormatBlockDevInfo(idx, True, device, opts.static), 2)
Iustin Pop's avatar
Iustin Pop committed
1138

1139
  ToStdout(buf.getvalue().rstrip('\n'))
Iustin Pop's avatar
Iustin Pop committed
1140
1141
1142
  return retcode


1143
def SetInstanceParams(opts, args):
Iustin Pop's avatar
Iustin Pop committed
1144
1145
1146
1147
  """Modifies an instance.

  All parameters take effect only at the next restart of the instance.

1148
1149
1150
1151
1152
  @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
1153
1154

  """
1155
  if not (opts.nics or opts.disks or
1156
          opts.hypervisor or opts.beparams):
1157
    ToStderr("Please give at least one of the parameters.")
Iustin Pop's avatar
Iustin Pop committed
1158
1159
    return 1

1160
  for param in opts.beparams:
1161
1162
1163
    if isinstance(opts.beparams[param], basestring):
      if opts.beparams[param].lower() == "default":
        opts.beparams[param] = constants.VALUE_DEFAULT
1164
1165
1166

  utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES,
                      allowed_values=[constants.VALUE_DEFAULT])
1167
1168

  for param in opts.hypervisor:
1169
1170
1171
    if isinstance(opts.hypervisor[param], basestring):
      if opts.hypervisor[param].lower() == "default":
        opts.hypervisor[param] = constants.VALUE_DEFAULT
1172
1173
1174

  utils.ForceDictType(opts.hypervisor, constants.HVS_PARAMETER_TYPES,
                      allowed_values=[constants.VALUE_DEFAULT])