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
37 from ganeti import objects
41 def InitCluster(opts, args):
42 """Initialize the cluster.
44 @param opts: the command line options selected by the user
46 @param args: should contain only one element, the desired
49 @return: the desired exit code
52 if not opts.lvm_storage and opts.vg_name:
53 ToStderr("Options --no-lvm-storage and --vg-name conflict.")
56 vg_name = opts.vg_name
57 if opts.lvm_storage and not opts.vg_name:
58 vg_name = constants.DEFAULT_VG
60 hvlist = opts.enabled_hypervisors
61 if hvlist is not None:
62 hvlist = hvlist.split(",")
64 hvlist = [opts.default_hypervisor]
66 # avoid an impossible situation
67 if opts.default_hypervisor not in hvlist:
68 ToStderr("The default hypervisor requested (%s) is not"
69 " within the enabled hypervisor list (%s)" %
70 (opts.default_hypervisor, hvlist))
73 hvparams = dict(opts.hvparams)
74 beparams = opts.beparams
76 # prepare beparams dict
77 beparams = objects.FillDict(constants.BEC_DEFAULTS, beparams)
78 utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
80 # prepare hvparams dict
81 for hv in constants.HYPER_TYPES:
82 if hv not in hvparams:
84 hvparams[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], hvparams[hv])
85 utils.ForceDictType(hvparams[hv], constants.HVS_PARAMETER_TYPES)
88 if hv not in constants.HYPER_TYPES:
89 ToStderr("invalid hypervisor: %s", hv)
92 bootstrap.InitCluster(cluster_name=args[0],
93 secondary_ip=opts.secondary_ip,
95 mac_prefix=opts.mac_prefix,
96 def_bridge=opts.def_bridge,
97 master_netdev=opts.master_netdev,
98 file_storage_dir=opts.file_storage_dir,
99 enabled_hypervisors=hvlist,
100 default_hypervisor=opts.default_hypervisor,
103 candidate_pool_size=opts.candidate_pool_size,
104 modify_etc_hosts=opts.modify_etc_hosts,
110 def DestroyCluster(opts, args):
111 """Destroy the cluster.
113 @param opts: the command line options selected by the user
115 @param args: should be an empty list
117 @return: the desired exit code
120 if not opts.yes_do_it:
121 ToStderr("Destroying a cluster is irreversible. If you really want"
122 " destroy this cluster, supply the --yes-do-it option.")
125 op = opcodes.OpDestroyCluster()
126 master = SubmitOpCode(op)
127 # if we reached this, the opcode didn't fail; we can proceed to
128 # shutdown all the daemons
129 bootstrap.FinalizeClusterDestroy(master)
133 def RenameCluster(opts, args):
134 """Rename the cluster.
136 @param opts: the command line options selected by the user
138 @param args: should contain only one element, the new cluster name
140 @return: the desired exit code
145 usertext = ("This will rename the cluster to '%s'. If you are connected"
146 " over the network to the cluster name, the operation is very"
147 " dangerous as the IP address will be removed from the node"
148 " and the change may not go through. Continue?") % name
149 if not AskUser(usertext):
152 op = opcodes.OpRenameCluster(name=name)
157 def RedistributeConfig(opts, args):
158 """Forces push of the cluster configuration.
160 @param opts: the command line options selected by the user
162 @param args: empty list
164 @return: the desired exit code
167 op = opcodes.OpRedistributeConfig()
168 SubmitOrSend(op, opts)
172 def ShowClusterVersion(opts, args):
173 """Write version of ganeti software to the standard output.
175 @param opts: the command line options selected by the user
177 @param args: should be an empty list
179 @return: the desired exit code
183 result = cl.QueryClusterInfo()
184 ToStdout("Software version: %s", result["software_version"])
185 ToStdout("Internode protocol: %s", result["protocol_version"])
186 ToStdout("Configuration format: %s", result["config_version"])
187 ToStdout("OS api version: %s", result["os_api_version"])
188 ToStdout("Export interface: %s", result["export_version"])
192 def ShowClusterMaster(opts, args):
193 """Write name of master node to the standard output.
195 @param opts: the command line options selected by the user
197 @param args: should be an empty list
199 @return: the desired exit code
202 master = bootstrap.GetMaster()
207 def ShowClusterConfig(opts, args):
208 """Shows cluster information.
210 @param opts: the command line options selected by the user
212 @param args: should be an empty list
214 @return: the desired exit code
218 result = cl.QueryClusterInfo()
220 ToStdout("Cluster name: %s", result["name"])
222 ToStdout("Master node: %s", result["master"])
224 ToStdout("Architecture (this node): %s (%s)",
225 result["architecture"][0], result["architecture"][1])
227 ToStdout("Default hypervisor: %s", result["default_hypervisor"])
228 ToStdout("Enabled hypervisors: %s", ", ".join(result["enabled_hypervisors"]))
230 ToStdout("Hypervisor parameters:")
231 for hv_name, hv_dict in result["hvparams"].items():
232 ToStdout(" - %s:", hv_name)
233 for item, val in hv_dict.iteritems():
234 ToStdout(" %s: %s", item, val)
236 ToStdout("Cluster parameters:")
237 ToStdout(" - candidate pool size: %s", result["candidate_pool_size"])
238 ToStdout(" - master netdev: %s", result["master_netdev"])
239 ToStdout(" - default bridge: %s", result["default_bridge"])
240 ToStdout(" - lvm volume group: %s", result["volume_group_name"])
241 ToStdout(" - file storage path: %s", result["file_storage_dir"])
243 ToStdout("Default instance parameters:")
244 for gr_name, gr_dict in result["beparams"].items():
245 ToStdout(" - %s:", gr_name)
246 for item, val in gr_dict.iteritems():
247 ToStdout(" %s: %s", item, val)
252 def ClusterCopyFile(opts, args):
253 """Copy a file from master to some nodes.
255 @param opts: the command line options selected by the user
257 @param args: should contain only one element, the path of
258 the file to be copied
260 @return: the desired exit code
264 if not os.path.exists(filename):
265 raise errors.OpPrereqError("No such filename '%s'" % filename)
269 myname = utils.HostInfo().name
271 cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
273 results = GetOnlineNodes(nodes=opts.nodes, cl=cl)
274 results = [name for name in results if name != myname]
276 srun = ssh.SshRunner(cluster_name=cluster_name)
278 if not srun.CopyFileToNode(node, filename):
279 ToStderr("Copy of file %s to node %s failed", filename, node)
284 def RunClusterCommand(opts, args):
285 """Run a command on some nodes.
287 @param opts: the command line options selected by the user
289 @param args: should contain the command to be run and its arguments
291 @return: the desired exit code
296 command = " ".join(args)
298 nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl)
300 cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
303 srun = ssh.SshRunner(cluster_name=cluster_name)
305 # Make sure master node is at list end
306 if master_node in nodes:
307 nodes.remove(master_node)
308 nodes.append(master_node)
311 result = srun.Run(name, "root", command)
312 ToStdout("------------------------------------------------")
313 ToStdout("node: %s", name)
314 ToStdout("%s", result.output)
315 ToStdout("return code = %s", result.exit_code)
320 def VerifyCluster(opts, args):
321 """Verify integrity of cluster, performing various test on nodes.
323 @param opts: the command line options selected by the user
325 @param args: should be an empty list
327 @return: the desired exit code
331 if opts.skip_nplusone_mem:
332 skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
333 op = opcodes.OpVerifyCluster(skip_checks=skip_checks)
340 def VerifyDisks(opts, args):
341 """Verify integrity of cluster disks.
343 @param opts: the command line options selected by the user
345 @param args: should be an empty list
347 @return: the desired exit code
350 op = opcodes.OpVerifyDisks()
351 result = SubmitOpCode(op)
352 if not isinstance(result, (list, tuple)) or len(result) != 4:
353 raise errors.ProgrammerError("Unknown result type for OpVerifyDisks")
355 nodes, nlvm, instances, missing = result
358 ToStdout("Nodes unreachable or with bad data:")
360 ToStdout("\t%s", name)
361 retcode = constants.EXIT_SUCCESS
364 for node, text in nlvm.iteritems():
365 ToStdout("Error on node %s: LVM error: %s",
366 node, utils.SafeEncode(text[-400:]))
368 ToStdout("You need to fix these nodes first before fixing instances")
371 for iname in instances:
374 op = opcodes.OpActivateInstanceDisks(instance_name=iname)
376 ToStdout("Activating disks for instance '%s'", iname)
378 except errors.GenericError, err:
379 nret, msg = FormatError(err)
381 ToStderr("Error activating disks for instance %s: %s", iname, msg)
384 for iname, ival in missing.iteritems():
385 all_missing = utils.all(ival, lambda x: x[0] in nlvm)
387 ToStdout("Instance %s cannot be verified as it lives on"
388 " broken nodes", iname)
390 ToStdout("Instance %s has missing logical volumes:", iname)
392 for node, vol in ival:
394 ToStdout("\tbroken node %s /dev/xenvg/%s", node, vol)
396 ToStdout("\t%s /dev/xenvg/%s", node, vol)
397 ToStdout("You need to run replace_disks for all the above"
398 " instances, if this message persist after fixing nodes.")
405 def MasterFailover(opts, args):
406 """Failover the master node.
408 This command, when run on a non-master node, will cause the current
409 master to cease being master, and the non-master to become new
412 @param opts: the command line options selected by the user
414 @param args: should be an empty list
416 @return: the desired exit code
419 return bootstrap.MasterFailover()
422 def SearchTags(opts, args):
423 """Searches the tags on all the cluster.
425 @param opts: the command line options selected by the user
427 @param args: should contain only one element, the tag pattern
429 @return: the desired exit code
432 op = opcodes.OpSearchTags(pattern=args[0])
433 result = SubmitOpCode(op)
436 result = list(result)
438 for path, tag in result:
439 ToStdout("%s %s", path, tag)
442 def SetClusterParams(opts, args):
443 """Modify the cluster.
445 @param opts: the command line options selected by the user
447 @param args: should be an empty list
449 @return: the desired exit code
452 if not (not opts.lvm_storage or opts.vg_name or
453 opts.enabled_hypervisors or opts.hvparams or
454 opts.beparams or opts.candidate_pool_size is not None):
455 ToStderr("Please give at least one of the parameters.")
458 vg_name = opts.vg_name
459 if not opts.lvm_storage and opts.vg_name:
460 ToStdout("Options --no-lvm-storage and --vg-name conflict.")
462 elif not opts.lvm_storage:
465 hvlist = opts.enabled_hypervisors
466 if hvlist is not None:
467 hvlist = hvlist.split(",")
469 # a list of (name, dict) we can pass directly to dict() (or [])
470 hvparams = dict(opts.hvparams)
471 for hv, hv_params in hvparams.iteritems():
472 utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
474 beparams = opts.beparams
475 utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
477 op = opcodes.OpSetClusterParams(vg_name=vg_name,
478 enabled_hypervisors=hvlist,
481 candidate_pool_size=opts.candidate_pool_size)
486 def QueueOps(opts, args):
489 @param opts: the command line options selected by the user
491 @param args: should contain only one element, the subcommand
493 @return: the desired exit code
498 if command in ("drain", "undrain"):
499 drain_flag = command == "drain"
500 client.SetQueueDrainFlag(drain_flag)
501 elif command == "info":
502 result = client.QueryConfigValues(["drain_flag"])
507 ToStdout("The drain flag is %s" % val)
509 raise errors.OpPrereqError("Command '%s' is not valid." % command)
513 # this is an option common to more than one command, so we declare
514 # it here and reuse it
515 node_option = make_option("-n", "--node", action="append", dest="nodes",
516 help="Node to copy to (if not given, all nodes),"
517 " can be given multiple times",
518 metavar="<node>", default=[])
521 'init': (InitCluster, ARGS_ONE,
523 make_option("-s", "--secondary-ip", dest="secondary_ip",
524 help="Specify the secondary ip for this node;"
525 " if given, the entire cluster must have secondary"
527 metavar="ADDRESS", default=None),
528 make_option("-m", "--mac-prefix", dest="mac_prefix",
529 help="Specify the mac prefix for the instance IP"
530 " addresses, in the format XX:XX:XX",
532 default=constants.DEFAULT_MAC_PREFIX,),
533 make_option("-g", "--vg-name", dest="vg_name",
534 help="Specify the volume group name "
535 " (cluster-wide) for disk allocation [xenvg]",
538 make_option("-b", "--bridge", dest="def_bridge",
539 help="Specify the default bridge name (cluster-wide)"
540 " to connect the instances to [%s]" %
541 constants.DEFAULT_BRIDGE,
543 default=constants.DEFAULT_BRIDGE,),
544 make_option("--master-netdev", dest="master_netdev",
545 help="Specify the node interface (cluster-wide)"
546 " on which the master IP address will be added "
547 " [%s]" % constants.DEFAULT_BRIDGE,
549 default=constants.DEFAULT_BRIDGE,),
550 make_option("--file-storage-dir", dest="file_storage_dir",
551 help="Specify the default directory (cluster-wide)"
552 " for storing the file-based disks [%s]" %
553 constants.DEFAULT_FILE_STORAGE_DIR,
555 default=constants.DEFAULT_FILE_STORAGE_DIR,),
556 make_option("--no-lvm-storage", dest="lvm_storage",
557 help="No support for lvm based instances"
559 action="store_false", default=True,),
560 make_option("--no-etc-hosts", dest="modify_etc_hosts",
561 help="Don't modify /etc/hosts"
563 action="store_false", default=True,),
564 make_option("--enabled-hypervisors", dest="enabled_hypervisors",
565 help="Comma-separated list of hypervisors",
566 type="string", default=None),
567 make_option("-t", "--default-hypervisor",
568 dest="default_hypervisor",
569 help="Default hypervisor to use for instance creation",
570 choices=list(constants.HYPER_TYPES),
571 default=constants.DEFAULT_ENABLED_HYPERVISOR),
572 ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
573 help="Hypervisor and hypervisor options, in the"
575 " hypervisor:option=value,option=value,...",
579 keyval_option("-B", "--backend-parameters", dest="beparams",
580 type="keyval", default={},
581 help="Backend parameters"),
582 make_option("-C", "--candidate-pool-size",
583 default=constants.MASTER_POOL_SIZE_DEFAULT,
584 help="Set the candidate pool size",
585 dest="candidate_pool_size", type="int"),
587 "[opts...] <cluster_name>",
588 "Initialises a new cluster configuration"),
589 'destroy': (DestroyCluster, ARGS_NONE,
591 make_option("--yes-do-it", dest="yes_do_it",
592 help="Destroy cluster",
593 action="store_true"),
595 "", "Destroy cluster"),
596 'rename': (RenameCluster, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
598 "Renames the cluster"),
599 'redist-conf': (RedistributeConfig, ARGS_NONE, [DEBUG_OPT, SUBMIT_OPT],
601 "Forces a push of the configuration file and ssconf files"
602 " to the nodes in the cluster"),
603 'verify': (VerifyCluster, ARGS_NONE, [DEBUG_OPT,
604 make_option("--no-nplus1-mem", dest="skip_nplusone_mem",
605 help="Skip N+1 memory redundancy tests",
609 "", "Does a check on the cluster configuration"),
610 'verify-disks': (VerifyDisks, ARGS_NONE, [DEBUG_OPT],
611 "", "Does a check on the cluster disk status"),
612 'masterfailover': (MasterFailover, ARGS_NONE, [DEBUG_OPT],
613 "", "Makes the current node the master"),
614 'version': (ShowClusterVersion, ARGS_NONE, [DEBUG_OPT],
615 "", "Shows the cluster version"),
616 'getmaster': (ShowClusterMaster, ARGS_NONE, [DEBUG_OPT],
617 "", "Shows the cluster master"),
618 'copyfile': (ClusterCopyFile, ARGS_ONE, [DEBUG_OPT, node_option],
619 "[-n node...] <filename>",
620 "Copies a file to all (or only some) nodes"),
621 'command': (RunClusterCommand, ARGS_ATLEAST(1), [DEBUG_OPT, node_option],
622 "[-n node...] <command>",
623 "Runs a command on all (or only some) nodes"),
624 'info': (ShowClusterConfig, ARGS_NONE, [DEBUG_OPT],
625 "", "Show cluster configuration"),
626 'list-tags': (ListTags, ARGS_NONE,
627 [DEBUG_OPT], "", "List the tags of the cluster"),
628 'add-tags': (AddTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
629 "tag...", "Add tags to the cluster"),
630 'remove-tags': (RemoveTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
631 "tag...", "Remove tags from the cluster"),
632 'search-tags': (SearchTags, ARGS_ONE,
633 [DEBUG_OPT], "", "Searches the tags on all objects on"
634 " the cluster for a given pattern (regex)"),
635 'queue': (QueueOps, ARGS_ONE, [DEBUG_OPT],
636 "drain|undrain|info", "Change queue properties"),
637 'modify': (SetClusterParams, ARGS_NONE,
639 make_option("-g", "--vg-name", dest="vg_name",
640 help="Specify the volume group name "
641 " (cluster-wide) for disk allocation "
642 "and enable lvm based storage",
644 make_option("--no-lvm-storage", dest="lvm_storage",
645 help="Disable support for lvm based instances"
647 action="store_false", default=True,),
648 make_option("--enabled-hypervisors", dest="enabled_hypervisors",
649 help="Comma-separated list of hypervisors",
650 type="string", default=None),
651 ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
652 help="Hypervisor and hypervisor options, in the"
654 " hypervisor:option=value,option=value,...",
658 keyval_option("-B", "--backend-parameters", dest="beparams",
659 type="keyval", default={},
660 help="Backend parameters"),
661 make_option("-C", "--candidate-pool-size", default=None,
662 help="Set the candidate pool size",
663 dest="candidate_pool_size", type="int"),
666 "Alters the parameters of the cluster"),
669 if __name__ == '__main__':
670 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER}))