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.dst_node
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.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.hvparams 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.hvparams:
1287 if isinstance(opts.hvparams[param], basestring):
1288 if opts.hvparams[param].lower() == "default":
1289 opts.hvparams[param] = constants.VALUE_DEFAULT
1291 utils.ForceDictType(opts.hvparams, 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.hvparams,
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 # multi-instance selection options
1332 m_force_multi = cli_option("--force-multiple", dest="force_multi",
1333 help="Do not ask for confirmation when more than"
1334 " one instance is affected",
1335 action="store_true", default=False)
1337 m_pri_node_opt = cli_option("--primary", dest="multi_mode",
1338 help="Filter by nodes (primary only)",
1339 const=_SHUTDOWN_NODES_PRI, action="store_const")
1341 m_sec_node_opt = cli_option("--secondary", dest="multi_mode",
1342 help="Filter by nodes (secondary only)",
1343 const=_SHUTDOWN_NODES_SEC, action="store_const")
1345 m_node_opt = cli_option("--node", dest="multi_mode",
1346 help="Filter by nodes (primary and secondary)",
1347 const=_SHUTDOWN_NODES_BOTH, action="store_const")
1349 m_clust_opt = cli_option("--all", dest="multi_mode",
1350 help="Select all instances in the cluster",
1351 const=_SHUTDOWN_CLUSTER, action="store_const")
1353 m_inst_opt = cli_option("--instance", dest="multi_mode",
1354 help="Filter by instance name [default]",
1355 const=_SHUTDOWN_INSTANCES, action="store_const")
1358 # this is defined separately due to readability only
1373 FILESTORE_DRIVER_OPT,
1380 'add': (AddInstance, [ArgHost(min=1, max=1)], add_opts,
1381 "[...] -t disk-type -n node[:secondary-node] -o os-type <name>",
1382 "Creates and adds a new instance to the cluster"),
1383 'batch-create': (BatchCreate, [ArgFile(min=1, max=1)],
1385 "<instances_file.json>",
1386 "Create a bunch of instances based on specs in the file."),
1387 'console': (ConnectToInstanceConsole, ARGS_ONE_INSTANCE,
1388 [DEBUG_OPT, SHOWCMD_OPT],
1389 "[--show-cmd] <instance>",
1390 "Opens a console on the specified instance"),
1391 'failover': (FailoverInstance, ARGS_ONE_INSTANCE,
1392 [DEBUG_OPT, FORCE_OPT, IGNORE_CONSIST_OPT, SUBMIT_OPT],
1394 "Stops the instance and starts it on the backup node, using"
1395 " the remote mirror (only for instances of type drbd)"),
1396 'migrate': (MigrateInstance, ARGS_ONE_INSTANCE,
1397 [DEBUG_OPT, FORCE_OPT, NONLIVE_OPT, CLEANUP_OPT],
1399 "Migrate instance to its secondary node"
1400 " (only for instances of type drbd)"),
1401 'move': (MoveInstance, ARGS_ONE_INSTANCE,
1402 [DEBUG_OPT, FORCE_OPT, SUBMIT_OPT, SINGLE_NODE_OPT],
1404 "Move instance to an arbitrary node"
1405 " (only for instances of type file and lv)"),
1406 'info': (ShowInstanceConfig, ARGS_MANY_INSTANCES,
1407 [DEBUG_OPT, STATIC_OPT, ALL_OPT],
1408 "[-s] {--all | <instance>...}",
1409 "Show information on the specified instance(s)"),
1410 'list': (ListInstances, ARGS_MANY_INSTANCES,
1411 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
1413 "Lists the instances and their status. The available fields are"
1414 " (see the man page for details): status, oper_state, oper_ram,"
1415 " name, os, pnode, snodes, admin_state, admin_ram, disk_template,"
1416 " ip, mac, mode, link, sda_size, sdb_size, vcpus, serial_no,"
1418 " The default field"
1419 " list is (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
1421 'reinstall': (ReinstallInstance, [ArgInstance(min=1)],
1422 [DEBUG_OPT, FORCE_OPT, OS_OPT,
1424 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1425 m_clust_opt, m_inst_opt,
1429 "[-f] <instance>", "Reinstall a stopped instance"),
1430 'remove': (RemoveInstance, ARGS_ONE_INSTANCE,
1431 [DEBUG_OPT, FORCE_OPT, IGNORE_FAILURES_OPT, SUBMIT_OPT],
1432 "[-f] <instance>", "Shuts down the instance and removes it"),
1433 'rename': (RenameInstance,
1434 [ArgInstance(min=1, max=1), ArgHost(min=1, max=1)],
1435 [DEBUG_OPT, NOIPCHECK_OPT, SUBMIT_OPT],
1436 "<instance> <new_name>", "Rename the instance"),
1437 'replace-disks': (ReplaceDisks, ARGS_ONE_INSTANCE,
1440 cli_option("-p", "--on-primary", dest="on_primary",
1441 default=False, action="store_true",
1442 help=("Replace the disk(s) on the primary"
1443 " node (only for the drbd template)")),
1444 cli_option("-s", "--on-secondary", dest="on_secondary",
1445 default=False, action="store_true",
1446 help=("Replace the disk(s) on the secondary"
1447 " node (only for the drbd template)")),
1448 cli_option("-a", "--auto", dest="auto",
1449 default=False, action="store_true",
1450 help=("Automatically replace faulty disks"
1451 " (only for the drbd template)")),
1456 "[-s|-p|-n NODE|-I NAME] <instance>",
1457 "Replaces all disks for the instance"),
1458 'modify': (SetInstanceParams, ARGS_ONE_INSTANCE,
1459 [BACKEND_OPT, DEBUG_OPT, DISK_OPT, FORCE_OPT, HVOPTS_OPT,
1460 NET_OPT, SUBMIT_OPT],
1461 "<instance>", "Alters the parameters of an instance"),
1462 'shutdown': (ShutdownInstance, [ArgInstance(min=1)],
1463 [DEBUG_OPT, m_node_opt, m_pri_node_opt, m_sec_node_opt,
1464 m_clust_opt, m_inst_opt, m_force_multi,
1467 "<instance>", "Stops an instance"),
1468 'startup': (StartupInstance, [ArgInstance(min=1)],
1469 [DEBUG_OPT, FORCE_OPT, m_force_multi,
1470 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1471 m_clust_opt, m_inst_opt,
1476 "<instance>", "Starts an instance"),
1477 'reboot': (RebootInstance, [ArgInstance(min=1)],
1478 [DEBUG_OPT, m_force_multi,
1479 cli_option("-t", "--type", dest="reboot_type",
1480 help="Type of reboot: soft/hard/full",
1481 default=constants.INSTANCE_REBOOT_HARD,
1483 choices=list(constants.REBOOT_TYPES)),
1484 cli_option("--ignore-secondaries", dest="ignore_secondaries",
1485 default=False, action="store_true",
1486 help="Ignore errors from secondaries"),
1487 m_node_opt, m_pri_node_opt, m_sec_node_opt,
1488 m_clust_opt, m_inst_opt,
1491 "<instance>", "Reboots an instance"),
1492 'activate-disks': (ActivateDisks, ARGS_ONE_INSTANCE,
1493 [DEBUG_OPT, SUBMIT_OPT,
1494 cli_option("--ignore-size", dest="ignore_size",
1495 default=False, action="store_true",
1496 help="Ignore current recorded size"
1497 " (useful for forcing activation when"
1498 " the recorded size is wrong)"),
1501 "Activate an instance's disks"),
1502 'deactivate-disks': (DeactivateDisks, ARGS_ONE_INSTANCE,
1503 [DEBUG_OPT, SUBMIT_OPT],
1505 "Deactivate an instance's disks"),
1506 'recreate-disks': (RecreateDisks, ARGS_ONE_INSTANCE,
1507 [DEBUG_OPT, SUBMIT_OPT, DISKIDX_OPT],
1509 "Recreate an instance's disks"),
1510 'grow-disk': (GrowDisk,
1511 [ArgInstance(min=1, max=1), ArgUnknown(min=1, max=1),
1512 ArgUnknown(min=1, max=1)],
1513 [DEBUG_OPT, SUBMIT_OPT, NWSYNC_OPT],
1514 "<instance> <disk> <size>", "Grow an instance's disk"),
1515 'list-tags': (ListTags, ARGS_ONE_INSTANCE, [DEBUG_OPT],
1516 "<instance_name>", "List the tags of the given instance"),
1517 'add-tags': (AddTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1518 [DEBUG_OPT, TAG_SRC_OPT],
1519 "<instance_name> tag...", "Add tags to the given instance"),
1520 'remove-tags': (RemoveTags, [ArgInstance(min=1, max=1), ArgUnknown()],
1521 [DEBUG_OPT, TAG_SRC_OPT],
1522 "<instance_name> tag...", "Remove tags from given instance"),
1525 #: dictionary with aliases for commands
1527 'activate_block_devs': 'activate-disks',
1528 'replace_disks': 'replace-disks',
1534 if __name__ == '__main__':
1535 sys.exit(GenericMain(commands, aliases=aliases,
1536 override={"tag_type": constants.TAG_INSTANCE}))