Create a new --no-voting option for masterfailover
[ganeti-local] / scripts / gnt-cluster
1 #!/usr/bin/python
2 #
3
4 # Copyright (C) 2006, 2007 Google Inc.
5 #
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.
10 #
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.
15 #
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
19 # 02110-1301, USA.
20
21
22 # pylint: disable-msg=W0401,W0614
23 # W0401: Wildcard import ganeti.cli
24 # W0614: Unused import %s from wildcard import (since we need cli)
25
26 import sys
27 from optparse import make_option
28 import os.path
29
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
38
39 @UsesRPC
40 def InitCluster(opts, args):
41   """Initialize the cluster.
42
43   @param opts: the command line options selected by the user
44   @type args: list
45   @param args: should contain only one element, the desired
46       cluster name
47   @rtype: int
48   @return: the desired exit code
49
50   """
51   if not opts.lvm_storage and opts.vg_name:
52     ToStderr("Options --no-lvm-storage and --vg-name conflict.")
53     return 1
54
55   vg_name = opts.vg_name
56   if opts.lvm_storage and not opts.vg_name:
57     vg_name = constants.DEFAULT_VG
58
59   hvlist = opts.enabled_hypervisors
60   if hvlist is not None:
61     hvlist = hvlist.split(",")
62   else:
63     hvlist = [opts.default_hypervisor]
64
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))
70     return 1
71
72   hvparams = dict(opts.hvparams)
73
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)
79       return 1
80
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)
86
87   # prepare hvparams dict
88   for hv in constants.HYPER_TYPES:
89     if hv not in hvparams:
90       hvparams[hv] = {}
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)
95
96   for hv in hvlist:
97     if hv not in constants.HYPER_TYPES:
98       ToStderr("invalid hypervisor: %s", hv)
99       return 1
100
101   bootstrap.InitCluster(cluster_name=args[0],
102                         secondary_ip=opts.secondary_ip,
103                         vg_name=vg_name,
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,
110                         hvparams=hvparams,
111                         beparams=beparams,
112                         candidate_pool_size=opts.candidate_pool_size,
113                         )
114   return 0
115
116
117 @UsesRPC
118 def DestroyCluster(opts, args):
119   """Destroy the cluster.
120
121   @param opts: the command line options selected by the user
122   @type args: list
123   @param args: should be an empty list
124   @rtype: int
125   @return: the desired exit code
126
127   """
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.")
131     return 1
132
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)
138   return 0
139
140
141 def RenameCluster(opts, args):
142   """Rename the cluster.
143
144   @param opts: the command line options selected by the user
145   @type args: list
146   @param args: should contain only one element, the new cluster name
147   @rtype: int
148   @return: the desired exit code
149
150   """
151   name = args[0]
152   if not opts.force:
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):
158       return 1
159
160   op = opcodes.OpRenameCluster(name=name)
161   SubmitOpCode(op)
162   return 0
163
164
165 def RedistributeConfig(opts, args):
166   """Forces push of the cluster configuration.
167
168   @param opts: the command line options selected by the user
169   @type args: list
170   @param args: empty list
171   @rtype: int
172   @return: the desired exit code
173
174   """
175   op = opcodes.OpRedistributeConfig()
176   SubmitOrSend(op, opts)
177   return 0
178
179
180 def ShowClusterVersion(opts, args):
181   """Write version of ganeti software to the standard output.
182
183   @param opts: the command line options selected by the user
184   @type args: list
185   @param args: should be an empty list
186   @rtype: int
187   @return: the desired exit code
188
189   """
190   cl = GetClient()
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"])
197   return 0
198
199
200 def ShowClusterMaster(opts, args):
201   """Write name of master node to the standard output.
202
203   @param opts: the command line options selected by the user
204   @type args: list
205   @param args: should be an empty list
206   @rtype: int
207   @return: the desired exit code
208
209   """
210   master = bootstrap.GetMaster()
211   ToStdout(master)
212   return 0
213
214
215 def ShowClusterConfig(opts, args):
216   """Shows cluster information.
217
218   @param opts: the command line options selected by the user
219   @type args: list
220   @param args: should be an empty list
221   @rtype: int
222   @return: the desired exit code
223
224   """
225   cl = GetClient()
226   result = cl.QueryClusterInfo()
227
228   ToStdout("Cluster name: %s", result["name"])
229
230   ToStdout("Master node: %s", result["master"])
231
232   ToStdout("Architecture (this node): %s (%s)",
233            result["architecture"][0], result["architecture"][1])
234
235   ToStdout("Default hypervisor: %s", result["default_hypervisor"])
236   ToStdout("Enabled hypervisors: %s", ", ".join(result["enabled_hypervisors"]))
237
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)
243
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"])
250
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)
256
257   return 0
258
259
260 def ClusterCopyFile(opts, args):
261   """Copy a file from master to some nodes.
262
263   @param opts: the command line options selected by the user
264   @type args: list
265   @param args: should contain only one element, the path of
266       the file to be copied
267   @rtype: int
268   @return: the desired exit code
269
270   """
271   filename = args[0]
272   if not os.path.exists(filename):
273     raise errors.OpPrereqError("No such filename '%s'" % filename)
274
275   cl = GetClient()
276
277   myname = utils.HostInfo().name
278
279   cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
280
281   results = GetOnlineNodes(nodes=opts.nodes, cl=cl)
282   results = [name for name in results if name != myname]
283
284   srun = ssh.SshRunner(cluster_name=cluster_name)
285   for node in results:
286     if not srun.CopyFileToNode(node, filename):
287       ToStderr("Copy of file %s to node %s failed", filename, node)
288
289   return 0
290
291
292 def RunClusterCommand(opts, args):
293   """Run a command on some nodes.
294
295   @param opts: the command line options selected by the user
296   @type args: list
297   @param args: should contain the command to be run and its arguments
298   @rtype: int
299   @return: the desired exit code
300
301   """
302   cl = GetClient()
303
304   command = " ".join(args)
305
306   nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl)
307
308   cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
309                                                     "master_node"])
310
311   srun = ssh.SshRunner(cluster_name=cluster_name)
312
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)
317
318   for name in nodes:
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)
324
325   return 0
326
327
328 def VerifyCluster(opts, args):
329   """Verify integrity of cluster, performing various test on nodes.
330
331   @param opts: the command line options selected by the user
332   @type args: list
333   @param args: should be an empty list
334   @rtype: int
335   @return: the desired exit code
336
337   """
338   skip_checks = []
339   if opts.skip_nplusone_mem:
340     skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
341   op = opcodes.OpVerifyCluster(skip_checks=skip_checks)
342   if SubmitOpCode(op):
343     return 0
344   else:
345     return 1
346
347
348 def VerifyDisks(opts, args):
349   """Verify integrity of cluster disks.
350
351   @param opts: the command line options selected by the user
352   @type args: list
353   @param args: should be an empty list
354   @rtype: int
355   @return: the desired exit code
356
357   """
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")
362
363   nodes, nlvm, instances, missing = result
364
365   if nodes:
366     ToStdout("Nodes unreachable or with bad data:")
367     for name in nodes:
368       ToStdout("\t%s", name)
369   retcode = constants.EXIT_SUCCESS
370
371   if nlvm:
372     for node, text in nlvm.iteritems():
373       ToStdout("Error on node %s: LVM error: %s",
374                node, utils.SafeEncode(text[-400:]))
375       retcode |= 1
376       ToStdout("You need to fix these nodes first before fixing instances")
377
378   if instances:
379     for iname in instances:
380       if iname in missing:
381         continue
382       op = opcodes.OpActivateInstanceDisks(instance_name=iname)
383       try:
384         ToStdout("Activating disks for instance '%s'", iname)
385         SubmitOpCode(op)
386       except errors.GenericError, err:
387         nret, msg = FormatError(err)
388         retcode |= nret
389         ToStderr("Error activating disks for instance %s: %s", iname, msg)
390
391   if missing:
392     for iname, ival in missing.iteritems():
393       all_missing = utils.all(ival, lambda x: x[0] in nlvm)
394       if all_missing:
395         ToStdout("Instance %s cannot be verified as it lives on"
396                  " broken nodes", iname)
397       else:
398         ToStdout("Instance %s has missing logical volumes:", iname)
399         ival.sort()
400         for node, vol in ival:
401           if node in nlvm:
402             ToStdout("\tbroken node %s /dev/xenvg/%s", node, vol)
403           else:
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.")
407     retcode |= 1
408
409   return retcode
410
411
412 @UsesRPC
413 def MasterFailover(opts, args):
414   """Failover the master node.
415
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
418   master.
419
420   @param opts: the command line options selected by the user
421   @type args: list
422   @param args: should be an empty list
423   @rtype: int
424   @return: the desired exit code
425
426   """
427   if opts.no_voting:
428     usertext = ("This will perform the failover even if most other nodes"
429                 " are down, or if this node is outdated. This is dangerous"
430                 " as it can lead to a non-consistent cluster. Check the"
431                 " gnt-cluster(8) man page before proceeding. Continue?")
432     if not AskUser(usertext):
433       return 1
434
435   return bootstrap.MasterFailover(no_voting=opts.no_voting)
436
437
438 def SearchTags(opts, args):
439   """Searches the tags on all the cluster.
440
441   @param opts: the command line options selected by the user
442   @type args: list
443   @param args: should contain only one element, the tag pattern
444   @rtype: int
445   @return: the desired exit code
446
447   """
448   op = opcodes.OpSearchTags(pattern=args[0])
449   result = SubmitOpCode(op)
450   if not result:
451     return 1
452   result = list(result)
453   result.sort()
454   for path, tag in result:
455     ToStdout("%s %s", path, tag)
456
457
458 def SetClusterParams(opts, args):
459   """Modify the cluster.
460
461   @param opts: the command line options selected by the user
462   @type args: list
463   @param args: should be an empty list
464   @rtype: int
465   @return: the desired exit code
466
467   """
468   if not (not opts.lvm_storage or opts.vg_name or
469           opts.enabled_hypervisors or opts.hvparams or
470           opts.beparams or opts.candidate_pool_size is not None):
471     ToStderr("Please give at least one of the parameters.")
472     return 1
473
474   vg_name = opts.vg_name
475   if not opts.lvm_storage and opts.vg_name:
476     ToStdout("Options --no-lvm-storage and --vg-name conflict.")
477     return 1
478   elif not opts.lvm_storage:
479     vg_name = ''
480
481   hvlist = opts.enabled_hypervisors
482   if hvlist is not None:
483     hvlist = hvlist.split(",")
484
485   # a list of (name, dict) we can pass directly to dict() (or [])
486   hvparams = dict(opts.hvparams)
487   for hv, hv_params in hvparams.iteritems():
488     utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
489
490   beparams = opts.beparams
491   utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
492
493   op = opcodes.OpSetClusterParams(vg_name=vg_name,
494                                   enabled_hypervisors=hvlist,
495                                   hvparams=hvparams,
496                                   beparams=beparams,
497                                   candidate_pool_size=opts.candidate_pool_size)
498   SubmitOpCode(op)
499   return 0
500
501
502 def QueueOps(opts, args):
503   """Queue operations.
504
505   @param opts: the command line options selected by the user
506   @type args: list
507   @param args: should contain only one element, the subcommand
508   @rtype: int
509   @return: the desired exit code
510
511   """
512   command = args[0]
513   client = GetClient()
514   if command in ("drain", "undrain"):
515     drain_flag = command == "drain"
516     client.SetQueueDrainFlag(drain_flag)
517   elif command == "info":
518     result = client.QueryConfigValues(["drain_flag"])
519     if result[0]:
520       val = "set"
521     else:
522       val = "unset"
523     ToStdout("The drain flag is %s" % val)
524   else:
525     raise errors.OpPrereqError("Command '%s' is not valid." % command)
526
527   return 0
528
529 # this is an option common to more than one command, so we declare
530 # it here and reuse it
531 node_option = make_option("-n", "--node", action="append", dest="nodes",
532                           help="Node to copy to (if not given, all nodes),"
533                                " can be given multiple times",
534                           metavar="<node>", default=[])
535
536 commands = {
537   'init': (InitCluster, ARGS_ONE,
538            [DEBUG_OPT,
539             make_option("-s", "--secondary-ip", dest="secondary_ip",
540                         help="Specify the secondary ip for this node;"
541                         " if given, the entire cluster must have secondary"
542                         " addresses",
543                         metavar="ADDRESS", default=None),
544             make_option("-m", "--mac-prefix", dest="mac_prefix",
545                         help="Specify the mac prefix for the instance IP"
546                         " addresses, in the format XX:XX:XX",
547                         metavar="PREFIX",
548                         default=constants.DEFAULT_MAC_PREFIX,),
549             make_option("-g", "--vg-name", dest="vg_name",
550                         help="Specify the volume group name "
551                         " (cluster-wide) for disk allocation [xenvg]",
552                         metavar="VG",
553                         default=None,),
554             make_option("-b", "--bridge", dest="def_bridge",
555                         help="Specify the default bridge name (cluster-wide)"
556                           " to connect the instances to [%s]" %
557                           constants.DEFAULT_BRIDGE,
558                         metavar="BRIDGE",
559                         default=constants.DEFAULT_BRIDGE,),
560             make_option("--master-netdev", dest="master_netdev",
561                         help="Specify the node interface (cluster-wide)"
562                           " on which the master IP address will be added "
563                           " [%s]" % constants.DEFAULT_BRIDGE,
564                         metavar="NETDEV",
565                         default=constants.DEFAULT_BRIDGE,),
566             make_option("--file-storage-dir", dest="file_storage_dir",
567                         help="Specify the default directory (cluster-wide)"
568                              " for storing the file-based disks [%s]" %
569                              constants.DEFAULT_FILE_STORAGE_DIR,
570                         metavar="DIR",
571                         default=constants.DEFAULT_FILE_STORAGE_DIR,),
572             make_option("--no-lvm-storage", dest="lvm_storage",
573                         help="No support for lvm based instances"
574                              " (cluster-wide)",
575                         action="store_false", default=True,),
576             make_option("--enabled-hypervisors", dest="enabled_hypervisors",
577                         help="Comma-separated list of hypervisors",
578                         type="string", default=None),
579             make_option("-t", "--default-hypervisor",
580                         dest="default_hypervisor",
581                         help="Default hypervisor to use for instance creation",
582                         choices=list(constants.HYPER_TYPES),
583                         default=constants.DEFAULT_ENABLED_HYPERVISOR),
584             ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
585                        help="Hypervisor and hypervisor options, in the"
586                          " format"
587                        " hypervisor:option=value,option=value,...",
588                        default=[],
589                        action="append",
590                        type="identkeyval"),
591             keyval_option("-B", "--backend-parameters", dest="beparams",
592                           type="keyval", default={},
593                           help="Backend parameters"),
594             make_option("-C", "--candidate-pool-size",
595                         default=constants.MASTER_POOL_SIZE_DEFAULT,
596                         help="Set the candidate pool size",
597                         dest="candidate_pool_size", type="int"),
598             ],
599            "[opts...] <cluster_name>",
600            "Initialises a new cluster configuration"),
601   'destroy': (DestroyCluster, ARGS_NONE,
602               [DEBUG_OPT,
603                make_option("--yes-do-it", dest="yes_do_it",
604                            help="Destroy cluster",
605                            action="store_true"),
606               ],
607               "", "Destroy cluster"),
608   'rename': (RenameCluster, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
609                "<new_name>",
610                "Renames the cluster"),
611   'redist-conf': (RedistributeConfig, ARGS_NONE, [DEBUG_OPT, SUBMIT_OPT],
612                   "",
613                   "Forces a push of the configuration file and ssconf files"
614                   " to the nodes in the cluster"),
615   'verify': (VerifyCluster, ARGS_NONE, [DEBUG_OPT,
616              make_option("--no-nplus1-mem", dest="skip_nplusone_mem",
617                          help="Skip N+1 memory redundancy tests",
618                          action="store_true",
619                          default=False,),
620              ],
621              "", "Does a check on the cluster configuration"),
622   'verify-disks': (VerifyDisks, ARGS_NONE, [DEBUG_OPT],
623                    "", "Does a check on the cluster disk status"),
624   'masterfailover': (MasterFailover, ARGS_NONE, [DEBUG_OPT,
625                      make_option("--no-voting", dest="no_voting",
626                                  help="Skip node agreement check (dangerous)",
627                                  action="store_true",
628                                  default=False,),
629                      ],
630                      "", "Makes the current node the master"),
631   'version': (ShowClusterVersion, ARGS_NONE, [DEBUG_OPT],
632               "", "Shows the cluster version"),
633   'getmaster': (ShowClusterMaster, ARGS_NONE, [DEBUG_OPT],
634                 "", "Shows the cluster master"),
635   'copyfile': (ClusterCopyFile, ARGS_ONE, [DEBUG_OPT, node_option],
636                "[-n node...] <filename>",
637                "Copies a file to all (or only some) nodes"),
638   'command': (RunClusterCommand, ARGS_ATLEAST(1), [DEBUG_OPT, node_option],
639               "[-n node...] <command>",
640               "Runs a command on all (or only some) nodes"),
641   'info': (ShowClusterConfig, ARGS_NONE, [DEBUG_OPT],
642                  "", "Show cluster configuration"),
643   'list-tags': (ListTags, ARGS_NONE,
644                 [DEBUG_OPT], "", "List the tags of the cluster"),
645   'add-tags': (AddTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
646                "tag...", "Add tags to the cluster"),
647   'remove-tags': (RemoveTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
648                   "tag...", "Remove tags from the cluster"),
649   'search-tags': (SearchTags, ARGS_ONE,
650                   [DEBUG_OPT], "", "Searches the tags on all objects on"
651                   " the cluster for a given pattern (regex)"),
652   'queue': (QueueOps, ARGS_ONE, [DEBUG_OPT],
653             "drain|undrain|info", "Change queue properties"),
654   'modify': (SetClusterParams, ARGS_NONE,
655              [DEBUG_OPT,
656               make_option("-g", "--vg-name", dest="vg_name",
657                           help="Specify the volume group name "
658                           " (cluster-wide) for disk allocation "
659                           "and enable lvm based storage",
660                           metavar="VG",),
661               make_option("--no-lvm-storage", dest="lvm_storage",
662                           help="Disable support for lvm based instances"
663                                " (cluster-wide)",
664                           action="store_false", default=True,),
665               make_option("--enabled-hypervisors", dest="enabled_hypervisors",
666                           help="Comma-separated list of hypervisors",
667                           type="string", default=None),
668               ikv_option("-H", "--hypervisor-parameters", dest="hvparams",
669                          help="Hypervisor and hypervisor options, in the"
670                          " format"
671                          " hypervisor:option=value,option=value,...",
672                          default=[],
673                          action="append",
674                          type="identkeyval"),
675               keyval_option("-B", "--backend-parameters", dest="beparams",
676                             type="keyval", default={},
677                             help="Backend parameters"),
678               make_option("-C", "--candidate-pool-size", default=None,
679                           help="Set the candidate pool size",
680                           dest="candidate_pool_size", type="int"),
681               ],
682              "[opts...]",
683              "Alters the parameters of the cluster"),
684   }
685
686 if __name__ == '__main__':
687   sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER}))