4 # Copyright (C) 2006, 2007 Google Inc.
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22 # pylint: disable-msg=W0401,W0614
23 # W0401: Wildcard import ganeti.cli
24 # W0614: Unused import %s from wildcard import (since we need cli)
31 from cStringIO import StringIO
33 from ganeti.cli import *
34 from ganeti import cli
35 from ganeti import opcodes
36 from ganeti import constants
37 from ganeti import utils
38 from ganeti import errors
41 _SHUTDOWN_CLUSTER = "cluster"
42 _SHUTDOWN_NODES_BOTH = "nodes"
43 _SHUTDOWN_NODES_PRI = "nodes-pri"
44 _SHUTDOWN_NODES_SEC = "nodes-sec"
45 _SHUTDOWN_INSTANCES = "instances"
50 #: default list of options for L{ListInstances}
52 "name", "hypervisor", "os", "pnode", "status", "oper_ram",
56 def _ExpandMultiNames(mode, names, client=None):
57 """Expand the given names using the passed mode.
59 For _SHUTDOWN_CLUSTER, all instances will be returned. For
60 _SHUTDOWN_NODES_PRI/SEC, all instances having those nodes as
61 primary/secondary will be returned. For _SHUTDOWN_NODES_BOTH, all
62 instances having those nodes as either primary or secondary will be
63 returned. For _SHUTDOWN_INSTANCES, the given instances will be
66 @param mode: one of L{_SHUTDOWN_CLUSTER}, L{_SHUTDOWN_NODES_BOTH},
67 L{_SHUTDOWN_NODES_PRI}, L{_SHUTDOWN_NODES_SEC} or
68 L{_SHUTDOWN_INSTANCES}
69 @param names: a list of names; for cluster, it must be empty,
70 and for node and instance it must be a list of valid item
71 names (short names are valid as usual, e.g. node1 instead of
74 @return: the list of names after the expansion
75 @raise errors.ProgrammerError: for unknown selection type
76 @raise errors.OpPrereqError: for invalid input parameters
81 if mode == _SHUTDOWN_CLUSTER:
83 raise errors.OpPrereqError("Cluster filter mode takes no arguments")
84 idata = client.QueryInstances([], ["name"], False)
85 inames = [row[0] for row in idata]
87 elif mode in (_SHUTDOWN_NODES_BOTH,
91 raise errors.OpPrereqError("No node names passed")
92 ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"],
94 ipri = [row[1] for row in ndata]
95 pri_names = list(itertools.chain(*ipri))
96 isec = [row[2] for row in ndata]
97 sec_names = list(itertools.chain(*isec))
98 if mode == _SHUTDOWN_NODES_BOTH:
99 inames = pri_names + sec_names
100 elif mode == _SHUTDOWN_NODES_PRI:
102 elif mode == _SHUTDOWN_NODES_SEC:
105 raise errors.ProgrammerError("Unhandled shutdown type")
107 elif mode == _SHUTDOWN_INSTANCES:
109 raise errors.OpPrereqError("No instance names passed")
110 idata = client.QueryInstances(names, ["name"], False)
111 inames = [row[0] for row in idata]
114 raise errors.OpPrereqError("Unknown mode '%s'" % mode)
119 def _ConfirmOperation(inames, text, extra=""):
120 """Ask the user to confirm an operation on a list of instances.
122 This function is used to request confirmation for doing an operation
123 on a given list of instances.
126 @param inames: the list of names that we display when
127 we ask for confirmation
129 @param text: the operation that the user should confirm
130 (e.g. I{shutdown} or I{startup})
132 @return: True or False depending on user's confirmation.
136 msg = ("The %s will operate on %d instances.\n%s"
137 "Do you want to continue?" % (text, count, extra))
138 affected = ("\nAffected instances:\n" +
139 "\n".join([" %s" % name for name in inames]))
141 choices = [('y', True, 'Yes, execute the %s' % text),
142 ('n', False, 'No, abort the %s' % text)]
145 choices.insert(1, ('v', 'v', 'View the list of affected instances'))
150 choice = AskUser(ask, choices)
153 choice = AskUser(msg + affected, choices)
157 def _EnsureInstancesExist(client, names):
158 """Check for and ensure the given instance names exist.
160 This function will raise an OpPrereqError in case they don't
161 exist. Otherwise it will exit cleanly.
163 @type client: L{ganeti.luxi.Client}
164 @param client: the client to use for the query
166 @param names: the list of instance names to query
167 @raise errors.OpPrereqError: in case any instance is missing
170 # TODO: change LUQueryInstances to that it actually returns None
171 # instead of raising an exception, or devise a better mechanism
172 result = client.QueryInstances(names, ["name"], False)
173 for orig_name, row in zip(names, result):
175 raise errors.OpPrereqError("Instance '%s' does not exist" % orig_name)
178 def ListInstances(opts, args):
179 """List instances and their properties.
181 @param opts: the command line options selected by the user
183 @param args: should be an empty list
185 @return: the desired exit code
188 if opts.output is None:
189 selected_fields = _LIST_DEF_FIELDS
190 elif opts.output.startswith("+"):
191 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
193 selected_fields = opts.output.split(",")
195 output = GetClient().QueryInstances(args, selected_fields, opts.do_locking)
197 if not opts.no_headers:
199 "name": "Instance", "os": "OS", "pnode": "Primary_node",
200 "snodes": "Secondary_Nodes", "admin_state": "Autostart",
201 "oper_state": "Running",
202 "oper_ram": "Memory", "disk_template": "Disk_template",
203 "ip": "IP_address", "mac": "MAC_address",
204 "nic_mode": "NIC_Mode", "nic_link": "NIC_Link",
206 "sda_size": "Disk/0", "sdb_size": "Disk/1",
207 "disk_usage": "DiskUsage",
208 "status": "Status", "tags": "Tags",
209 "network_port": "Network_port",
210 "hv/kernel_path": "Kernel_path",
211 "hv/initrd_path": "Initrd_path",
212 "hv/boot_order": "HVM_boot_order",
213 "hv/acpi": "HVM_ACPI",
215 "hv/cdrom_image_path": "HVM_CDROM_image_path",
216 "hv/nic_type": "HVM_NIC_type",
217 "hv/disk_type": "HVM_Disk_type",
218 "hv/vnc_bind_address": "VNC_bind_address",
219 "serial_no": "SerialNo", "hypervisor": "Hypervisor",
220 "hvparams": "Hypervisor_parameters",
221 "be/memory": "Configured_memory",
224 "be/auto_balance": "Auto_balance",
225 "disk.count": "Disks", "disk.sizes": "Disk_sizes",
226 "nic.count": "NICs", "nic.ips": "NIC_IPs",
227 "nic.modes": "NIC_modes", "nic.links": "NIC_links",
228 "nic.bridges": "NIC_bridges", "nic.macs": "NIC_MACs",
229 "ctime": "CTime", "mtime": "MTime",
234 unitfields = ["be/memory", "oper_ram", "sd(a|b)_size", "disk\.size/.*"]
235 numfields = ["be/memory", "oper_ram", "sd(a|b)_size", "be/vcpus",
236 "serial_no", "(disk|nic)\.count", "disk\.size/.*"]
238 list_type_fields = ("tags", "disk.sizes", "nic.macs", "nic.ips",
239 "nic.modes", "nic.links", "nic.bridges")
240 # change raw values to nicer strings
242 for idx, field in enumerate(selected_fields):
244 if field == "snodes":
245 val = ",".join(val) or "-"
246 elif field == "admin_state":
251 elif field == "oper_state":
258 elif field == "oper_ram":
261 elif field == "sda_size" or field == "sdb_size":
264 elif field == "ctime" or field == "mtime":
265 val = utils.FormatTime(val)
266 elif field in list_type_fields:
267 val = ",".join(str(item) for item in val)
272 data = GenerateTable(separator=opts.separator, headers=headers,
273 fields=selected_fields, unitfields=unitfields,
274 numfields=numfields, data=output, units=opts.units)
282 def AddInstance(opts, args):
283 """Add an instance to the cluster.
285 @param opts: the command line options selected by the user
287 @param args: should contain only one element, the new instance name
289 @return: the desired exit code
294 (pnode, snode) = SplitNodeOption(opts.node)
299 hypervisor, hvparams = opts.hypervisor
303 nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
304 except ValueError, err:
305 raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
306 nics = [{}] * nic_max
307 for nidx, ndict in opts.nics:
309 if not isinstance(ndict, dict):
310 msg = "Invalid nic/%d value: expected dict, got %s" % (nidx, ndict)
311 raise errors.OpPrereqError(msg)
317 # default of one nic, all auto
320 if opts.disk_template == constants.DT_DISKLESS:
321 if opts.disks or opts.sd_size is not None:
322 raise errors.OpPrereqError("Diskless instance but disk"
323 " information passed")
326 if not opts.disks and not opts.sd_size:
327 raise errors.OpPrereqError("No disk information specified")
328 if opts.disks and opts.sd_size is not None:
329 raise errors.OpPrereqError("Please use either the '--disk' or"
331 if opts.sd_size is not None:
332 opts.disks = [(0, {"size": opts.sd_size})]
334 disk_max = max(int(didx[0])+1 for didx in opts.disks)
335 except ValueError, err:
336 raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
337 disks = [{}] * disk_max
338 for didx, ddict in opts.disks:
340 if not isinstance(ddict, dict):
341 msg = "Invalid disk/%d value: expected dict, got %s" % (didx, ddict)
342 raise errors.OpPrereqError(msg)
343 elif "size" not in ddict:
344 raise errors.OpPrereqError("Missing size for disk %d" % didx)
346 ddict["size"] = utils.ParseUnit(ddict["size"])
347 except ValueError, err:
348 raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
352 utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES)
353 utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
355 op = opcodes.OpCreateInstance(instance_name=instance,
357 disk_template=opts.disk_template,
359 mode=constants.INSTANCE_CREATE,
360 os_type=opts.os, pnode=pnode,
362 start=opts.start, ip_check=opts.ip_check,
363 wait_for_sync=opts.wait_for_sync,
364 hypervisor=hypervisor,
366 beparams=opts.beparams,
367 iallocator=opts.iallocator,
368 file_storage_dir=opts.file_storage_dir,
369 file_driver=opts.file_driver,
372 SubmitOrSend(op, opts)
376 def BatchCreate(opts, args):
377 """Create instances using a definition file.
379 This function reads a json file with instances defined
383 "disk_size": [20480],
389 "primary_node": "firstnode",
390 "secondary_node": "secondnode",
391 "iallocator": "dumb"}
394 Note that I{primary_node} and I{secondary_node} have precedence over
397 @param opts: the command line options selected by the user
399 @param args: should contain one element, the json filename
401 @return: the desired exit code
404 _DEFAULT_SPECS = {"disk_size": [20 * 1024],
407 "primary_node": None,
408 "secondary_node": None,
414 "file_storage_dir": None,
415 "file_driver": 'loop'}
417 def _PopulateWithDefaults(spec):
418 """Returns a new hash combined with default values."""
419 mydict = _DEFAULT_SPECS.copy()
424 """Validate the instance specs."""
425 # Validate fields required under any circumstances
426 for required_field in ('os', 'template'):
427 if required_field not in spec:
428 raise errors.OpPrereqError('Required field "%s" is missing.' %
430 # Validate special fields
431 if spec['primary_node'] is not None:
432 if (spec['template'] in constants.DTS_NET_MIRROR and
433 spec['secondary_node'] is None):
434 raise errors.OpPrereqError('Template requires secondary node, but'
435 ' there was no secondary provided.')
436 elif spec['iallocator'] is None:
437 raise errors.OpPrereqError('You have to provide at least a primary_node'
438 ' or an iallocator.')
440 if (spec['hvparams'] and
441 not isinstance(spec['hvparams'], dict)):
442 raise errors.OpPrereqError('Hypervisor parameters must be a dict.')
444 json_filename = args[0]
446 instance_data = simplejson.loads(utils.ReadFile(json_filename))
447 except Exception, err:
448 ToStderr("Can't parse the instance definition file: %s" % str(err))
453 # Iterate over the instances and do:
454 # * Populate the specs with default value
455 # * Validate the instance specs
456 i_names = utils.NiceSort(instance_data.keys())
458 specs = instance_data[name]
459 specs = _PopulateWithDefaults(specs)
462 hypervisor = specs['hypervisor']
463 hvparams = specs['hvparams']
466 for elem in specs['disk_size']:
468 size = utils.ParseUnit(elem)
469 except ValueError, err:
470 raise errors.OpPrereqError("Invalid disk size '%s' for"
473 disks.append({"size": size})
475 utils.ForceDictType(specs['backend'], constants.BES_PARAMETER_TYPES)
476 utils.ForceDictType(hvparams, constants.HVS_PARAMETER_TYPES)
479 for field in ('ip', 'mac', 'mode', 'link', 'bridge'):
483 tmp_nics[0][field] = specs[field]
485 if specs['nics'] is not None and tmp_nics:
486 raise errors.OpPrereqError("'nics' list incompatible with using"
487 " individual nic fields as well")
488 elif specs['nics'] is not None:
489 tmp_nics = specs['nics']
493 op = opcodes.OpCreateInstance(instance_name=name,
495 disk_template=specs['template'],
496 mode=constants.INSTANCE_CREATE,
498 pnode=specs['primary_node'],
499 snode=specs['secondary_node'],
501 start=specs['start'],
502 ip_check=specs['ip_check'],
504 iallocator=specs['iallocator'],
505 hypervisor=hypervisor,
507 beparams=specs['backend'],
508 file_storage_dir=specs['file_storage_dir'],
509 file_driver=specs['file_driver'])
511 jex.QueueJob(name, op)
512 # we never want to wait, just show the submitted job IDs
513 jex.WaitOrShow(False)
518 def ReinstallInstance(opts, args):
519 """Reinstall an instance.
521 @param opts: the command line options selected by the user
523 @param args: should contain only one element, the name of the
524 instance to be reinstalled
526 @return: the desired exit code
529 # first, compute the desired name list
530 if opts.multi_mode is None:
531 opts.multi_mode = _SHUTDOWN_INSTANCES
533 inames = _ExpandMultiNames(opts.multi_mode, args)
535 raise errors.OpPrereqError("Selection filter does not match any instances")
537 # second, if requested, ask for an OS
538 if opts.select_os is True:
539 op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
540 result = SubmitOpCode(op)
543 ToStdout("Can't get the OS list")
546 ToStdout("Available OS templates:")
550 ToStdout("%3s: %s", number, entry[0])
551 choices.append(("%s" % number, entry[0], entry[0]))
554 choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
555 selected = AskUser("Enter OS template number (or x to abort):",
558 if selected == 'exit':
559 ToStderr("User aborted reinstall, exiting")
566 # third, get confirmation: multi-reinstall requires --force-multi
567 # *and* --force, single-reinstall just --force
568 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
570 warn_msg = "Note: this will remove *all* data for the below instances!\n"
571 if not ((opts.force_multi and opts.force) or
572 _ConfirmOperation(inames, "reinstall", extra=warn_msg)):
576 usertext = ("This will reinstall the instance %s and remove"
577 " all data. Continue?") % inames[0]
578 if not AskUser(usertext):
581 jex = JobExecutor(verbose=multi_on)
582 for instance_name in inames:
583 op = opcodes.OpReinstallInstance(instance_name=instance_name,
585 jex.QueueJob(instance_name, op)
587 jex.WaitOrShow(not opts.submit_only)
591 def RemoveInstance(opts, args):
592 """Remove an instance.
594 @param opts: the command line options selected by the user
596 @param args: should contain only one element, the name of
597 the instance to be removed
599 @return: the desired exit code
602 instance_name = args[0]
607 _EnsureInstancesExist(cl, [instance_name])
609 usertext = ("This will remove the volumes of the instance %s"
610 " (including mirrors), thus removing all the data"
611 " of the instance. Continue?") % instance_name
612 if not AskUser(usertext):
615 op = opcodes.OpRemoveInstance(instance_name=instance_name,
616 ignore_failures=opts.ignore_failures)
617 SubmitOrSend(op, opts, cl=cl)
621 def RenameInstance(opts, args):
622 """Rename an instance.
624 @param opts: the command line options selected by the user
626 @param args: should contain two elements, the old and the
629 @return: the desired exit code
632 op = opcodes.OpRenameInstance(instance_name=args[0],
634 ignore_ip=opts.ignore_ip)
635 SubmitOrSend(op, opts)
639 def ActivateDisks(opts, args):
640 """Activate an instance's disks.
642 This serves two purposes:
643 - it allows (as long as the instance is not running)
644 mounting the disks and modifying them from the node
645 - it repairs inactive secondary drbds
647 @param opts: the command line options selected by the user
649 @param args: should contain only one element, the instance name
651 @return: the desired exit code
654 instance_name = args[0]
655 op = opcodes.OpActivateInstanceDisks(instance_name=instance_name,
656 ignore_size=opts.ignore_size)
657 disks_info = SubmitOrSend(op, opts)
658 for host, iname, nname in disks_info:
659 ToStdout("%s:%s:%s", host, iname, nname)
663 def DeactivateDisks(opts, args):
664 """Deactivate an instance's disks.
666 This function takes the instance name, looks for its primary node
667 and the tries to shutdown its block devices on that node.
669 @param opts: the command line options selected by the user
671 @param args: should contain only one element, the instance name
673 @return: the desired exit code
676 instance_name = args[0]
677 op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
678 SubmitOrSend(op, opts)
682 def RecreateDisks(opts, args):
683 """Recreate an instance's disks.
685 @param opts: the command line options selected by the user
687 @param args: should contain only one element, the instance name
689 @return: the desired exit code
692 instance_name = args[0]
695 opts.disks = [int(v) for v in opts.disks.split(",")]
696 except (ValueError, TypeError), err:
697 ToStderr("Invalid disks value: %s" % str(err))
702 op = opcodes.OpRecreateInstanceDisks(instance_name=instance_name,
704 SubmitOrSend(op, opts)
708 def GrowDisk(opts, args):
709 """Grow an instance's disks.
711 @param opts: the command line options selected by the user
713 @param args: should contain two elements, the instance name
714 whose disks we grow and the disk name, e.g. I{sda}
716 @return: the desired exit code
723 except ValueError, err:
724 raise errors.OpPrereqError("Invalid disk index: %s" % str(err))
725 amount = utils.ParseUnit(args[2])
726 op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
727 wait_for_sync=opts.wait_for_sync)
728 SubmitOrSend(op, opts)
732 def StartupInstance(opts, args):
733 """Startup instances.
735 Depending on the options given, this will start one or more
738 @param opts: the command line options selected by the user
740 @param args: the instance or node names based on which we
741 create the final selection (in conjunction with the
744 @return: the desired exit code
748 if opts.multi_mode is None:
749 opts.multi_mode = _SHUTDOWN_INSTANCES
750 inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
752 raise errors.OpPrereqError("Selection filter does not match any instances")
753 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
754 if not (opts.force_multi or not multi_on
755 or _ConfirmOperation(inames, "startup")):
757 jex = cli.JobExecutor(verbose=multi_on, cl=cl)
759 op = opcodes.OpStartupInstance(instance_name=name,
761 # do not add these parameters to the opcode unless they're defined
763 op.hvparams = opts.hvparams
765 op.beparams = opts.beparams
766 jex.QueueJob(name, op)
767 jex.WaitOrShow(not opts.submit_only)
771 def RebootInstance(opts, args):
772 """Reboot instance(s).
774 Depending on the parameters given, this will reboot one or more
777 @param opts: the command line options selected by the user
779 @param args: the instance or node names based on which we
780 create the final selection (in conjunction with the
783 @return: the desired exit code
787 if opts.multi_mode is None:
788 opts.multi_mode = _SHUTDOWN_INSTANCES
789 inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
791 raise errors.OpPrereqError("Selection filter does not match any instances")
792 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
793 if not (opts.force_multi or not multi_on
794 or _ConfirmOperation(inames, "reboot")):
796 jex = JobExecutor(verbose=multi_on, cl=cl)
798 op = opcodes.OpRebootInstance(instance_name=name,
799 reboot_type=opts.reboot_type,
800 ignore_secondaries=opts.ignore_secondaries)
801 jex.QueueJob(name, op)
802 jex.WaitOrShow(not opts.submit_only)
806 def ShutdownInstance(opts, args):
807 """Shutdown an instance.
809 @param opts: the command line options selected by the user
811 @param args: the instance or node names based on which we
812 create the final selection (in conjunction with the
815 @return: the desired exit code
819 if opts.multi_mode is None:
820 opts.multi_mode = _SHUTDOWN_INSTANCES
821 inames = _ExpandMultiNames(opts.multi_mode, args, client=cl)
823 raise errors.OpPrereqError("Selection filter does not match any instances")
824 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
825 if not (opts.force_multi or not multi_on
826 or _ConfirmOperation(inames, "shutdown")):
829 jex = cli.JobExecutor(verbose=multi_on, cl=cl)
831 op = opcodes.OpShutdownInstance(instance_name=name)
832 jex.QueueJob(name, op)
833 jex.WaitOrShow(not opts.submit_only)
837 def ReplaceDisks(opts, args):
838 """Replace the disks of an instance
840 @param opts: the command line options selected by the user
842 @param args: should contain only one element, the instance name
844 @return: the desired exit code
847 instance_name = args[0]
848 new_2ndary = opts.new_secondary
849 iallocator = opts.iallocator
850 if opts.disks is None:
854 disks = [int(i) for i in opts.disks.split(",")]
855 except ValueError, err:
856 raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
857 cnt = [opts.on_primary, opts.on_secondary, opts.auto,
858 new_2ndary is not None, iallocator is not None].count(True)
860 raise errors.OpPrereqError("One and only one of the -p, -s, -a, -n and -i"
861 " options must be passed")
862 elif opts.on_primary:
863 mode = constants.REPLACE_DISK_PRI
864 elif opts.on_secondary:
865 mode = constants.REPLACE_DISK_SEC
867 mode = constants.REPLACE_DISK_AUTO
869 raise errors.OpPrereqError("Cannot specify disks when using automatic"
871 elif new_2ndary is not None or iallocator is not None:
873 mode = constants.REPLACE_DISK_CHG
875 op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
876 remote_node=new_2ndary, mode=mode,
877 iallocator=iallocator)
878 SubmitOrSend(op, opts)
882 def FailoverInstance(opts, args):
883 """Failover an instance.
885 The failover is done by shutting it down on its present node and
886 starting it on the secondary.
888 @param opts: the command line options selected by the user
890 @param args: should contain only one element, the instance name
892 @return: the desired exit code
896 instance_name = args[0]
900 _EnsureInstancesExist(cl, [instance_name])
902 usertext = ("Failover will happen to image %s."
903 " This requires a shutdown of the instance. Continue?" %
905 if not AskUser(usertext):
908 op = opcodes.OpFailoverInstance(instance_name=instance_name,
909 ignore_consistency=opts.ignore_consistency)
910 SubmitOrSend(op, opts, cl=cl)
914 def MigrateInstance(opts, args):
915 """Migrate an instance.
917 The migrate is done without shutdown.
919 @param opts: the command line options selected by the user
921 @param args: should contain only one element, the instance name
923 @return: the desired exit code
927 instance_name = args[0]
931 _EnsureInstancesExist(cl, [instance_name])
934 usertext = ("Instance %s will be recovered from a failed migration."
935 " Note that the migration procedure (including cleanup)" %
938 usertext = ("Instance %s will be migrated. Note that migration" %
940 usertext += (" is **experimental** in this version."
941 " This might impact the instance if anything goes wrong."
943 if not AskUser(usertext):
946 op = opcodes.OpMigrateInstance(instance_name=instance_name, live=opts.live,
947 cleanup=opts.cleanup)
948 SubmitOpCode(op, cl=cl)
952 def MoveInstance(opts, args):
955 @param opts: the command line options selected by the user
957 @param args: should contain only one element, the instance name
959 @return: the desired exit code
963 instance_name = args[0]
967 usertext = ("Instance %s will be moved."
968 " This requires a shutdown of the instance. Continue?" %
970 if not AskUser(usertext):
973 op = opcodes.OpMoveInstance(instance_name=instance_name,
974 target_node=opts.target_node)
975 SubmitOrSend(op, opts, cl=cl)
979 def ConnectToInstanceConsole(opts, args):
980 """Connect to the console of an instance.
982 @param opts: the command line options selected by the user
984 @param args: should contain only one element, the instance name
986 @return: the desired exit code
989 instance_name = args[0]
991 op = opcodes.OpConnectConsole(instance_name=instance_name)
992 cmd = SubmitOpCode(op)
994 if opts.show_command:
995 ToStdout("%s", utils.ShellQuoteArgs(cmd))
998 os.execvp(cmd[0], cmd)
1000 ToStderr("Can't run console command %s with arguments:\n'%s'",
1001 cmd[0], " ".join(cmd))
1005 def _FormatLogicalID(dev_type, logical_id):
1006 """Formats the logical_id of a disk.
1009 if dev_type == constants.LD_DRBD8:
1010 node_a, node_b, port, minor_a, minor_b, key = logical_id
1012 ("nodeA", "%s, minor=%s" % (node_a, minor_a)),
1013 ("nodeB", "%s, minor=%s" % (node_b, minor_b)),
1017 elif dev_type == constants.LD_LV:
1018 vg_name, lv_name = logical_id
1019 data = ["%s/%s" % (vg_name, lv_name)]
1021 data = [str(logical_id)]
1026 def _FormatBlockDevInfo(idx, top_level, dev, static):
1027 """Show block device information.
1029 This is only used by L{ShowInstanceConfig}, but it's too big to be
1030 left for an inline definition.
1033 @param idx: the index of the current disk
1034 @type top_level: boolean
1035 @param top_level: if this a top-level disk?
1037 @param dev: dictionary with disk information
1038 @type static: boolean
1039 @param static: wheter the device information doesn't contain
1040 runtime information but only static data
1041 @return: a list of either strings, tuples or lists
1042 (which should be formatted at a higher indent level)
1045 def helper(dtype, status):
1046 """Format one line for physical device status.
1049 @param dtype: a constant from the L{constants.LDS_BLOCK} set
1051 @param status: a tuple as returned from L{backend.FindBlockDevice}
1052 @return: the string representing the status
1058 (path, major, minor, syncp, estt, degr, ldisk_status) = status
1060 major_string = "N/A"
1062 major_string = str(major)
1065 minor_string = "N/A"
1067 minor_string = str(minor)
1069 txt += ("%s (%s:%s)" % (path, major_string, minor_string))
1070 if dtype in (constants.LD_DRBD8, ):
1071 if syncp is not None:
1072 sync_text = "*RECOVERING* %5.2f%%," % syncp
1074 sync_text += " ETA %ds" % estt
1076 sync_text += " ETA unknown"
1078 sync_text = "in sync"
1080 degr_text = "*DEGRADED*"
1083 if ldisk_status == constants.LDS_FAULTY:
1084 ldisk_text = " *MISSING DISK*"
1085 elif ldisk_status == constants.LDS_UNKNOWN:
1086 ldisk_text = " *UNCERTAIN STATE*"
1089 txt += (" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
1090 elif dtype == constants.LD_LV:
1091 if ldisk_status == constants.LDS_FAULTY:
1092 ldisk_text = " *FAILED* (failed drive?)"
1100 if dev["iv_name"] is not None:
1101 txt = dev["iv_name"]
1103 txt = "disk %d" % idx
1105 txt = "child %d" % idx
1106 if isinstance(dev["size"], int):
1107 nice_size = utils.FormatUnit(dev["size"], "h")
1109 nice_size = dev["size"]
1110 d1 = ["- %s: %s, size %s" % (txt, dev["dev_type"], nice_size)]
1113 data.append(("access mode", dev["mode"]))
1114 if dev["logical_id"] is not None:
1116 l_id = _FormatLogicalID(dev["dev_type"], dev["logical_id"])
1118 l_id = [str(dev["logical_id"])]
1120 data.append(("logical_id", l_id[0]))
1123 elif dev["physical_id"] is not None:
1124 data.append("physical_id:")
1125 data.append([dev["physical_id"]])
1127 data.append(("on primary", helper(dev["dev_type"], dev["pstatus"])))
1128 if dev["sstatus"] and not static:
1129 data.append(("on secondary", helper(dev["dev_type"], dev["sstatus"])))
1132 data.append("child devices:")
1133 for c_idx, child in enumerate(dev["children"]):
1134 data.append(_FormatBlockDevInfo(c_idx, False, child, static))
1139 def _FormatList(buf, data, indent_level):
1140 """Formats a list of data at a given indent level.
1142 If the element of the list is:
1143 - a string, it is simply formatted as is
1144 - a tuple, it will be split into key, value and the all the
1145 values in a list will be aligned all at the same start column
1146 - a list, will be recursively formatted
1149 @param buf: the buffer into which we write the output
1150 @param data: the list to format
1151 @type indent_level: int
1152 @param indent_level: the indent level to format at
1155 max_tlen = max([len(elem[0]) for elem in data
1156 if isinstance(elem, tuple)] or [0])
1158 if isinstance(elem, basestring):
1159 buf.write("%*s%s\n" % (2*indent_level, "", elem))
1160 elif isinstance(elem, tuple):
1162 spacer = "%*s" % (max_tlen - len(key), "")
1163 buf.write("%*s%s:%s %s\n" % (2*indent_level, "", key, spacer, value))
1164 elif isinstance(elem, list):
1165 _FormatList(buf, elem, indent_level+1)
1168 def ShowInstanceConfig(opts, args):
1169 """Compute instance run-time status.
1171 @param opts: the command line options selected by the user
1173 @param args: either an empty list, and then we query all
1174 instances, or should contain a list of instance names
1176 @return: the desired exit code
1179 if not args and not opts.show_all:
1180 ToStderr("No instance selected."
1181 " Please pass in --all if you want to query all instances.\n"
1182 "Note that this can take a long time on a big cluster.")
1184 elif args and opts.show_all:
1185 ToStderr("Cannot use --all if you specify instance names.")
1189 op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
1190 result = SubmitOpCode(op)
1192 ToStdout("No instances.")
1197 for instance_name in result:
1198 instance = result[instance_name]
1199 buf.write("Instance name: %s\n" % instance["name"])
1200 buf.write("Serial number: %s\n" % instance["serial_no"])
1201 buf.write("Creation time: %s\n" % utils.FormatTime(instance["ctime"]))
1202 buf.write("Modification time: %s\n" % utils.FormatTime(instance["mtime"]))
1203 buf.write("State: configured to be %s" % instance["config_state"])
1205 buf.write(", actual state is %s" % instance["run_state"])
1207 ##buf.write("Considered for memory checks in cluster verify: %s\n" %
1208 ## instance["auto_balance"])
1209 buf.write(" Nodes:\n")
1210 buf.write(" - primary: %s\n" % instance["pnode"])
1211 buf.write(" - secondaries: %s\n" % ", ".join(instance["snodes"]))
1212 buf.write(" Operating system: %s\n" % instance["os"])
1213 if instance.has_key("network_port"):
1214 buf.write(" Allocated network port: %s\n" % instance["network_port"])
1215 buf.write(" Hypervisor: %s\n" % instance["hypervisor"])
1217 # custom VNC console information
1218 vnc_bind_address = instance["hv_actual"].get(constants.HV_VNC_BIND_ADDRESS,
1220 if vnc_bind_address:
1221 port = instance["network_port"]
1222 display = int(port) - constants.VNC_BASE_PORT
1223 if display > 0 and vnc_bind_address == constants.BIND_ADDRESS_GLOBAL:
1224 vnc_console_port = "%s:%s (display %s)" % (instance["pnode"],
1227 elif display > 0 and utils.IsValidIP(vnc_bind_address):
1228 vnc_console_port = ("%s:%s (node %s) (display %s)" %
1229 (vnc_bind_address, port,
1230 instance["pnode"], display))
1232 # vnc bind address is a file
1233 vnc_console_port = "%s:%s" % (instance["pnode"],
1235 buf.write(" - console connection: vnc to %s\n" % vnc_console_port)
1237 for key in instance["hv_actual"]:
1238 if key in instance["hv_instance"]:
1239 val = instance["hv_instance"][key]
1241 val = "default (%s)" % instance["hv_actual"][key]
1242 buf.write(" - %s: %s\n" % (key, val))
1243 buf.write(" Hardware:\n")
1244 buf.write(" - VCPUs: %d\n" %
1245 instance["be_actual"][constants.BE_VCPUS])
1246 buf.write(" - memory: %dMiB\n" %
1247 instance["be_actual"][constants.BE_MEMORY])
1248 buf.write(" - NICs:\n")
1249 for idx, (mac, ip, mode, link) in enumerate(instance["nics"]):
1250 buf.write(" - nic/%d: MAC: %s, IP: %s, mode: %s, link: %s\n" %
1251 (idx, mac, ip, mode, link))
1252 buf.write(" Disks:\n")
1254 for idx, device in enumerate(instance["disks"]):
1255 _FormatList(buf, _FormatBlockDevInfo(idx, True, device, opts.static), 2)
1257 ToStdout(buf.getvalue().rstrip('\n'))
1261 def SetInstanceParams(opts, args):
1262 """Modifies an instance.
1264 All parameters take effect only at the next restart of the instance.
1266 @param opts: the command line options selected by the user
1268 @param args: should contain only one element, the instance name
1270 @return: the desired exit code
1273 if not (opts.nics or opts.disks or
1274 opts.hypervisor or opts.beparams):
1275 ToStderr("Please give at least one of the parameters.")
1278 for param in opts.beparams:
1279 if isinstance(opts.beparams[param], basestring):
1280 if opts.beparams[param].lower() == "default":
1281 opts.beparams[param] = constants.VALUE_DEFAULT
1283 utils.ForceDictType(opts.beparams, constants.BES_PARAMETER_TYPES,
1284 allowed_values=[constants.VALUE_DEFAULT])
1286 for param in opts.hypervisor:
1287 if isinstance(opts.hypervisor[param], basestring):
1288 if opts.hypervisor[param].lower() == "default":
1289 opts.hypervisor[param] = constants.VALUE_DEFAULT
1291 utils.ForceDictType(opts.hypervisor, constants.HVS_PARAMETER_TYPES,
1292 allowed_values=[constants.VALUE_DEFAULT])
1294 for idx, (nic_op, nic_dict) in enumerate(opts.nics):
1296 nic_op = int(nic_op)
1297 opts.nics[idx] = (nic_op, nic_dict)
1301 for idx, (disk_op, disk_dict) in enumerate(opts.disks):
1303 disk_op = int(disk_op)
1304 opts.disks[idx] = (disk_op, disk_dict)
1307 if disk_op == constants.DDM_ADD:
1308 if 'size' not in disk_dict:
1309 raise errors.OpPrereqError("Missing required parameter 'size'")
1310 disk_dict['size'] = utils.ParseUnit(disk_dict['size'])
1312 op = opcodes.OpSetInstanceParams(instance_name=args[0],
1315 hvparams=opts.hypervisor,
1316 beparams=opts.beparams,
1319 # even if here we process the result, we allow submit only
1320 result = SubmitOrSend(op, opts)
1323 ToStdout("Modified instance %s", args[0])
1324 for param, data in result:
1325 ToStdout(" - %-5s -> %s", param, data)
1326 ToStdout("Please don't forget that these parameters take effect"
1327 " only at the next start of the instance.")
1331 # options used in more than one cmd
1332 node_opt = cli_option("-n", "--node", dest="node", help="Target node",
1334 completion_suggest=OPT_COMPL_ONE_NODE)
1336 os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
1338 completion_suggest=OPT_COMPL_ONE_OS)
1340 # multi-instance selection options
1341 m_force_multi = cli_option("--force-multiple", dest="force_multi",
1342 help="Do not ask for confirmation when more than"
1343 " one instance is affected",
1344 action="store_true", default=False)
1346 m_pri_node_opt = cli_option("--primary", dest="multi_mode",
1347 help="Filter by nodes (primary only)",
1348 const=_SHUTDOWN_NODES_PRI, action="store_const")
1350 m_sec_node_opt = cli_option("--secondary", dest="multi_mode",
1351 help="Filter by nodes (secondary only)",
1352 const=_SHUTDOWN_NODES_SEC, action="store_const")
1354 m_node_opt = cli_option("--node", dest="multi_mode",
1355 help="Filter by nodes (primary and secondary)",
1356 const=_SHUTDOWN_NODES_BOTH, action="store_const")
1358 m_clust_opt = cli_option("--all", dest="multi_mode",
1359 help="Select all instances in the cluster",
1360 const=_SHUTDOWN_CLUSTER, action="store_const")
1362 m_inst_opt = cli_option("--instance", dest="multi_mode",
1363 help="Filter by instance name [default]",
1364 const=_SHUTDOWN_INSTANCES, action="store_const")
1367 # this is defined separately due to readability only
1370 cli_option("-n", "--node", dest="node",
1371 help="Target node and optional secondary node",
1372 metavar="<pnode>[:<snode>]",
1373 completion_suggest=OPT_COMPL_INST_ADD_NODES),
1375 cli_option("-B", "--backend", dest="beparams",
1376 type="keyval", default={},
1377 help="Backend parameters"),
1378 cli_option("-t", "--disk-template", dest="disk_template",
1379 help="Custom disk setup (diskless, file, plain or drbd)",
1380 default=None, metavar="TEMPL",
1381 choices=list(constants.DISK_TEMPLATES)),
1382 cli_option("-s", "--os-size", dest="sd_size", help="Disk size for a"
1383 " single-disk configuration, when not using the --disk option,"
1384 " in MiB unless a suffix is used",
1385 default=None, type="unit", metavar="<size>"),
1386 cli_option("--disk", help="Disk information",
1387 default=[], dest="disks",
1389 type="identkeyval"),
1390 cli_option("--net", help="NIC information",
1391 default=[], dest="nics",
1393 type="identkeyval"),
1394 cli_option("--no-nics", default=False, action="store_true",
1395 help="Do not create any network cards for the instance"),
1396 cli_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
1397 action="store_false", help="Don't wait for sync (DANGEROUS!)"),
1398 cli_option("--no-start", dest="start", default=True,
1399 action="store_false", help="Don't start the instance after"
1401 cli_option("--no-ip-check", dest="ip_check", default=True,
1402 action="store_false", help="Don't check that the instance's IP"
1403 " is alive (only valid with --no-start)"),
1404 cli_option("--file-storage-dir", dest="file_storage_dir",
1405 help="Relative path under default cluster-wide file storage dir"
1406 " to store file-based disks", default=None,
1408 cli_option("--file-driver", dest="file_driver", help="Driver to use"
1409 " for image files", default="loop", metavar="<DRIVER>",
1410 choices=list(constants.FILE_DRIVER)),
1411 cli_option("-I", "--iallocator", metavar="<NAME>",
1412 help="Select nodes for the instance automatically using the"
1413 " <NAME> iallocator plugin", default=None, type="string",
1414 completion_suggest=OPT_COMPL_ONE_IALLOCATOR),
1415 cli_option("-H", "--hypervisor", dest="hypervisor",
1416 help="Hypervisor and hypervisor options, in the format"
1417 " hypervisor:option=value,option=value,...", default=None,
1418 type="identkeyval"),
1423 'add': (AddInstance, [ArgHost(min=1, max=1)], add_opts,
1424 "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
1425 "Creates and adds a new instance to the cluster"),
1426 'batch-create': (BatchCreate, [ArgFile(min=1, max=1)],
1428 "<instances_file.json>",
1429 "Create a bunch of instances based on specs in the file."),
1430 'console': (ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
1432 cli_option("--show-cmd", dest="show_command",
1433 action="store_true", default=False,
1434 help=("Show command instead of executing it"))],
1435 "[--show-cmd] <instance>",
1436 "Opens a console on the specified instance"),
1437 'failover': (FailoverInstance, ARGS_ONE_INSTANCE,
1438 [DEBUG_OPT, FORCE_OPT,
1439 cli_option("--ignore-consistency", dest="ignore_consistency",
1440 action="store_true", default=False,
1441 help="Ignore the consistency of the disks on"
1446 "Stops the instance and starts it on the backup node, using"
1447 " the remote mirror (only for instances of type drbd)"),
1448 'migrate': (MigrateInstance, ARGS_ONE_INSTANCE,
1449 [DEBUG_OPT, FORCE_OPT,
1450 cli_option("--non-live", dest="live",
1451 default=True, action="store_false",
1452 help="Do a non-live migration (this usually means"
1453 " freeze the instance, save the state,"
1454 " transfer and only then resume running on the"
1455 " secondary node)"),
1456 cli_option("--cleanup", dest="cleanup",
1457 default=False, action="store_true",
1458 help="Instead of performing the migration, try to"
1459 " recover from a failed cleanup. This is safe"
1460 " to run even if the instance is healthy, but it"
1461 " will create extra replication traffic and "
1462 " disrupt briefly the replication (like during the"
1466 "Migrate instance to its secondary node"
1467 " (only for instances of type drbd)"),
1468 'move': (MoveInstance, ARGS_ONE_INSTANCE,
1469 [DEBUG_OPT, FORCE_OPT, SUBMIT_OPT,
1470 cli_option("-n", "--new-node", dest="target_node",
1471 help="Destinattion node", metavar="NODE",
1473 completion_suggest=OPT_COMPL_ONE_NODE),
1476 "Move instance to an arbitrary node"
1477 " (only for instances of type file and lv)"),
1478 'info': (ShowInstanceConfig, ARGS_MANY_INSTANCES,
1480 cli_option("-s", "--static", dest="static",
1481 action="store_true", default=False,
1482 help="Only show configuration data, not runtime data"),
1483 cli_option("--all", dest="show_all",
1484 default=False, action="store_true",
1485 help="Show info on all instances on the cluster."
1486 " This can take a long time to run, use wisely."),
1487 ], "[-s] {--all | <instance>...}",
1488 "Show information on the specified instance(s)"),
1489 'list': (ListInstances, ARGS_MANY_INSTANCES,
1490 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
1492 "Lists the instances and their status. The available fields are"
1493 " (see the man page for details): status, oper_state, oper_ram,"
1494 " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
1495 " ip, mac, mode, link, sda_size, sdb_size, vcpus, serial_no,"
1497 " The default field"
1498 " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
1500 'reinstall': (ReinstallInstance, [ArgInstance(min=1)],
1501 [DEBUG_OPT, FORCE_OPT, os_opt,
1503 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1504 m_clust_opt, m_inst_opt,
1505 cli_option("--select-os", dest="select_os",
1506 action="store_true", default=False,
1507 help="Interactive OS reinstall, lists available"
1508 " OS templates for selection"),
1511 "[-f] <instance>", "Reinstall a stopped instance"),
1512 'remove': (RemoveInstance, ARGS_ONE_INSTANCE,
1513 [DEBUG_OPT, FORCE_OPT,
1514 cli_option("--ignore-failures", dest="ignore_failures",
1515 action="store_true", default=False,
1516 help=("Remove the instance from the cluster even"
1517 " if there are failures during the removal"
1518 " process (shutdown, disk removal, etc.)")),
1521 "[-f] <instance>", "Shuts down the instance and removes it"),
1522 'rename': (RenameInstance,
1523 [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
1525 cli_option("--no-ip-check", dest="ignore_ip",
1526 help="Do not check that the IP of the new name"
1528 default=False, action="store_true"),
1531 "<instance> <new_name>", "Rename the instance"),
1532 'replace-disks': (ReplaceDisks, ARGS_ONE_INSTANCE,
1534 cli_option("-n", "--new-secondary", dest="new_secondary",
1535 help=("New secondary node (for secondary"
1536 " node change)"), metavar="NODE",
1538 completion_suggest=OPT_COMPL_ONE_NODE),
1539 cli_option("-p", "--on-primary", dest="on_primary",
1540 default=False, action="store_true",
1541 help=("Replace the disk(s) on the primary"
1542 " node (only for the drbd template)")),
1543 cli_option("-s", "--on-secondary", dest="on_secondary",
1544 default=False, action="store_true",
1545 help=("Replace the disk(s) on the secondary"
1546 " node (only for the drbd template)")),
1547 cli_option("-a", "--auto", dest="auto",
1548 default=False, action="store_true",
1549 help=("Automatically replace faulty disks"
1550 " (only for the drbd template)")),
1551 cli_option("--disks", dest="disks", default=None,
1552 help="Comma-separated list of disks"
1553 " indices to replace (e.g. 0,2) (optional,"
1554 " defaults to all disks)"),
1555 cli_option("-I", "--iallocator", metavar="<NAME>",
1556 help="Select new secondary for the instance"
1557 " automatically using the"
1558 " <NAME> iallocator plugin (enables"
1559 " secondary node replacement)",
1560 default=None, type="string",
1561 completion_suggest=OPT_COMPL_ONE_IALLOCATOR),
1564 "[-s|-p|-n NODE|-I NAME] <instance>",
1565 "Replaces all disks for the instance"),
1566 'modify': (SetInstanceParams, ARGS_ONE_INSTANCE,
1567 [DEBUG_OPT, FORCE_OPT,
1568 cli_option("-H", "--hypervisor", type="keyval",
1569 default={}, dest="hypervisor",
1570 help="Change hypervisor parameters"),
1571 cli_option("-B", "--backend", type="keyval",
1572 default={}, dest="beparams",
1573 help="Change backend parameters"),
1574 cli_option("--disk", help="Disk changes",
1575 default=[], dest="disks",
1577 type="identkeyval"),
1578 cli_option("--net", help="NIC changes",
1579 default=[], dest="nics",
1581 type="identkeyval"),
1584 "<instance>", "Alters the parameters of an instance"),
1585 'shutdown': (ShutdownInstance, [ArgInstance(min=1)],
1586 [DEBUG_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1587 m_clust_opt, m_inst_opt, m_force_multi,
1590 "<instance>", "Stops an instance"),
1591 'startup': (StartupInstance, [ArgInstance(min=1)],
1592 [DEBUG_OPT, FORCE_OPT, m_force_multi,
1593 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1594 m_clust_opt, m_inst_opt,
1596 cli_option("-H", "--hypervisor", type="keyval",
1597 default={}, dest="hvparams",
1598 help="Temporary hypervisor parameters"),
1599 cli_option("-B", "--backend", type="keyval",
1600 default={}, dest="beparams",
1601 help="Temporary backend parameters"),
1603 "<instance>", "Starts an instance"),
1604 'reboot': (RebootInstance, [ArgInstance(min=1)],
1605 [DEBUG_OPT, m_force_multi,
1606 cli_option("-t", "--type", dest="reboot_type",
1607 help="Type of reboot: soft/hard/full",
1608 default=constants.INSTANCE_REBOOT_HARD,
1610 choices=list(constants.REBOOT_TYPES)),
1611 cli_option("--ignore-secondaries", dest="ignore_secondaries",
1612 default=False, action="store_true",
1613 help="Ignore errors from secondaries"),
1614 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1615 m_clust_opt, m_inst_opt,
1618 "<instance>", "Reboots an instance"),
1619 'activate-disks': (ActivateDisks, ARGS_ONE_INSTANCE,
1620 [DEBUG_OPT, SUBMIT_OPT,
1621 cli_option("--ignore-size", dest="ignore_size",
1622 default=False, action="store_true",
1623 help="Ignore current recorded size"
1624 " (useful for forcing activation when"
1625 " the recorded size is wrong)"),
1628 "Activate an instance's disks"),
1629 'deactivate-disks': (DeactivateDisks, ARGS_ONE_INSTANCE,
1630 [DEBUG_OPT, SUBMIT_OPT],
1632 "Deactivate an instance's disks"),
1633 'recreate-disks': (RecreateDisks, ARGS_ONE_INSTANCE,
1634 [DEBUG_OPT, SUBMIT_OPT,
1635 cli_option("--disks", dest="disks", default=None,
1636 help="Comma-separated list of disks"
1637 " indices to replace (e.g. 0,2) (optional,"
1638 " defaults to all disks)"),
1641 "Recreate an instance's disks"),
1642 'grow-disk': (GrowDisk,
1643 [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
1644 ArgUnknown(min=1, max=1)],
1645 [DEBUG_OPT, SUBMIT_OPT,
1646 cli_option("--no-wait-for-sync",
1647 dest="wait_for_sync", default=True,
1648 action="store_false",
1649 help="Don't wait for sync (DANGEROUS!)"),
1651 "<instance> <disk> <size>", "Grow an instance's disk"),
1652 'list-tags': (ListTags, ARGS_ONE_INSTANCE, [DEBUG_OPT],
1653 "<instance_name>", "List the tags of the given instance"),
1654 'add-tags': (AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1655 [DEBUG_OPT, TAG_SRC_OPT],
1656 "<instance_name> tag...", "Add tags to the given instance"),
1657 'remove-tags': (RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1658 [DEBUG_OPT, TAG_SRC_OPT],
1659 "<instance_name> tag...", "Remove tags from given instance"),
1662 #: dictionary with aliases for commands
1664 'activate_block_devs': 'activate-disks',
1665 'replace_disks': 'replace-disks',
1671 if __name__ == '__main__':
1672 sys.exit(GenericMain(commands, aliases=aliases,
1673 override={"tag_type": constants.TAG_INSTANCE}))