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)
27 from optparse import make_option
30 from ganeti.cli import *
31 from ganeti import opcodes
32 from ganeti import constants
33 from ganeti import errors
34 from ganeti import utils
35 from ganeti import bootstrap
36 from ganeti import ssh
40 def InitCluster(opts, args):
41 """Initialize the cluster.
43 @param opts: the command line options selected by the user
45 @param args: should contain only one element, the desired
48 @return: the desired exit code
51 if not opts.lvm_storage and opts.vg_name:
52 ToStderr("Options --no-lvm-storage and --vg-name conflict.")
55 vg_name = opts.vg_name
56 if opts.lvm_storage and not opts.vg_name:
57 vg_name = constants.DEFAULT_VG
59 hvlist = opts.enabled_hypervisors
60 if hvlist is not None:
61 hvlist = hvlist.split(",")
63 hvlist = [opts.default_hypervisor]
65 # avoid an impossible situation
66 if opts.default_hypervisor not in hvlist:
67 ToStderr("The default hypervisor requested (%s) is not"
68 " within the enabled hypervisor list (%s)" %
69 (opts.default_hypervisor, hvlist))
72 hvparams = dict(opts.hvparams)
74 beparams = opts.beparams
75 # check for invalid parameters
76 for parameter in beparams:
77 if parameter not in constants.BES_PARAMETERS:
78 ToStderr("Invalid backend parameter: %s", parameter)
81 # prepare beparams dict
82 for parameter in constants.BES_PARAMETERS:
83 if parameter not in beparams:
84 beparams[parameter] = constants.BEC_DEFAULTS[parameter]
85 utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
87 # prepare hvparams dict
88 for hv in constants.HYPER_TYPES:
89 if hv not in hvparams:
91 for parameter in constants.HVC_DEFAULTS[hv]:
92 if parameter not in hvparams[hv]:
93 hvparams[hv][parameter] = constants.HVC_DEFAULTS[hv][parameter]
94 utils.ForceDictType(hvparams[hv], constants.HVS_PARAMETER_TYPES)
97 if hv not in constants.HYPER_TYPES:
98 ToStderr("invalid hypervisor: %s", hv)
101 bootstrap.InitCluster(cluster_name=args[0],
102 secondary_ip=opts.secondary_ip,
104 mac_prefix=opts.mac_prefix,
105 def_bridge=opts.def_bridge,
106 master_netdev=opts.master_netdev,
107 file_storage_dir=opts.file_storage_dir,
108 enabled_hypervisors=hvlist,
109 default_hypervisor=opts.default_hypervisor,
112 candidate_pool_size=opts.candidate_pool_size,
118 def DestroyCluster(opts, args):
119 """Destroy the cluster.
121 @param opts: the command line options selected by the user
123 @param args: should be an empty list
125 @return: the desired exit code
128 if not opts.yes_do_it:
129 ToStderr("Destroying a cluster is irreversible. If you really want"
130 " destroy this cluster, supply the --yes-do-it option.")
133 op = opcodes.OpDestroyCluster()
134 master = SubmitOpCode(op)
135 # if we reached this, the opcode didn't fail; we can proceed to
136 # shutdown all the daemons
137 bootstrap.FinalizeClusterDestroy(master)
141 def RenameCluster(opts, args):
142 """Rename the cluster.
144 @param opts: the command line options selected by the user
146 @param args: should contain only one element, the new cluster name
148 @return: the desired exit code
153 usertext = ("This will rename the cluster to '%s'. If you are connected"
154 " over the network to the cluster name, the operation is very"
155 " dangerous as the IP address will be removed from the node"
156 " and the change may not go through. Continue?") % name
157 if not AskUser(usertext):
160 op = opcodes.OpRenameCluster(name=name)
165 def RedistributeConfig(opts, args):
166 """Forces push of the cluster configuration.
168 @param opts: the command line options selected by the user
170 @param args: empty list
172 @return: the desired exit code
175 op = opcodes.OpRedistributeConfig()
176 SubmitOrSend(op, opts)
180 def ShowClusterVersion(opts, args):
181 """Write version of ganeti software to the standard output.
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
191 result = cl.QueryClusterInfo()
192 ToStdout("Software version: %s", result["software_version"])
193 ToStdout("Internode protocol: %s", result["protocol_version"])
194 ToStdout("Configuration format: %s", result["config_version"])
195 ToStdout("OS api version: %s", result["os_api_version"])
196 ToStdout("Export interface: %s", result["export_version"])
200 def ShowClusterMaster(opts, args):
201 """Write name of master node to the standard output.
203 @param opts: the command line options selected by the user
205 @param args: should be an empty list
207 @return: the desired exit code
210 master = bootstrap.GetMaster()
215 def ShowClusterConfig(opts, args):
216 """Shows cluster information.
218 @param opts: the command line options selected by the user
220 @param args: should be an empty list
222 @return: the desired exit code
226 result = cl.QueryClusterInfo()
228 ToStdout("Cluster name: %s", result["name"])
230 ToStdout("Master node: %s", result["master"])
232 ToStdout("Architecture (this node): %s (%s)",
233 result["architecture"][0], result["architecture"][1])
235 ToStdout("Default hypervisor: %s", result["default_hypervisor"])
236 ToStdout("Enabled hypervisors: %s", ", ".join(result["enabled_hypervisors"]))
238 ToStdout("Hypervisor parameters:")
239 for hv_name, hv_dict in result["hvparams"].items():
240 ToStdout(" - %s:", hv_name)
241 for item, val in hv_dict.iteritems():
242 ToStdout(" %s: %s", item, val)
244 ToStdout("Cluster parameters:")
245 ToStdout(" - candidate pool size: %s", result["candidate_pool_size"])
246 ToStdout(" - master netdev: %s", result["master_netdev"])
247 ToStdout(" - default bridge: %s", result["default_bridge"])
248 ToStdout(" - lvm volume group: %s", result["volume_group_name"])
249 ToStdout(" - file storage path: %s", result["file_storage_dir"])
251 ToStdout("Default instance parameters:")
252 for gr_name, gr_dict in result["beparams"].items():
253 ToStdout(" - %s:", gr_name)
254 for item, val in gr_dict.iteritems():
255 ToStdout(" %s: %s", item, val)
260 def ClusterCopyFile(opts, args):
261 """Copy a file from master to some nodes.
263 @param opts: the command line options selected by the user
265 @param args: should contain only one element, the path of
266 the file to be copied
268 @return: the desired exit code
272 if not os.path.exists(filename):
273 raise errors.OpPrereqError("No such filename '%s'" % filename)
277 myname = utils.HostInfo().name
279 cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
281 results = GetOnlineNodes(nodes=opts.nodes, cl=cl)
282 results = [name for name in results if name != myname]
284 srun = ssh.SshRunner(cluster_name=cluster_name)
286 if not srun.CopyFileToNode(node, filename):
287 ToStderr("Copy of file %s to node %s failed", filename, node)
292 def RunClusterCommand(opts, args):
293 """Run a command on some nodes.
295 @param opts: the command line options selected by the user
297 @param args: should contain the command to be run and its arguments
299 @return: the desired exit code
304 command = " ".join(args)
306 nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl)
308 cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
311 srun = ssh.SshRunner(cluster_name=cluster_name)
313 # Make sure master node is at list end
314 if master_node in nodes:
315 nodes.remove(master_node)
316 nodes.append(master_node)
319 result = srun.Run(name, "root", command)
320 ToStdout("------------------------------------------------")
321 ToStdout("node: %s", name)
322 ToStdout("%s", result.output)
323 ToStdout("return code = %s", result.exit_code)
328 def VerifyCluster(opts, args):
329 """Verify integrity of cluster, performing various test on nodes.
331 @param opts: the command line options selected by the user
333 @param args: should be an empty list
335 @return: the desired exit code
339 if opts.skip_nplusone_mem:
340 skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
341 op = opcodes.OpVerifyCluster(skip_checks=skip_checks)
348 def VerifyDisks(opts, args):
349 """Verify integrity of cluster disks.
351 @param opts: the command line options selected by the user
353 @param args: should be an empty list
355 @return: the desired exit code
358 op = opcodes.OpVerifyDisks()
359 result = SubmitOpCode(op)
360 if not isinstance(result, (list, tuple)) or len(result) != 4:
361 raise errors.ProgrammerError("Unknown result type for OpVerifyDisks")
363 nodes, nlvm, instances, missing = result
366 ToStdout("Nodes unreachable or with bad data:")
368 ToStdout("\t%s", name)
369 retcode = constants.EXIT_SUCCESS
372 for node, text in nlvm.iteritems():
373 ToStdout("Error on node %s: LVM error: %s",
374 node, utils.SafeEncode(text[-400:]))
376 ToStdout("You need to fix these nodes first before fixing instances")
379 for iname in instances:
382 op = opcodes.OpActivateInstanceDisks(instance_name=iname)
384 ToStdout("Activating disks for instance '%s'", iname)
386 except errors.GenericError, err:
387 nret, msg = FormatError(err)
389 ToStderr("Error activating disks for instance %s: %s", iname, msg)
392 for iname, ival in missing.iteritems():
393 all_missing = utils.all(ival, lambda x: x[0] in nlvm)
395 ToStdout("Instance %s cannot be verified as it lives on"
396 " broken nodes", iname)
398 ToStdout("Instance %s has missing logical volumes:", iname)
400 for node, vol in ival:
402 ToStdout("\tbroken node %s /dev/xenvg/%s", node, vol)
404 ToStdout("\t%s /dev/xenvg/%s", node, vol)
405 ToStdout("You need to run replace_disks for all the above"
406 " instances, if this message persist after fixing nodes.")
413 def MasterFailover(opts, args):
414 """Failover the master node.
416 This command, when run on a non-master node, will cause the current
417 master to cease being master, and the non-master to become new
420 @param opts: the command line options selected by the user
422 @param args: should be an empty list
424 @return: the desired exit code
427 return bootstrap.MasterFailover()
430 def SearchTags(opts, args):
431 """Searches the tags on all the cluster.
433 @param opts: the command line options selected by the user
435 @param args: should contain only one element, the tag pattern
437 @return: the desired exit code
440 op = opcodes.OpSearchTags(pattern=args[0])
441 result = SubmitOpCode(op)
444 result = list(result)
446 for path, tag in result:
447 ToStdout("%s %s", path, tag)
450 def SetClusterParams(opts, args):
451 """Modify the cluster.
453 @param opts: the command line options selected by the user
455 @param args: should be an empty list
457 @return: the desired exit code
460 if not (not opts.lvm_storage or opts.vg_name or
461 opts.enabled_hypervisors or opts.hvparams or
462 opts.beparams or opts.candidate_pool_size is not None):
463 ToStderr("Please give at least one of the parameters.")
466 vg_name = opts.vg_name
467 if not opts.lvm_storage and opts.vg_name:
468 ToStdout("Options --no-lvm-storage and --vg-name conflict.")
470 elif not opts.lvm_storage:
473 hvlist = opts.enabled_hypervisors
474 if hvlist is not None:
475 hvlist = hvlist.split(",")
477 # a list of (name, dict) we can pass directly to dict() (or [])
478 hvparams = dict(opts.hvparams)
479 for hv, hv_params in hvparams.iteritems():
480 utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
482 beparams = opts.beparams
483 utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
485 op = opcodes.OpSetClusterParams(vg_name=vg_name,
486 enabled_hypervisors=hvlist,
489 candidate_pool_size=opts.candidate_pool_size)
494 def QueueOps(opts, args):
497 @param opts: the command line options selected by the user
499 @param args: should contain only one element, the subcommand
501 @return: the desired exit code
506 if command in ("drain", "undrain"):
507 drain_flag = command == "drain"
508 client.SetQueueDrainFlag(drain_flag)
509 elif command == "info":
510 result = client.QueryConfigValues(["drain_flag"])
515 ToStdout("The drain flag is %s" % val)
517 raise errors.OpPrereqError("Command '%s' is not valid." % command)
521 # this is an option common to more than one command, so we declare
522 # it here and reuse it
523 node_option = make_option("-n", "--node", action="append", dest="nodes",
524 help="Node to copy to (if not given, all nodes),"
525 " can be given multiple times",
526 metavar="<node>", default=[])
529 'init': (InitCluster, ARGS_ONE,
531 make_option("-s", "--secondary-ip", dest="secondary_ip",
532 help="Specify the secondary ip for this node;"
533 " if given, the entire cluster must have secondary"
535 metavar="ADDRESS", default=None),
536 make_option("-m", "--mac-prefix", dest="mac_prefix",
537 help="Specify the mac prefix for the instance IP"
538 " addresses, in the format XX:XX:XX",
540 default=constants.DEFAULT_MAC_PREFIX,),
541 make_option("-g", "--vg-name", dest="vg_name",
542 help="Specify the volume group name "
543 " (cluster-wide) for disk allocation [xenvg]",
546 make_option("-b", "--bridge", dest="def_bridge",
547 help="Specify the default bridge name (cluster-wide)"
548 " to connect the instances to [%s]" %
549 constants.DEFAULT_BRIDGE,
551 default=constants.DEFAULT_BRIDGE,),
552 make_option("--master-netdev", dest="master_netdev",
553 help="Specify the node interface (cluster-wide)"
554 " on which the master IP address will be added "
555 " [%s]" % constants.DEFAULT_BRIDGE,
557 default=constants.DEFAULT_BRIDGE,),
558 make_option("--file-storage-dir", dest="file_storage_dir",
559 help="Specify the default directory (cluster-wide)"
560 " for storing the file-based disks [%s]" %
561 constants.DEFAULT_FILE_STORAGE_DIR,
563 default=constants.DEFAULT_FILE_STORAGE_DIR,),
564 make_option("--no-lvm-storage", dest="lvm_storage",
565 help="No support for lvm based instances"
567 action="store_false", default=True,),
568 make_option("--enabled-hypervisors", dest="enabled_hypervisors",
569 help="Comma-separated list of hypervisors",
570 type="string", default=None),
571 make_option("-t", "--default-hypervisor",
572 dest="default_hypervisor",
573 help="Default hypervisor to use for instance creation",
574 choices=list(constants.HYPER_TYPES),
575 default=constants.DEFAULT_ENABLED_HYPERVISOR),
576 ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
577 help="Hypervisor and hypervisor options, in the"
579 " hypervisor:option=value,option=value,...",
583 keyval_option("-B", "--backend-parameters", dest="beparams",
584 type="keyval", default={},
585 help="Backend parameters"),
586 make_option("-C", "--candidate-pool-size",
587 default=constants.MASTER_POOL_SIZE_DEFAULT,
588 help="Set the candidate pool size",
589 dest="candidate_pool_size", type="int"),
591 "[opts...] <cluster_name>",
592 "Initialises a new cluster configuration"),
593 'destroy': (DestroyCluster, ARGS_NONE,
595 make_option("--yes-do-it", dest="yes_do_it",
596 help="Destroy cluster",
597 action="store_true"),
599 "", "Destroy cluster"),
600 'rename': (RenameCluster, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
602 "Renames the cluster"),
603 'redist-conf': (RedistributeConfig, ARGS_NONE, [DEBUG_OPT, SUBMIT_OPT],
605 "Forces a push of the configuration file and ssconf files"
606 " to the nodes in the cluster"),
607 'verify': (VerifyCluster, ARGS_NONE, [DEBUG_OPT,
608 make_option("--no-nplus1-mem", dest="skip_nplusone_mem",
609 help="Skip N+1 memory redundancy tests",
613 "", "Does a check on the cluster configuration"),
614 'verify-disks': (VerifyDisks, ARGS_NONE, [DEBUG_OPT],
615 "", "Does a check on the cluster disk status"),
616 'masterfailover': (MasterFailover, ARGS_NONE, [DEBUG_OPT],
617 "", "Makes the current node the master"),
618 'version': (ShowClusterVersion, ARGS_NONE, [DEBUG_OPT],
619 "", "Shows the cluster version"),
620 'getmaster': (ShowClusterMaster, ARGS_NONE, [DEBUG_OPT],
621 "", "Shows the cluster master"),
622 'copyfile': (ClusterCopyFile, ARGS_ONE, [DEBUG_OPT, node_option],
623 "[-n node...] <filename>",
624 "Copies a file to all (or only some) nodes"),
625 'command': (RunClusterCommand, ARGS_ATLEAST(1), [DEBUG_OPT, node_option],
626 "[-n node...] <command>",
627 "Runs a command on all (or only some) nodes"),
628 'info': (ShowClusterConfig, ARGS_NONE, [DEBUG_OPT],
629 "", "Show cluster configuration"),
630 'list-tags': (ListTags, ARGS_NONE,
631 [DEBUG_OPT], "", "List the tags of the cluster"),
632 'add-tags': (AddTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
633 "tag...", "Add tags to the cluster"),
634 'remove-tags': (RemoveTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
635 "tag...", "Remove tags from the cluster"),
636 'search-tags': (SearchTags, ARGS_ONE,
637 [DEBUG_OPT], "", "Searches the tags on all objects on"
638 " the cluster for a given pattern (regex)"),
639 'queue': (QueueOps, ARGS_ONE, [DEBUG_OPT],
640 "drain|undrain|info", "Change queue properties"),
641 'modify': (SetClusterParams, ARGS_NONE,
643 make_option("-g", "--vg-name", dest="vg_name",
644 help="Specify the volume group name "
645 " (cluster-wide) for disk allocation "
646 "and enable lvm based storage",
648 make_option("--no-lvm-storage", dest="lvm_storage",
649 help="Disable support for lvm based instances"
651 action="store_false", default=True,),
652 make_option("--enabled-hypervisors", dest="enabled_hypervisors",
653 help="Comma-separated list of hypervisors",
654 type="string", default=None),
655 ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
656 help="Hypervisor and hypervisor options, in the"
658 " hypervisor:option=value,option=value,...",
662 keyval_option("-B", "--backend-parameters", dest="beparams",
663 type="keyval", default={},
664 help="Backend parameters"),
665 make_option("-C", "--candidate-pool-size", default=None,
666 help="Set the candidate pool size",
667 dest="candidate_pool_size", type="int"),
670 "Alters the parameters of the cluster"),
673 if __name__ == '__main__':
674 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER}))