gnt-instance 52 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
57
58
59
60
def _ExpandMultiNames(mode, names):
  """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
81
  """
  if mode == _SHUTDOWN_CLUSTER:
    if names:
      raise errors.OpPrereqError("Cluster filter mode takes no arguments")
82
83
    client = GetClient()
    idata = client.QueryInstances([], ["name"])
84
85
86
87
88
89
90
    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")
91
92
    client = GetClient()
    ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"])
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
    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")
109
110
    client = GetClient()
    idata = client.QueryInstances(names, ["name"])
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
172
173
174
175
176
177
178
179
def _TransformPath(user_input):
  """Transform a user path into a canonical value.

  This function transforms the a path passed as textual information
  into the constants that the LU code expects.

  """
  if user_input:
    if user_input.lower() == "default":
      result_path = constants.VALUE_DEFAULT
    elif user_input.lower() == "none":
      result_path = constants.VALUE_NONE
    else:
      if not os.path.isabs(user_input):
        raise errors.OpPrereqError("Path '%s' is not an absolute filename" %
                                   user_input)
      result_path = user_input
  else:
    result_path = constants.VALUE_DEFAULT

  return result_path


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

183
184
185
186
187
188
  @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
189
190
  """
  if opts.output is None:
191
192
193
    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
194
195
196
  else:
    selected_fields = opts.output.split(",")

197
  output = GetClient().QueryInstances([], selected_fields)
Iustin Pop's avatar
Iustin Pop committed
198
199

  if not opts.no_headers:
200
201
202
    headers = {
      "name": "Instance", "os": "OS", "pnode": "Primary_node",
      "snodes": "Secondary_Nodes", "admin_state": "Autostart",
Iustin Pop's avatar
Iustin Pop committed
203
      "oper_state": "Running",
204
      "oper_ram": "Memory", "disk_template": "Disk_template",
205
      "ip": "IP_address", "mac": "MAC_address",
Iustin Pop's avatar
Iustin Pop committed
206
      "bridge": "Bridge",
207
      "sda_size": "Disk/0", "sdb_size": "Disk/1",
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
      "be/auto_balance": "Auto_balance",
Iustin Pop's avatar
Iustin Pop committed
224
225
226
      "disk.count": "Disks", "disk.sizes": "Disk_sizes",
      "nic.count": "NICs", "nic.ips": "NIC_IPs",
      "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
227
      }
228
229
230
  else:
    headers = None

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

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

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

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

  return 0


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

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

  """
  instance = args[0]

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

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

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

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

336
  ValidateBeParams(opts.beparams)
Iustin Pop's avatar
Iustin Pop committed
337

338
339
##  kernel_path = _TransformPath(opts.kernel_path)
##  initrd_path = _TransformPath(opts.initrd_path)
340

341
342
343
344
345
346
347
348
##  hvm_acpi = opts.hvm_acpi == _VALUE_TRUE
##  hvm_pae = opts.hvm_pae == _VALUE_TRUE

##  if ((opts.hvm_cdrom_image_path is not None) and
##      (opts.hvm_cdrom_image_path.lower() == constants.VALUE_NONE)):
##    hvm_cdrom_image_path = None
##  else:
##    hvm_cdrom_image_path = opts.hvm_cdrom_image_path
349

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

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


371
def BatchCreate(opts, args):
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
  """Create instances using a definition file.

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

    {"instance-name":{
      "disk_size": 25,
      "swap_size": 1024,
      "template": "drbd",
      "backend": {
        "memory": 512,
        "vcpus": 1 },
      "os": "etch-image",
      "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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416

  """
  _DEFAULT_SPECS = {"disk_size": 20 * 1024,
                    "swap_size": 4 * 1024,
                    "backend": {},
                    "iallocator": None,
                    "primary_node": None,
                    "secondary_node": None,
                    "ip": 'none',
                    "mac": 'auto',
                    "bridge": None,
                    "start": True,
                    "ip_check": True,
                    "hypervisor": None,
                    "file_storage_dir": None,
                    "file_driver": 'loop'}

  def _PopulateWithDefaults(spec):
    """Returns a new hash combined with default values."""
417
418
419
    mydict = _DEFAULT_SPECS.copy()
    mydict.update(spec)
    return mydict
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480

  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.')

    if (spec['hypervisor'] and
        not isinstance(spec['hypervisor'], dict)):
      raise errors.OpPrereqError('Hypervisor parameters must be a dict.')

  json_filename = args[0]
  fd = open(json_filename, 'r')
  try:
    instance_data = simplejson.load(fd)
  finally:
    fd.close()

  # Iterate over the instances and do:
  #  * Populate the specs with default value
  #  * Validate the instance specs
  for (name, specs) in instance_data.iteritems():
    specs = _PopulateWithDefaults(specs)
    _Validate(specs)

    hypervisor = None
    hvparams = {}
    if specs['hypervisor']:
      hypervisor, hvparams = specs['hypervisor'].iteritems()

    op = opcodes.OpCreateInstance(instance_name=name,
                                  disk_size=specs['disk_size'],
                                  swap_size=specs['swap_size'],
                                  disk_template=specs['template'],
                                  mode=constants.INSTANCE_CREATE,
                                  os_type=specs['os'],
                                  pnode=specs['primary_node'],
                                  snode=specs['secondary_node'],
                                  ip=specs['ip'], bridge=specs['bridge'],
                                  start=specs['start'],
                                  ip_check=specs['ip_check'],
                                  wait_for_sync=True,
                                  mac=specs['mac'],
                                  iallocator=specs['iallocator'],
                                  hypervisor=hypervisor,
                                  hvparams=hvparams,
                                  beparams=specs['backend'],
                                  file_storage_dir=specs['file_storage_dir'],
                                  file_driver=specs['file_driver'])

481
    ToStdout("%s: %s", name, cli.SendJob([op]))
482
483
484
485

  return 0


486
487
488
def ReinstallInstance(opts, args):
  """Reinstall an instance.

489
490
491
492
493
494
  @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
495
496
497
498

  """
  instance_name = args[0]

499
500
501
502
503
  if opts.select_os is True:
    op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
    result = SubmitOpCode(op)

    if not result:
504
      ToStdout("Can't get the OS list")
505
506
      return 1

507
    ToStdout("Available OS templates:")
508
509
510
    number = 0
    choices = []
    for entry in result:
511
      ToStdout("%3s: %s", number, entry[0])
512
513
514
515
516
517
518
519
      choices.append(("%s" % number, entry[0], entry[0]))
      number = number + 1

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

    if selected == 'exit':
520
      ToStdout("User aborted reinstall, exiting")
521
522
      return 1

523
    os_name = selected
524
  else:
525
    os_name = opts.os
526

527
  if not opts.force:
528
529
    usertext = ("This will reinstall the instance %s and remove"
                " all data. Continue?") % instance_name
530
    if not AskUser(usertext):
531
532
      return 1

533
  op = opcodes.OpReinstallInstance(instance_name=instance_name,
534
                                   os_type=os_name)
535
  SubmitOrSend(op, opts)
536
537
538
539

  return 0


Iustin Pop's avatar
Iustin Pop committed
540
541
542
def RemoveInstance(opts, args):
  """Remove an instance.

543
544
545
546
547
548
  @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
549
550
551
552
553
554
555
556
557

  """
  instance_name = args[0]
  force = opts.force

  if not force:
    usertext = ("This will remove the volumes of the instance %s"
                " (including mirrors), thus removing all the data"
                " of the instance. Continue?") % instance_name
558
    if not AskUser(usertext):
Iustin Pop's avatar
Iustin Pop committed
559
560
      return 1

Iustin Pop's avatar
Iustin Pop committed
561
562
  op = opcodes.OpRemoveInstance(instance_name=instance_name,
                                ignore_failures=opts.ignore_failures)
563
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
564
565
566
  return 0


567
def RenameInstance(opts, args):
Guido Trotter's avatar
Guido Trotter committed
568
  """Rename an instance.
569

570
571
572
573
574
575
  @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
576
577
578
579
580

  """
  op = opcodes.OpRenameInstance(instance_name=args[0],
                                new_name=args[1],
                                ignore_ip=opts.ignore_ip)
581
  SubmitOrSend(op, opts)
582
583
584
  return 0


Iustin Pop's avatar
Iustin Pop committed
585
586
587
588
def ActivateDisks(opts, args):
  """Activate an instance's disks.

  This serves two purposes:
589
590
    - 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
591
592
    - it repairs inactive secondary drbds

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 instance name
  @rtype: int
  @return: the desired exit code

Iustin Pop's avatar
Iustin Pop committed
599
600
601
  """
  instance_name = args[0]
  op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
602
  disks_info = SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
603
  for host, iname, nname in disks_info:
604
    ToStdout("%s:%s:%s", host, iname, nname)
Iustin Pop's avatar
Iustin Pop committed
605
606
607
608
  return 0


def DeactivateDisks(opts, args):
609
  """Deactivate an instance's disks..
Iustin Pop's avatar
Iustin Pop committed
610
611
612
613

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

614
615
616
617
618
619
  @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
620
621
622
  """
  instance_name = args[0]
  op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
623
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
624
625
626
  return 0


Iustin Pop's avatar
Iustin Pop committed
627
def GrowDisk(opts, args):
628
  """Grow an instance's disks.
Iustin Pop's avatar
Iustin Pop committed
629

630
631
632
633
634
635
  @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
636
637
638
639

  """
  instance = args[0]
  disk = args[1]
640
641
642
643
  try:
    disk = int(disk)
  except ValueError, err:
    raise errors.OpPrereqError("Invalid disk index: %s" % str(err))
Iustin Pop's avatar
Iustin Pop committed
644
  amount = utils.ParseUnit(args[2])
645
646
  op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
                          wait_for_sync=opts.wait_for_sync)
647
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
648
649
650
  return 0


Iustin Pop's avatar
Iustin Pop committed
651
def StartupInstance(opts, args):
652
  """Startup instances.
Iustin Pop's avatar
Iustin Pop committed
653

654
655
656
657
658
659
660
661
662
663
  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
664
665

  """
666
667
668
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
  inames = _ExpandMultiNames(opts.multi_mode, args)
669
670
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
671
672
673
674
  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
675
676
677
678
679
  for name in inames:
    op = opcodes.OpStartupInstance(instance_name=name,
                                   force=opts.force,
                                   extra_args=opts.extra_args)
    if multi_on:
680
      ToStdout("Starting up %s", name)
681
682
683
684
    try:
      SubmitOrSend(op, opts)
    except JobSubmittedException, err:
      _, txt = FormatError(err)
685
      ToStdout("%s", txt)
Iustin Pop's avatar
Iustin Pop committed
686
687
  return 0

688

689
def RebootInstance(opts, args):
690
691
692
693
  """Reboot instance(s).

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

695
696
697
698
699
700
701
  @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
702
703
704
705
706

  """
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
  inames = _ExpandMultiNames(opts.multi_mode, args)
707
708
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
709
710
711
712
713
714
715
716
717
  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
  for name in inames:
    op = opcodes.OpRebootInstance(instance_name=name,
                                  reboot_type=opts.reboot_type,
                                  ignore_secondaries=opts.ignore_secondaries)

718
    SubmitOrSend(op, opts)
719
  return 0
Iustin Pop's avatar
Iustin Pop committed
720

721

Iustin Pop's avatar
Iustin Pop committed
722
723
724
def ShutdownInstance(opts, args):
  """Shutdown an instance.

725
726
727
728
729
730
731
  @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
732
733

  """
734
735
736
  if opts.multi_mode is None:
    opts.multi_mode = _SHUTDOWN_INSTANCES
  inames = _ExpandMultiNames(opts.multi_mode, args)
737
738
  if not inames:
    raise errors.OpPrereqError("Selection filter does not match any instances")
739
740
741
742
  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
743
744
745
  for name in inames:
    op = opcodes.OpShutdownInstance(instance_name=name)
    if multi_on:
746
      ToStdout("Shutting down %s", name)
747
748
749
750
    try:
      SubmitOrSend(op, opts)
    except JobSubmittedException, err:
      _, txt = FormatError(err)
751
      ToStdout("%s", txt)
Iustin Pop's avatar
Iustin Pop committed
752
753
754
755
756
757
  return 0


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

758
759
760
761
762
  @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
763
764
765

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

  op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
789
790
                              remote_node=new_2ndary, mode=mode,
                              iallocator=iallocator)
791
  SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
792
793
794
795
796
797
798
799
800
  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.

801
802
803
804
805
  @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
806
807

  """
808
809
  instance_name = args[0]
  force = opts.force
Iustin Pop's avatar
Iustin Pop committed
810

811
812
813
814
815
816
  if not force:
    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
817

818
819
  op = opcodes.OpFailoverInstance(instance_name=instance_name,
                                  ignore_consistency=opts.ignore_consistency)
820
  SubmitOrSend(op, opts)
821
  return 0
Iustin Pop's avatar
Iustin Pop committed
822
823


824
825
826
827
828
def MigrateInstance(opts, args):
  """Migrate an instance.

  The migrate is done without shutdown.

Iustin Pop's avatar
Iustin Pop committed
829
830
831
832
833
  @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
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858

  """
  instance_name = args[0]
  force = opts.force

  if not force:
    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)
  SubmitOpCode(op)
  return 0


Iustin Pop's avatar
Iustin Pop committed
859
860
861
def ConnectToInstanceConsole(opts, args):
  """Connect to the console of an instance.

862
863
864
865
866
  @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
867
868
869
870
871

  """
  instance_name = args[0]

  op = opcodes.OpConnectConsole(instance_name=instance_name)
872
  cmd = SubmitOpCode(op)
873
874

  if opts.show_command:
875
    ToStdout("%s", utils.ShellQuoteArgs(cmd))
876
877
878
879
  else:
    try:
      os.execvp(cmd[0], cmd)
    finally:
880
      ToStderr("Can't run console command %s with arguments:\n'%s'",
881
               cmd[0], " ".join(cmd))
882
      os._exit(1)
Iustin Pop's avatar
Iustin Pop committed
883
884


885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
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
907
908
  """Show block device information.

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

912
913
914
915
  @type idx: int
  @param idx: the index of the current disk
  @type top_level: boolean
  @param top_level: if this a top-level disk?
916
917
918
919
920
  @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
921
922
  @return: a list of either strings, tuples or lists
      (which should be formatted at a higher indent level)
923

Iustin Pop's avatar
Iustin Pop committed
924
  """
925
  def helper(dtype, status):
926
927
928
929
930
931
    """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}
932
    @return: the string representing the status
933
934

    """
Iustin Pop's avatar
Iustin Pop committed
935
    if not status:
936
937
938
939
940
      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
941
    else:
942
      major_string = str(major)
943

944
945
946
947
948
949
950
951
952
953
954
    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
955
        else:
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
          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
982
  else:
983
984
985
986
987
    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
988
  if dev["logical_id"] is not None:
989
990
991
992
993
994
995
996
    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
997
  elif dev["physical_id"] is not None:
998
999
    data.append("physical_id:")
    data.append([dev["physical_id"]])
1000
  if not static:
1001
    data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1002
  if dev["sstatus"] and not static:
1003
    data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
Iustin Pop's avatar
Iustin Pop committed
1004
1005

  if dev["children"]:
1006
1007
1008
1009
1010
    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
1011
1012


1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
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
1041
1042
1043
def ShowInstanceConfig(opts, args):
  """Compute instance run-time status.

1044
1045
1046
1047
1048
1049
1050
  @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
1051
1052
  """
  retcode = 0
1053
  op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
Iustin Pop's avatar
Iustin Pop committed
1054
1055
  result = SubmitOpCode(op)
  if not result:
1056
    ToStdout("No instances.")
Iustin Pop's avatar
Iustin Pop committed
1057
1058
1059
1060
1061
1062
1063
    return 1

  buf = StringIO()
  retcode = 0
  for instance_name in result:
    instance = result[instance_name]
    buf.write("Instance name: %s\n" % instance["name"])
1064
1065
1066
1067
1068
1069
    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
1070
1071
1072
1073
    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"])
1074
1075
    if instance.has_key("network_port"):
      buf.write("  Allocated network port: %s\n" % instance["network_port"])
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
    buf.write("  Hypervisor: %s\n" % instance["hypervisor"])
    if instance["hypervisor"] == constants.HT_XEN_PVM:
      hvattrs = ((constants.HV_KERNEL_PATH, "kernel path"),
                 (constants.HV_INITRD_PATH, "initrd path"))
    elif instance["hypervisor"] == constants.HT_XEN_HVM:
      hvattrs = ((constants.HV_BOOT_ORDER, "boot order"),
                 (constants.HV_ACPI, "ACPI"),
                 (constants.HV_PAE, "PAE"),
                 (constants.HV_CDROM_IMAGE_PATH, "virtual CDROM"),
                 (constants.HV_NIC_TYPE, "NIC type"),
                 (constants.HV_DISK_TYPE, "Disk type"),
                 (constants.HV_VNC_BIND_ADDRESS, "VNC bind address"),
                 )
      # custom console information for HVM
      vnc_bind_address = instance["hv_actual"][constants.HV_VNC_BIND_ADDRESS]
      if vnc_bind_address == constants.BIND_ADDRESS_GLOBAL:
        vnc_console_port = "%s:%s" % (instance["pnode"],
                                      instance["network_port"])
      elif vnc_bind_address == constants.LOCALHOST_IP_ADDRESS:
        vnc_console_port = "%s:%s on node %s" % (vnc_bind_address,
                                                 instance["network_port"],
                                                 instance["pnode"])
1098
      else:
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
        vnc_console_port = "%s:%s" % (vnc_bind_address,
                                      instance["network_port"])
      buf.write("    - console connection: vnc to %s\n" % vnc_console_port)

    else:
      # auto-handle other hypervisor types
      hvattrs = [(key, key) for key in instance["hv_actual"]]

    for key, desc in hvattrs:
      if key in instance["hv_instance"]:
        val = instance["hv_instance"][key]
1110
      else:
1111
1112
        val = "default (%s)" % instance["hv_actual"][key]
      buf.write("    - %s: %s\n" % (desc, val))
Iustin Pop's avatar
Iustin Pop committed
1113
    buf.write("  Hardware:\n")
Iustin Pop's avatar
Iustin Pop committed
1114
1115
1116
1117
    buf.write("    - VCPUs: %d\n" %
              instance["be_actual"][constants.BE_VCPUS])
    buf.write("    - memory: %dMiB\n" %
              instance["be_actual"][constants.BE_MEMORY])
1118
1119
1120
1121
    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))
1122
    buf.write("  Disks:\n")
Iustin Pop's avatar
Iustin Pop committed
1123

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

1127
  ToStdout(buf.getvalue().rstrip('\n'))
Iustin Pop's avatar
Iustin Pop committed
1128
1129
1130
  return retcode


1131
def SetInstanceParams(opts, args):
Iustin Pop's avatar
Iustin Pop committed
1132
1133
1134
1135
  """Modifies an instance.

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

1136
1137
1138
1139
1140
  @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
1141
1142

  """
1143
  if not (opts.nics or opts.disks or
1144
          opts.hypervisor or opts.beparams):
1145
    ToStderr("Please give at least one of the parameters.")
Iustin Pop's avatar
Iustin Pop committed
1146
1147
    return 1

1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
  for param in opts.beparams:
    if opts.beparams[param].lower() == "default":
      opts.beparams[param] = constants.VALUE_DEFAULT
    elif opts.beparams[param].lower() == "none":
      opts.beparams[param] = constants.VALUE_NONE
    elif param == constants.BE_MEMORY:
      opts.beparams[constants.BE_MEMORY] = \
        utils.ParseUnit(opts.beparams[constants.BE_MEMORY])

  for param in opts.hypervisor:
    if opts.hypervisor[param].lower() == "default":
      opts.hypervisor[param] = constants.VALUE_DEFAULT
    elif opts.hypervisor[param].lower() == "none":
      opts.hypervisor[param] = constants.VALUE_NONE
1162

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
  for idx, (nic_op, nic_dict) in enumerate(opts.nics):
    try:
      nic_op = int(nic_op)
      opts.nics[idx] = (nic_op, nic_dict)
    except ValueError:
      pass

  for idx, (disk_op, disk_dict) in enumerate(opts.disks):
    try:
      disk_op = int(disk_op)
      opts.disks[idx] = (disk_op, disk_dict)
    except ValueError:
      pass
    if disk_op == constants.DDM_ADD:
      if 'size' not in disk_dict:
        raise errors.OpPrereqError("Missing required parameter 'size'")
      disk_dict['size'] = utils.ParseUnit(disk_dict['size'])

Iustin Pop's avatar
Iustin Pop committed
1181
  op = opcodes.OpSetInstanceParams(instance_name=args[0],
1182
1183
                                   nics=opts.nics,
                                   disks=opts.disks,
1184
                                   hvparams=opts.hypervisor,
Iustin Pop's avatar
Iustin Pop committed
1185
                                   beparams=opts.beparams,
1186
                                   force=opts.force)
1187

1188
1189
  # even if here we process the result, we allow submit only
  result = SubmitOrSend(op, opts)
Iustin Pop's avatar
Iustin Pop committed
1190
1191

  if result:
1192
    ToStdout("Modified instance %s", args[0])
Iustin Pop's avatar
Iustin Pop committed
1193
    for param, data in result:
1194
1195
1196
      ToStdout(" - %-5s -> %s", param, data)
    ToStdout("Please don't forget that these parameters take effect"
             " only at the next start of the instance.")
Iustin Pop's avatar
Iustin Pop committed
1197
1198
1199
1200
1201
1202
1203
  return 0


# options used in more than one cmd
node_opt = make_option("-n", "--node", dest="node", help="Target node",
                       metavar="<node>")

1204
os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
Michael Hanselmann's avatar
Michael Hanselmann committed
1205
                    metavar="<os>")
1206

1207
# multi-instance selection options
1208
1209
1210
1211
1212
m_force_multi = make_option("--force-multiple", dest="force_multi",
                            help="Do not ask for confirmation when more than"
                            " one instance is affected",
                            action="store_true", default=False)

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
m_pri_node_opt = make_option("--primary", dest="multi_mode",
                             help="Filter by nodes (primary only)",
                             const=_SHUTDOWN_NODES_PRI, action="store_const")

m_sec_node_opt = make_option("--secondary", dest="multi_mode",
                             help="Filter by nodes (secondary only)",
                             const=_SHUTDOWN_NODES_SEC, action="store_const")

m_node_opt = make_option("--node", dest="multi_mode",
                         help="Filter by nodes (primary and secondary)",
                         const=_SHUTDOWN_NODES_BOTH, action="store_const")

m_clust_opt = make_option("--all", dest="multi_mode",
                          help="Select all instances in the cluster",
                          const=_SHUTDOWN_CLUSTER, action="store_const")

m_inst_opt = make_option("--instance", dest="multi_mode",
                         help="Filter by instance name [default]",
                         const=_SHUTDOWN_INSTANCES, action="store_const")


Iustin Pop's avatar
Iustin Pop committed
1234
1235
1236
# this is defined separately due to readability only
add_opts = [
  DEBUG_OPT,
1237
1238
1239
  make_option("-n", "--node", dest="node",
              help="Target node and optional secondary node",
              metavar="<pnode>[:<snode>]"),
1240
  os_opt,
Iustin Pop's avatar
Iustin Pop committed
1241
1242
1243
  keyval_option("-B", "--backend", dest="beparams",
                type="keyval", default={},
                help="Backend parameters"),
Iustin Pop's avatar
Iustin Pop committed
1244
  make_option("-t", "--disk-template", dest="disk_template",
1245
              help="Custom disk setup (diskless, file, plain or drbd)",
1246
              default=None, metavar="TEMPL"),
1247
1248
1249
1250
1251
1252
1253
1254
  ikv_option("--disk", help="Disk information",
             default=[], dest="disks",
             action="append",
             type="identkeyval"),
  ikv_option("--net", help="NIC information",
             default=[], dest="nics",
             action="append",
             type="identkeyval"),
Iustin Pop's avatar
Iustin Pop committed
1255
1256
  make_option("--no-nics", default=False, action="store_true",
              help="Do not create any network cards for the instance"),
Iustin Pop's avatar
Iustin Pop committed
1257
1258
  make_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
              action="store_false", help="Don't wait for sync (DANGEROUS!)"),
1259
1260
1261
1262
1263
1264
  make_option("--no-start", dest="start", default=True,
              action="store_false", help="Don't start the instance after"
              " creation"),
  make_option("--no-ip-check", dest="ip_check", default=True,
              action="store_false", help="Don't check that the instance's IP"
              " is alive (only valid with --no-start)"),
1265
1266
1267
1268
1269
  make_option("--file-storage-dir", dest="file_storage_dir",
              help="Relative path under default cluster-wide file storage dir"
              " to store file-based disks", default=None,
              metavar="<DIR>"),
  make_option("--file-driver", dest="file_driver", help="Driver to use"
1270
1271
1272
1273
              " for image files", default="loop", metavar="<DRIVER>"),
  make_option("--iallocator", metavar="<NAME>",
              help="Select nodes for the instance automatically using the"
              " <NAME> iallocator plugin", default=None, type="string"),
1274
1275
1276
1277
  ikv_option("-H", "--hypervisor", dest="hypervisor",
              help="Hypervisor and hypervisor options, in the format"
              " hypervisor:option=value,option=value,...", default=None,
              type="identkeyval"),
1278
  SUBMIT_OPT,
Iustin Pop's avatar
Iustin Pop committed
1279
1280
1281
1282
  ]

commands = {
  'add': (AddInstance, ARGS_ONE, add_opts,
1283
          "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
Iustin Pop's avatar
Iustin Pop committed
1284
          "Creates and adds a new instance to the cluster"),
1285
1286
1287
1288
  'batch-create': (BatchCreate, ARGS_ONE,
                   [DEBUG_OPT],
                   "<instances_file.json>",
                   "Create a bunch of instances based on specs in the file."),
1289
1290
1291
1292
1293
  'console': (ConnectToInstanceConsole, ARGS_ONE,
              [DEBUG_OPT,
               make_option("--show-cmd", dest="show_command",
                           action="store_true", default=False,
                           help=("Show command instead of executing it"))],
1294
              "[--show-cmd] <instance>",
Iustin Pop's avatar
Iustin Pop committed
1295
              "Opens a console on the specified instance"),
1296
  'failover': (FailoverInstance, ARGS_ONE,
1297
               [DEBUG_OPT, FORCE_OPT,
Iustin Pop's avatar
Iustin Pop committed
1298
1299
1300
1301
                make_option("--ignore-consistency", dest="ignore_consistency",
                            action="store_true", default=False,
                            help="Ignore the consistency of the disks on"
                            " the secondary"),
1302
                SUBMIT_OPT,
Iustin Pop's avatar
Iustin Pop committed
1303
                ],
1304
               "[-f] <instance>",
Iustin Pop's avatar
Iustin Pop committed
1305
               "Stops the instance and starts it on the backup node, using"
1306
               " the remote mirror (only for instances of type drbd)"),
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
  'migrate': (MigrateInstance, ARGS_ONE,
               [DEBUG_OPT, FORCE_OPT,
                make_option("--non-live", dest="live",
                            default=True, action="store_false",
                            help="Do a non-live migration (this usually means"
                            " freeze the instance, save the state,"
                            " transfer and only then resume running on the"
                            " secondary node)"),
                make_option("--cleanup", dest="cleanup",
                            default=False, action="store_true",
                            help="Instead of performing the migration, try to"
                            " recover from a failed cleanup. This is safe"
                            " to run even if the instance is healthy, but it"
                            " will create extra replication traffic and "
                            " disrupt briefly the replication (like during the"
                            " migration"),
                ],