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)
30 from optparse import make_option
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):
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
79 if mode == _SHUTDOWN_CLUSTER:
81 raise errors.OpPrereqError("Cluster filter mode takes no arguments")
83 idata = client.QueryInstances([], ["name"])
84 inames = [row[0] for row in idata]
86 elif mode in (_SHUTDOWN_NODES_BOTH,
90 raise errors.OpPrereqError("No node names passed")
92 ndata = client.QueryNodes(names, ["name", "pinst_list", "sinst_list"])
93 ipri = [row[1] for row in ndata]
94 pri_names = list(itertools.chain(*ipri))
95 isec = [row[2] for row in ndata]
96 sec_names = list(itertools.chain(*isec))
97 if mode == _SHUTDOWN_NODES_BOTH:
98 inames = pri_names + sec_names
99 elif mode == _SHUTDOWN_NODES_PRI:
101 elif mode == _SHUTDOWN_NODES_SEC:
104 raise errors.ProgrammerError("Unhandled shutdown type")
106 elif mode == _SHUTDOWN_INSTANCES:
108 raise errors.OpPrereqError("No instance names passed")
110 idata = client.QueryInstances(names, ["name"])
111 inames = [row[0] for row in idata]
114 raise errors.OpPrereqError("Unknown mode '%s'" % mode)
119 def _ConfirmOperation(inames, text):
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"
137 "Do you want to continue?" % (text, count))
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 _TransformPath(user_input):
158 """Transform a user path into a canonical value.
160 This function transforms the a path passed as textual information
161 into the constants that the LU code expects.
165 if user_input.lower() == "default":
166 result_path = constants.VALUE_DEFAULT
167 elif user_input.lower() == "none":
168 result_path = constants.VALUE_NONE
170 if not os.path.isabs(user_input):
171 raise errors.OpPrereqError("Path '%s' is not an absolute filename" %
173 result_path = user_input
175 result_path = constants.VALUE_DEFAULT
180 def ListInstances(opts, args):
181 """List instances and their properties.
183 @param opts: the command line options selected by the user
185 @param args: should be an empty list
187 @return: the desired exit code
190 if opts.output is None:
191 selected_fields = _LIST_DEF_FIELDS
192 elif opts.output.startswith("+"):
193 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
195 selected_fields = opts.output.split(",")
197 output = GetClient().QueryInstances([], selected_fields)
199 if not opts.no_headers:
201 "name": "Instance", "os": "OS", "pnode": "Primary_node",
202 "snodes": "Secondary_Nodes", "admin_state": "Autostart",
203 "oper_state": "Running",
204 "oper_ram": "Memory", "disk_template": "Disk_template",
205 "ip": "IP_address", "mac": "MAC_address",
207 "sda_size": "Disk/0", "sdb_size": "Disk/1",
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",
223 "be/auto_balance": "Auto_balance",
228 if opts.human_readable:
229 unitfields = ["be/memory", "oper_ram", "sda_size", "sdb_size"]
233 numfields = ["be/memory", "oper_ram", "sda_size", "sdb_size", "be/vcpus",
236 list_type_fields = ("tags",)
237 # change raw values to nicer strings
239 for idx, field in enumerate(selected_fields):
241 if field == "snodes":
242 val = ",".join(val) or "-"
243 elif field == "admin_state":
248 elif field == "oper_state":
255 elif field == "oper_ram":
258 elif field == "sda_size" or field == "sdb_size":
261 elif field in list_type_fields:
267 data = GenerateTable(separator=opts.separator, headers=headers,
268 fields=selected_fields, unitfields=unitfields,
269 numfields=numfields, data=output)
277 def AddInstance(opts, args):
278 """Add an instance to the cluster.
280 @param opts: the command line options selected by the user
282 @param args: should contain only one element, the new instance name
284 @return: the desired exit code
289 (pnode, snode) = SplitNodeOption(opts.node)
294 hypervisor, hvparams = opts.hypervisor
298 nic_max = max(int(nidx[0])+1 for nidx in opts.nics)
299 except ValueError, err:
300 raise errors.OpPrereqError("Invalid NIC index passed: %s" % str(err))
301 nics = [{}] * nic_max
302 for nidx, ndict in opts.nics.items():
306 # default of one nic, all auto
309 if not opts.disks and opts.disk_template != constants.DT_DISKLESS:
310 raise errors.OpPrereqError("No disk information specified")
311 elif opts.disks and opts.disk_template == constants.DT_DISKLESS:
312 raise errors.OpPrereqError("Diskless instance but disk information passeD")
315 disk_max = max(int(didx[0])+1 for didx in opts.disks)
316 except ValueError, err:
317 raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
318 disks = [{}] * disk_max
319 for didx, ddict in opts.disks:
321 if "size" not in ddict:
322 raise errors.OpPrereqError("Missing size for disk %d" % didx)
324 ddict["size"] = utils.ParseUnit(ddict["size"])
325 except ValueError, err:
326 raise errors.OpPrereqError("Invalid disk size for disk %d: %s" %
330 ValidateBeParams(opts.beparams)
332 ## kernel_path = _TransformPath(opts.kernel_path)
333 ## initrd_path = _TransformPath(opts.initrd_path)
335 ## hvm_acpi = opts.hvm_acpi == _VALUE_TRUE
336 ## hvm_pae = opts.hvm_pae == _VALUE_TRUE
338 ## if ((opts.hvm_cdrom_image_path is not None) and
339 ## (opts.hvm_cdrom_image_path.lower() == constants.VALUE_NONE)):
340 ## hvm_cdrom_image_path = None
342 ## hvm_cdrom_image_path = opts.hvm_cdrom_image_path
344 op = opcodes.OpCreateInstance(instance_name=instance,
346 disk_template=opts.disk_template,
348 mode=constants.INSTANCE_CREATE,
349 os_type=opts.os, pnode=pnode,
351 start=opts.start, ip_check=opts.ip_check,
352 wait_for_sync=opts.wait_for_sync,
353 hypervisor=hypervisor,
355 beparams=opts.beparams,
356 iallocator=opts.iallocator,
357 file_storage_dir=opts.file_storage_dir,
358 file_driver=opts.file_driver,
361 SubmitOrSend(op, opts)
365 def BatchCreate(opts, args):
366 """Create instances using a definition file.
368 This function reads a json file with instances defined
379 "primary_node": "firstnode",
380 "secondary_node": "secondnode",
381 "iallocator": "dumb"}
384 Note that I{primary_node} and I{secondary_node} have precedence over
387 @param opts: the command line options selected by the user
389 @param args: should contain one element, the json filename
391 @return: the desired exit code
394 _DEFAULT_SPECS = {"disk_size": 20 * 1024,
395 "swap_size": 4 * 1024,
398 "primary_node": None,
399 "secondary_node": None,
406 "file_storage_dir": None,
407 "file_driver": 'loop'}
409 def _PopulateWithDefaults(spec):
410 """Returns a new hash combined with default values."""
411 mydict = _DEFAULT_SPECS.copy()
416 """Validate the instance specs."""
417 # Validate fields required under any circumstances
418 for required_field in ('os', 'template'):
419 if required_field not in spec:
420 raise errors.OpPrereqError('Required field "%s" is missing.' %
422 # Validate special fields
423 if spec['primary_node'] is not None:
424 if (spec['template'] in constants.DTS_NET_MIRROR and
425 spec['secondary_node'] is None):
426 raise errors.OpPrereqError('Template requires secondary node, but'
427 ' there was no secondary provided.')
428 elif spec['iallocator'] is None:
429 raise errors.OpPrereqError('You have to provide at least a primary_node'
430 ' or an iallocator.')
432 if (spec['hypervisor'] and
433 not isinstance(spec['hypervisor'], dict)):
434 raise errors.OpPrereqError('Hypervisor parameters must be a dict.')
436 json_filename = args[0]
437 fd = open(json_filename, 'r')
439 instance_data = simplejson.load(fd)
443 # Iterate over the instances and do:
444 # * Populate the specs with default value
445 # * Validate the instance specs
446 for (name, specs) in instance_data.iteritems():
447 specs = _PopulateWithDefaults(specs)
452 if specs['hypervisor']:
453 hypervisor, hvparams = specs['hypervisor'].iteritems()
455 op = opcodes.OpCreateInstance(instance_name=name,
456 disk_size=specs['disk_size'],
457 swap_size=specs['swap_size'],
458 disk_template=specs['template'],
459 mode=constants.INSTANCE_CREATE,
461 pnode=specs['primary_node'],
462 snode=specs['secondary_node'],
463 ip=specs['ip'], bridge=specs['bridge'],
464 start=specs['start'],
465 ip_check=specs['ip_check'],
468 iallocator=specs['iallocator'],
469 hypervisor=hypervisor,
471 beparams=specs['backend'],
472 file_storage_dir=specs['file_storage_dir'],
473 file_driver=specs['file_driver'])
475 ToStdout("%s: %s", name, cli.SendJob([op]))
480 def ReinstallInstance(opts, args):
481 """Reinstall an instance.
483 @param opts: the command line options selected by the user
485 @param args: should contain only one element, the name of the
486 instance to be reinstalled
488 @return: the desired exit code
491 instance_name = args[0]
493 if opts.select_os is True:
494 op = opcodes.OpDiagnoseOS(output_fields=["name", "valid"], names=[])
495 result = SubmitOpCode(op)
498 ToStdout("Can't get the OS list")
501 ToStdout("Available OS templates:")
505 ToStdout("%3s: %s", number, entry[0])
506 choices.append(("%s" % number, entry[0], entry[0]))
509 choices.append(('x', 'exit', 'Exit gnt-instance reinstall'))
510 selected = AskUser("Enter OS template name or number (or x to abort):",
513 if selected == 'exit':
514 ToStdout("User aborted reinstall, exiting")
522 usertext = ("This will reinstall the instance %s and remove"
523 " all data. Continue?") % instance_name
524 if not AskUser(usertext):
527 op = opcodes.OpReinstallInstance(instance_name=instance_name,
529 SubmitOrSend(op, opts)
534 def RemoveInstance(opts, args):
535 """Remove an instance.
537 @param opts: the command line options selected by the user
539 @param args: should contain only one element, the name of
540 the instance to be removed
542 @return: the desired exit code
545 instance_name = args[0]
549 usertext = ("This will remove the volumes of the instance %s"
550 " (including mirrors), thus removing all the data"
551 " of the instance. Continue?") % instance_name
552 if not AskUser(usertext):
555 op = opcodes.OpRemoveInstance(instance_name=instance_name,
556 ignore_failures=opts.ignore_failures)
557 SubmitOrSend(op, opts)
561 def RenameInstance(opts, args):
562 """Rename an instance.
564 @param opts: the command line options selected by the user
566 @param args: should contain two elements, the old and the
569 @return: the desired exit code
572 op = opcodes.OpRenameInstance(instance_name=args[0],
574 ignore_ip=opts.ignore_ip)
575 SubmitOrSend(op, opts)
579 def ActivateDisks(opts, args):
580 """Activate an instance's disks.
582 This serves two purposes:
583 - it allows (as long as the instance is not running)
584 mounting the disks and modifying them from the node
585 - it repairs inactive secondary drbds
587 @param opts: the command line options selected by the user
589 @param args: should contain only one element, the instance name
591 @return: the desired exit code
594 instance_name = args[0]
595 op = opcodes.OpActivateInstanceDisks(instance_name=instance_name)
596 disks_info = SubmitOrSend(op, opts)
597 for host, iname, nname in disks_info:
598 ToStdout("%s:%s:%s", host, iname, nname)
602 def DeactivateDisks(opts, args):
603 """Deactivate an instance's disks..
605 This function takes the instance name, looks for its primary node
606 and the tries to shutdown its block devices on that node.
608 @param opts: the command line options selected by the user
610 @param args: should contain only one element, the instance name
612 @return: the desired exit code
615 instance_name = args[0]
616 op = opcodes.OpDeactivateInstanceDisks(instance_name=instance_name)
617 SubmitOrSend(op, opts)
621 def GrowDisk(opts, args):
622 """Grow an instance's disks.
624 @param opts: the command line options selected by the user
626 @param args: should contain two elements, the instance name
627 whose disks we grow and the disk name, e.g. I{sda}
629 @return: the desired exit code
634 amount = utils.ParseUnit(args[2])
635 op = opcodes.OpGrowDisk(instance_name=instance, disk=disk, amount=amount,
636 wait_for_sync=opts.wait_for_sync)
637 SubmitOrSend(op, opts)
641 def StartupInstance(opts, args):
642 """Startup instances.
644 Depending on the options given, this will start one or more
647 @param opts: the command line options selected by the user
649 @param args: the instance or node names based on which we
650 create the final selection (in conjunction with the
653 @return: the desired exit code
656 if opts.multi_mode is None:
657 opts.multi_mode = _SHUTDOWN_INSTANCES
658 inames = _ExpandMultiNames(opts.multi_mode, args)
660 raise errors.OpPrereqError("Selection filter does not match any instances")
661 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
662 if not (opts.force_multi or not multi_on
663 or _ConfirmOperation(inames, "startup")):
666 op = opcodes.OpStartupInstance(instance_name=name,
668 extra_args=opts.extra_args)
670 ToStdout("Starting up %s", name)
672 SubmitOrSend(op, opts)
673 except JobSubmittedException, err:
674 _, txt = FormatError(err)
679 def RebootInstance(opts, args):
680 """Reboot instance(s).
682 Depending on the parameters given, this will reboot one or more
685 @param opts: the command line options selected by the user
687 @param args: the instance or node names based on which we
688 create the final selection (in conjunction with the
691 @return: the desired exit code
694 if opts.multi_mode is None:
695 opts.multi_mode = _SHUTDOWN_INSTANCES
696 inames = _ExpandMultiNames(opts.multi_mode, args)
698 raise errors.OpPrereqError("Selection filter does not match any instances")
699 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
700 if not (opts.force_multi or not multi_on
701 or _ConfirmOperation(inames, "reboot")):
704 op = opcodes.OpRebootInstance(instance_name=name,
705 reboot_type=opts.reboot_type,
706 ignore_secondaries=opts.ignore_secondaries)
708 SubmitOrSend(op, opts)
712 def ShutdownInstance(opts, args):
713 """Shutdown an instance.
715 @param opts: the command line options selected by the user
717 @param args: the instance or node names based on which we
718 create the final selection (in conjunction with the
721 @return: the desired exit code
724 if opts.multi_mode is None:
725 opts.multi_mode = _SHUTDOWN_INSTANCES
726 inames = _ExpandMultiNames(opts.multi_mode, args)
728 raise errors.OpPrereqError("Selection filter does not match any instances")
729 multi_on = opts.multi_mode != _SHUTDOWN_INSTANCES or len(inames) > 1
730 if not (opts.force_multi or not multi_on
731 or _ConfirmOperation(inames, "shutdown")):
734 op = opcodes.OpShutdownInstance(instance_name=name)
736 ToStdout("Shutting down %s", name)
738 SubmitOrSend(op, opts)
739 except JobSubmittedException, err:
740 _, txt = FormatError(err)
745 def ReplaceDisks(opts, args):
746 """Replace the disks of an instance
748 @param opts: the command line options selected by the user
750 @param args: should contain only one element, the instance name
752 @return: the desired exit code
755 instance_name = args[0]
756 new_2ndary = opts.new_secondary
757 iallocator = opts.iallocator
758 if opts.disks is None:
762 disks = [int(i) for i in opts.disks.split(",")]
763 except ValueError, err:
764 raise errors.OpPrereqError("Invalid disk index passed: %s" % str(err))
765 if opts.on_primary == opts.on_secondary: # no -p or -s passed, or both passed
766 mode = constants.REPLACE_DISK_ALL
767 elif opts.on_primary: # only on primary:
768 mode = constants.REPLACE_DISK_PRI
769 if new_2ndary is not None or iallocator is not None:
770 raise errors.OpPrereqError("Can't change secondary node on primary disk"
772 elif opts.on_secondary is not None or iallocator is not None:
774 mode = constants.REPLACE_DISK_SEC
776 op = opcodes.OpReplaceDisks(instance_name=args[0], disks=disks,
777 remote_node=new_2ndary, mode=mode,
778 iallocator=iallocator)
779 SubmitOrSend(op, opts)
783 def FailoverInstance(opts, args):
784 """Failover an instance.
786 The failover is done by shutting it down on its present node and
787 starting it on the secondary.
789 @param opts: the command line options selected by the user
791 @param args: should contain only one element, the instance name
793 @return: the desired exit code
796 instance_name = args[0]
800 usertext = ("Failover will happen to image %s."
801 " This requires a shutdown of the instance. Continue?" %
803 if not AskUser(usertext):
806 op = opcodes.OpFailoverInstance(instance_name=instance_name,
807 ignore_consistency=opts.ignore_consistency)
808 SubmitOrSend(op, opts)
812 def ConnectToInstanceConsole(opts, args):
813 """Connect to the console of an instance.
815 @param opts: the command line options selected by the user
817 @param args: should contain only one element, the instance name
819 @return: the desired exit code
822 instance_name = args[0]
824 op = opcodes.OpConnectConsole(instance_name=instance_name)
825 cmd = SubmitOpCode(op)
827 if opts.show_command:
828 ToStdout("%s", utils.ShellQuoteArgs(cmd))
831 os.execvp(cmd[0], cmd)
833 ToStderr("Can't run console command %s with arguments:\n'%s'",
834 cmd[0], " ".join(cmd))
838 def _FormatBlockDevInfo(buf, dev, indent_level, static):
839 """Show block device information.
841 This is only used by L{ShowInstanceConfig}, but it's too big to be
842 left for an inline definition.
845 @param buf: buffer that will accumulate the output
847 @param dev: dictionary with disk information
848 @type indent_level: int
849 @param indent_level: the indendation level we are at, used for
850 the layout of the device tree
851 @type static: boolean
852 @param static: wheter the device information doesn't contain
853 runtime information but only static data
856 def helper(buf, dtype, status):
857 """Format one line for physical device status.
860 @param buf: buffer that will accumulate the output
862 @param dtype: a constant from the L{constants.LDS_BLOCK} set
864 @param status: a tuple as returned from L{backend.FindBlockDevice}
868 buf.write("not active\n")
870 (path, major, minor, syncp, estt, degr, ldisk) = status
874 major_string = str(major)
879 minor_string = str(minor)
881 buf.write("%s (%s:%s)" % (path, major_string, minor_string))
882 if dtype in (constants.LD_DRBD8, ):
883 if syncp is not None:
884 sync_text = "*RECOVERING* %5.2f%%," % syncp
886 sync_text += " ETA %ds" % estt
888 sync_text += " ETA unknown"
890 sync_text = "in sync"
892 degr_text = "*DEGRADED*"
896 ldisk_text = " *MISSING DISK*"
899 buf.write(" %s, status %s%s" % (sync_text, degr_text, ldisk_text))
900 elif dtype == constants.LD_LV:
902 ldisk_text = " *FAILED* (failed drive?)"
905 buf.write(ldisk_text)
908 if dev["iv_name"] is not None:
909 data = " - %s, " % dev["iv_name"]
912 data += "type: %s" % dev["dev_type"]
913 if dev["logical_id"] is not None:
914 data += ", logical_id: %s" % (dev["logical_id"],)
915 elif dev["physical_id"] is not None:
916 data += ", physical_id: %s" % (dev["physical_id"],)
917 buf.write("%*s%s\n" % (2*indent_level, "", data))
919 buf.write("%*s primary: " % (2*indent_level, ""))
920 helper(buf, dev["dev_type"], dev["pstatus"])
922 if dev["sstatus"] and not static:
923 buf.write("%*s secondary: " % (2*indent_level, ""))
924 helper(buf, dev["dev_type"], dev["sstatus"])
927 for child in dev["children"]:
928 _FormatBlockDevInfo(buf, child, indent_level+1, static)
931 def ShowInstanceConfig(opts, args):
932 """Compute instance run-time status.
934 @param opts: the command line options selected by the user
936 @param args: either an empty list, and then we query all
937 instances, or should contain a list of instance names
939 @return: the desired exit code
943 op = opcodes.OpQueryInstanceData(instances=args, static=opts.static)
944 result = SubmitOpCode(op)
946 ToStdout("No instances.")
951 for instance_name in result:
952 instance = result[instance_name]
953 buf.write("Instance name: %s\n" % instance["name"])
954 buf.write("State: configured to be %s" % instance["config_state"])
956 buf.write(", actual state is %s" % instance["run_state"])
958 ##buf.write("Considered for memory checks in cluster verify: %s\n" %
959 ## instance["auto_balance"])
960 buf.write(" Nodes:\n")
961 buf.write(" - primary: %s\n" % instance["pnode"])
962 buf.write(" - secondaries: %s\n" % ", ".join(instance["snodes"]))
963 buf.write(" Operating system: %s\n" % instance["os"])
964 if instance.has_key("network_port"):
965 buf.write(" Allocated network port: %s\n" % instance["network_port"])
966 buf.write(" Hypervisor: %s\n" % instance["hypervisor"])
967 if instance["hypervisor"] == constants.HT_XEN_PVM:
968 hvattrs = ((constants.HV_KERNEL_PATH, "kernel path"),
969 (constants.HV_INITRD_PATH, "initrd path"))
970 elif instance["hypervisor"] == constants.HT_XEN_HVM:
971 hvattrs = ((constants.HV_BOOT_ORDER, "boot order"),
972 (constants.HV_ACPI, "ACPI"),
973 (constants.HV_PAE, "PAE"),
974 (constants.HV_CDROM_IMAGE_PATH, "virtual CDROM"),
975 (constants.HV_NIC_TYPE, "NIC type"),
976 (constants.HV_DISK_TYPE, "Disk type"),
977 (constants.HV_VNC_BIND_ADDRESS, "VNC bind address"),
979 # custom console information for HVM
980 vnc_bind_address = instance["hv_actual"][constants.HV_VNC_BIND_ADDRESS]
981 if vnc_bind_address == constants.BIND_ADDRESS_GLOBAL:
982 vnc_console_port = "%s:%s" % (instance["pnode"],
983 instance["network_port"])
984 elif vnc_bind_address == constants.LOCALHOST_IP_ADDRESS:
985 vnc_console_port = "%s:%s on node %s" % (vnc_bind_address,
986 instance["network_port"],
989 vnc_console_port = "%s:%s" % (vnc_bind_address,
990 instance["network_port"])
991 buf.write(" - console connection: vnc to %s\n" % vnc_console_port)
994 # auto-handle other hypervisor types
995 hvattrs = [(key, key) for key in instance["hv_actual"]]
997 for key, desc in hvattrs:
998 if key in instance["hv_instance"]:
999 val = instance["hv_instance"][key]
1001 val = "default (%s)" % instance["hv_actual"][key]
1002 buf.write(" - %s: %s\n" % (desc, val))
1003 buf.write(" Hardware:\n")
1004 buf.write(" - VCPUs: %d\n" %
1005 instance["be_actual"][constants.BE_VCPUS])
1006 buf.write(" - memory: %dMiB\n" %
1007 instance["be_actual"][constants.BE_MEMORY])
1008 buf.write(" - NICs: %s\n" %
1009 ", ".join(["{MAC: %s, IP: %s, bridge: %s}" %
1011 for mac, ip, bridge in instance["nics"]]))
1012 buf.write(" Block devices:\n")
1014 for device in instance["disks"]:
1015 _FormatBlockDevInfo(buf, device, 1, opts.static)
1017 ToStdout(buf.getvalue().rstrip('\n'))
1021 def SetInstanceParams(opts, args):
1022 """Modifies an instance.
1024 All parameters take effect only at the next restart of the instance.
1026 @param opts: the command line options selected by the user
1028 @param args: should contain only one element, the instance name
1030 @return: the desired exit code
1033 if not (opts.ip or opts.bridge or opts.mac or
1034 opts.hypervisor or opts.beparams):
1035 ToStderr("Please give at least one of the parameters.")
1038 if constants.BE_MEMORY in opts.beparams:
1039 opts.beparams[constants.BE_MEMORY] = utils.ParseUnit(
1040 opts.beparams[constants.BE_MEMORY])
1042 op = opcodes.OpSetInstanceParams(instance_name=args[0],
1044 bridge=opts.bridge, mac=opts.mac,
1045 hvparams=opts.hypervisor,
1046 beparams=opts.beparams,
1049 # even if here we process the result, we allow submit only
1050 result = SubmitOrSend(op, opts)
1053 ToStdout("Modified instance %s", args[0])
1054 for param, data in result:
1055 ToStdout(" - %-5s -> %s", param, data)
1056 ToStdout("Please don't forget that these parameters take effect"
1057 " only at the next start of the instance.")
1061 # options used in more than one cmd
1062 node_opt = make_option("-n", "--node", dest="node", help="Target node",
1065 os_opt = cli_option("-o", "--os-type", dest="os", help="What OS to run",
1068 # multi-instance selection options
1069 m_force_multi = make_option("--force-multiple", dest="force_multi",
1070 help="Do not ask for confirmation when more than"
1071 " one instance is affected",
1072 action="store_true", default=False)
1074 m_pri_node_opt = make_option("--primary", dest="multi_mode",
1075 help="Filter by nodes (primary only)",
1076 const=_SHUTDOWN_NODES_PRI, action="store_const")
1078 m_sec_node_opt = make_option("--secondary", dest="multi_mode",
1079 help="Filter by nodes (secondary only)",
1080 const=_SHUTDOWN_NODES_SEC, action="store_const")
1082 m_node_opt = make_option("--node", dest="multi_mode",
1083 help="Filter by nodes (primary and secondary)",
1084 const=_SHUTDOWN_NODES_BOTH, action="store_const")
1086 m_clust_opt = make_option("--all", dest="multi_mode",
1087 help="Select all instances in the cluster",
1088 const=_SHUTDOWN_CLUSTER, action="store_const")
1090 m_inst_opt = make_option("--instance", dest="multi_mode",
1091 help="Filter by instance name [default]",
1092 const=_SHUTDOWN_INSTANCES, action="store_const")
1095 # this is defined separately due to readability only
1098 make_option("-n", "--node", dest="node",
1099 help="Target node and optional secondary node",
1100 metavar="<pnode>[:<snode>]"),
1101 cli_option("-s", "--os-size", dest="size", help="Disk size, in MiB unless"
1102 " a suffix is used",
1103 default=20 * 1024, type="unit", metavar="<size>"),
1104 cli_option("--swap-size", dest="swap", help="Swap size, in MiB unless a"
1106 default=4 * 1024, type="unit", metavar="<size>"),
1108 keyval_option("-B", "--backend", dest="beparams",
1109 type="keyval", default={},
1110 help="Backend parameters"),
1111 make_option("-t", "--disk-template", dest="disk_template",
1112 help="Custom disk setup (diskless, file, plain or drbd)",
1113 default=None, metavar="TEMPL"),
1114 ikv_option("--disk", help="Disk information",
1115 default=[], dest="disks",
1117 type="identkeyval"),
1118 ikv_option("--net", help="NIC information",
1119 default=[], dest="nics",
1121 type="identkeyval"),
1122 make_option("--no-wait-for-sync", dest="wait_for_sync", default=True,
1123 action="store_false", help="Don't wait for sync (DANGEROUS!)"),
1124 make_option("--no-start", dest="start", default=True,
1125 action="store_false", help="Don't start the instance after"
1127 make_option("--no-ip-check", dest="ip_check", default=True,
1128 action="store_false", help="Don't check that the instance's IP"
1129 " is alive (only valid with --no-start)"),
1130 make_option("--file-storage-dir", dest="file_storage_dir",
1131 help="Relative path under default cluster-wide file storage dir"
1132 " to store file-based disks", default=None,
1134 make_option("--file-driver", dest="file_driver", help="Driver to use"
1135 " for image files", default="loop", metavar="<DRIVER>"),
1136 make_option("--iallocator", metavar="<NAME>",
1137 help="Select nodes for the instance automatically using the"
1138 " <NAME> iallocator plugin", default=None, type="string"),
1139 ikv_option("-H", "--hypervisor", dest="hypervisor",
1140 help="Hypervisor and hypervisor options, in the format"
1141 " hypervisor:option=value,option=value,...", default=None,
1142 type="identkeyval"),
1147 'add': (AddInstance, ARGS_ONE, add_opts,
1148 "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
1149 "Creates and adds a new instance to the cluster"),
1150 'batch-create': (BatchCreate, ARGS_ONE,
1152 "<instances_file.json>",
1153 "Create a bunch of instances based on specs in the file."),
1154 'console': (ConnectToInstanceConsole, ARGS_ONE,
1156 make_option("--show-cmd", dest="show_command",
1157 action="store_true", default=False,
1158 help=("Show command instead of executing it"))],
1159 "[--show-cmd] <instance>",
1160 "Opens a console on the specified instance"),
1161 'failover': (FailoverInstance, ARGS_ONE,
1162 [DEBUG_OPT, FORCE_OPT,
1163 make_option("--ignore-consistency", dest="ignore_consistency",
1164 action="store_true", default=False,
1165 help="Ignore the consistency of the disks on"
1170 "Stops the instance and starts it on the backup node, using"
1171 " the remote mirror (only for instances of type drbd)"),
1172 'info': (ShowInstanceConfig, ARGS_ANY,
1174 make_option("-s", "--static", dest="static",
1175 action="store_true", default=False,
1176 help="Only show configuration data, not runtime data"),
1177 ], "[-s] [<instance>...]",
1178 "Show information on the specified instance(s)"),
1179 'list': (ListInstances, ARGS_NONE,
1180 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT], "",
1181 "Lists the instances and their status. The available fields are"
1182 " (see the man page for details): status, oper_state, oper_ram,"
1183 " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
1184 " ip, mac, bridge, sda_size, sdb_size, vcpus, serial_no,"
1186 " The default field"
1187 " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
1189 'reinstall': (ReinstallInstance, ARGS_ONE,
1190 [DEBUG_OPT, FORCE_OPT, os_opt,
1191 make_option("--select-os", dest="select_os",
1192 action="store_true", default=False,
1193 help="Interactive OS reinstall, lists available"
1194 " OS templates for selection"),
1197 "[-f] <instance>", "Reinstall a stopped instance"),
1198 'remove': (RemoveInstance, ARGS_ONE,
1199 [DEBUG_OPT, FORCE_OPT,
1200 make_option("--ignore-failures", dest="ignore_failures",
1201 action="store_true", default=False,
1202 help=("Remove the instance from the cluster even"
1203 " if there are failures during the removal"
1204 " process (shutdown, disk removal, etc.)")),
1207 "[-f] <instance>", "Shuts down the instance and removes it"),
1208 'rename': (RenameInstance, ARGS_FIXED(2),
1210 make_option("--no-ip-check", dest="ignore_ip",
1211 help="Do not check that the IP of the new name"
1213 default=False, action="store_true"),
1216 "<instance> <new_name>", "Rename the instance"),
1217 'replace-disks': (ReplaceDisks, ARGS_ONE,
1219 make_option("-n", "--new-secondary", dest="new_secondary",
1220 help=("New secondary node (for secondary"
1221 " node change)"), metavar="NODE"),
1222 make_option("-p", "--on-primary", dest="on_primary",
1223 default=False, action="store_true",
1224 help=("Replace the disk(s) on the primary"
1225 " node (only for the drbd template)")),
1226 make_option("-s", "--on-secondary", dest="on_secondary",
1227 default=False, action="store_true",
1228 help=("Replace the disk(s) on the secondary"
1229 " node (only for the drbd template)")),
1230 make_option("--disks", dest="disks", default=None,
1231 help=("Comma-separated list of disks"
1232 " to replace (e.g. sda) (optional,"
1233 " defaults to all disks")),
1234 make_option("--iallocator", metavar="<NAME>",
1235 help="Select new secondary for the instance"
1236 " automatically using the"
1237 " <NAME> iallocator plugin (enables"
1238 " secondary node replacement)",
1239 default=None, type="string"),
1242 "[-s|-p|-n NODE] <instance>",
1243 "Replaces all disks for the instance"),
1244 'modify': (SetInstanceParams, ARGS_ONE,
1245 [DEBUG_OPT, FORCE_OPT,
1246 make_option("-i", "--ip", dest="ip",
1247 help="IP address ('none' or numeric IP)",
1248 default=None, type="string", metavar="<ADDRESS>"),
1249 make_option("-b", "--bridge", dest="bridge",
1250 help="Bridge to connect this instance to",
1251 default=None, type="string", metavar="<bridge>"),
1252 make_option("--mac", dest="mac",
1253 help="MAC address", default=None,
1254 type="string", metavar="<MACADDRESS>"),
1255 keyval_option("-H", "--hypervisor", type="keyval",
1256 default={}, dest="hypervisor",
1257 help="Change hypervisor parameters"),
1258 keyval_option("-B", "--backend", type="keyval",
1259 default={}, dest="beparams",
1260 help="Change backend parameters"),
1263 "<instance>", "Alters the parameters of an instance"),
1264 'shutdown': (ShutdownInstance, ARGS_ANY,
1265 [DEBUG_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1266 m_clust_opt, m_inst_opt, m_force_multi,
1269 "<instance>", "Stops an instance"),
1270 'startup': (StartupInstance, ARGS_ANY,
1271 [DEBUG_OPT, FORCE_OPT, m_force_multi,
1272 make_option("-e", "--extra", dest="extra_args",
1273 help="Extra arguments for the instance's kernel",
1274 default=None, type="string", metavar="<PARAMS>"),
1275 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1276 m_clust_opt, m_inst_opt,
1279 "<instance>", "Starts an instance"),
1281 'reboot': (RebootInstance, ARGS_ANY,
1282 [DEBUG_OPT, m_force_multi,
1283 make_option("-e", "--extra", dest="extra_args",
1284 help="Extra arguments for the instance's kernel",
1285 default=None, type="string", metavar="<PARAMS>"),
1286 make_option("-t", "--type", dest="reboot_type",
1287 help="Type of reboot: soft/hard/full",
1288 default=constants.INSTANCE_REBOOT_HARD,
1289 type="string", metavar="<REBOOT>"),
1290 make_option("--ignore-secondaries", dest="ignore_secondaries",
1291 default=False, action="store_true",
1292 help="Ignore errors from secondaries"),
1293 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1294 m_clust_opt, m_inst_opt,
1297 "<instance>", "Reboots an instance"),
1298 'activate-disks': (ActivateDisks, ARGS_ONE, [DEBUG_OPT, SUBMIT_OPT],
1300 "Activate an instance's disks"),
1301 'deactivate-disks': (DeactivateDisks, ARGS_ONE, [DEBUG_OPT, SUBMIT_OPT],
1303 "Deactivate an instance's disks"),
1304 'grow-disk': (GrowDisk, ARGS_FIXED(3),
1305 [DEBUG_OPT, SUBMIT_OPT,
1306 make_option("--no-wait-for-sync",
1307 dest="wait_for_sync", default=True,
1308 action="store_false",
1309 help="Don't wait for sync (DANGEROUS!)"),
1311 "<instance> <disk> <size>", "Grow an instance's disk"),
1312 'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
1313 "<instance_name>", "List the tags of the given instance"),
1314 'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
1315 "<instance_name> tag...", "Add tags to the given instance"),
1316 'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
1317 "<instance_name> tag...", "Remove tags from given instance"),
1320 #: dictionary with aliases for commands
1322 'activate_block_devs': 'activate-disks',
1323 'replace_disks': 'replace-disks',
1328 if __name__ == '__main__':
1329 sys.exit(GenericMain(commands, aliases=aliases,
1330 override={"tag_type": constants.TAG_INSTANCE}))