4 # Copyright (C) 2006, 2007, 2008 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
29 from ganeti.cli import *
30 from ganeti import opcodes
31 from ganeti import utils
32 from ganeti import constants
33 from ganeti import errors
34 from ganeti import bootstrap
37 #: default list of field for L{ListNodes}
39 "name", "dtotal", "dfree",
40 "mtotal", "mnode", "mfree",
41 "pinst_cnt", "sinst_cnt",
44 #: headers (and full field list for L{ListNodes}
46 "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
47 "pinst_list": "PriInstances", "sinst_list": "SecInstances",
48 "pip": "PrimaryIP", "sip": "SecondaryIP",
49 "dtotal": "DTotal", "dfree": "DFree",
50 "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
54 "serial_no": "SerialNo",
55 "master_candidate": "MasterC",
62 def AddNode(opts, args):
63 """Add a node to the cluster.
65 @param opts: the command line options selected by the user
67 @param args: should contain only one element, the new node name
69 @return: the desired exit code
73 dns_data = utils.HostInfo(args[0])
78 output = cl.QueryNodes(names=[node], fields=['name'])
79 except (errors.OpPrereqError, errors.OpExecError):
82 ToStderr("Node %s already in the cluster (as %s)"
83 " - please use --readd", args[0], output[0][0])
86 # read the cluster name from the master
87 output = cl.QueryConfigValues(['cluster_name'])
88 cluster_name = output[0]
90 ToStderr("-- WARNING -- \n"
91 "Performing this operation is going to replace the ssh daemon"
93 "on the target machine (%s) with the ones of the"
95 "and grant full intra-cluster ssh root access to/from it\n", node)
97 bootstrap.SetupNodeDaemon(cluster_name, node, opts.ssh_key_check)
99 op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
104 def ListNodes(opts, args):
105 """List nodes and their properties.
107 @param opts: the command line options selected by the user
109 @param args: should be an empty list
111 @return: the desired exit code
114 if opts.output is None:
115 selected_fields = _LIST_DEF_FIELDS
116 elif opts.output.startswith("+"):
117 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
119 selected_fields = opts.output.split(",")
121 output = GetClient().QueryNodes([], selected_fields)
123 if not opts.no_headers:
124 headers = _LIST_HEADERS
128 unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
130 numfields = ["dtotal", "dfree",
131 "mtotal", "mnode", "mfree",
132 "pinst_cnt", "sinst_cnt",
133 "ctotal", "serial_no"]
135 list_type_fields = ("pinst_list", "sinst_list", "tags")
136 # change raw values to nicer strings
138 for idx, field in enumerate(selected_fields):
140 if field in list_type_fields:
142 elif field in ('master', 'master_candidate', 'offline'):
151 data = GenerateTable(separator=opts.separator, headers=headers,
152 fields=selected_fields, unitfields=unitfields,
153 numfields=numfields, data=output, units=opts.units)
160 def EvacuateNode(opts, args):
161 """Relocate all secondary instance from a node.
163 @param opts: the command line options selected by the user
165 @param args: should be an empty list
167 @return: the desired exit code
171 selected_fields = ["name", "sinst_list"]
172 src_node, dst_node = args
174 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
175 result = SubmitOpCode(op)
176 src_node, sinst = result[0]
177 op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
178 result = SubmitOpCode(op)
179 dst_node = result[0][0]
181 if src_node == dst_node:
182 raise errors.OpPrereqError("Evacuate node needs different source and"
183 " target nodes (node %s given twice)" %
187 ToStderr("No secondary instances on node %s, exiting.", src_node)
188 return constants.EXIT_SUCCESS
190 sinst = utils.NiceSort(sinst)
192 retcode = constants.EXIT_SUCCESS
194 if not force and not AskUser("Relocate instance(s) %s from node\n"
195 " %s to node\n %s?" %
196 (",".join("'%s'" % name for name in sinst),
197 src_node, dst_node)):
198 return constants.EXIT_CONFIRMATION
200 good_cnt = bad_cnt = 0
202 op = opcodes.OpReplaceDisks(instance_name=iname,
203 remote_node=dst_node,
204 mode=constants.REPLACE_DISK_ALL,
205 disks=["sda", "sdb"])
207 ToStdout("Replacing disks for instance %s", iname)
209 ToStdout("Instance %s has been relocated", iname)
211 except errors.GenericError, err:
212 nret, msg = FormatError(err)
214 ToStderr("Error replacing disks for instance %s: %s", iname, msg)
217 if retcode == constants.EXIT_SUCCESS:
218 ToStdout("All %d instance(s) relocated successfully.", good_cnt)
220 ToStdout("There were errors during the relocation:\n"
221 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
225 def FailoverNode(opts, args):
226 """Failover all primary instance on a node.
228 @param opts: the command line options selected by the user
230 @param args: should be an empty list
232 @return: the desired exit code
236 selected_fields = ["name", "pinst_list"]
238 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
239 result = SubmitOpCode(op)
240 node, pinst = result[0]
243 ToStderr("No primary instances on node %s, exiting.", node)
246 pinst = utils.NiceSort(pinst)
250 if not force and not AskUser("Fail over instance(s) %s?" %
251 (",".join("'%s'" % name for name in pinst))):
254 good_cnt = bad_cnt = 0
256 op = opcodes.OpFailoverInstance(instance_name=iname,
257 ignore_consistency=opts.ignore_consistency)
259 ToStdout("Failing over instance %s", iname)
261 ToStdout("Instance %s has been failed over", iname)
263 except errors.GenericError, err:
264 nret, msg = FormatError(err)
266 ToStderr("Error failing over instance %s: %s", iname, msg)
270 ToStdout("All %d instance(s) failed over successfully.", good_cnt)
272 ToStdout("There were errors during the failover:\n"
273 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
277 def ShowNodeConfig(opts, args):
278 """Show node information.
280 @param opts: the command line options selected by the user
282 @param args: should either be an empty list, in which case
283 we show information about all nodes, or should contain
284 a list of nodes to be queried for information
286 @return: the desired exit code
289 op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
290 "pinst_list", "sinst_list"],
292 result = SubmitOpCode(op)
294 for name, primary_ip, secondary_ip, pinst, sinst in result:
295 ToStdout("Node name: %s", name)
296 ToStdout(" primary ip: %s", primary_ip)
297 ToStdout(" secondary ip: %s", secondary_ip)
299 ToStdout(" primary for instances:")
301 ToStdout(" - %s", iname)
303 ToStdout(" primary for no instances")
305 ToStdout(" secondary for instances:")
307 ToStdout(" - %s", iname)
309 ToStdout(" secondary for no instances")
314 def RemoveNode(opts, args):
315 """Remove a node from the cluster.
317 @param opts: the command line options selected by the user
319 @param args: should contain only one element, the name of
320 the node to be removed
322 @return: the desired exit code
325 op = opcodes.OpRemoveNode(node_name=args[0])
330 def ListVolumes(opts, args):
331 """List logical volumes on node(s).
333 @param opts: the command line options selected by the user
335 @param args: should either be an empty list, in which case
336 we list data for all nodes, or contain a list of nodes
337 to display data only for those
339 @return: the desired exit code
342 if opts.output is None:
343 selected_fields = ["node", "phys", "vg",
344 "name", "size", "instance"]
346 selected_fields = opts.output.split(",")
348 op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
349 output = SubmitOpCode(op)
351 if not opts.no_headers:
352 headers = {"node": "Node", "phys": "PhysDev",
353 "vg": "VG", "name": "Name",
354 "size": "Size", "instance": "Instance"}
358 unitfields = ["size"]
362 data = GenerateTable(separator=opts.separator, headers=headers,
363 fields=selected_fields, unitfields=unitfields,
364 numfields=numfields, data=output, units=opts.units)
372 def SetNodeParams(opts, args):
375 @param opts: the command line options selected by the user
377 @param args: should contain only one element, the node name
379 @return: the desired exit code
382 if opts.master_candidate is None and opts.offline is None:
383 ToStderr("Please give at least one of the parameters.")
386 if opts.master_candidate is not None:
387 candidate = opts.master_candidate == 'yes'
390 if opts.offline is not None:
391 offline = opts.offline == 'yes'
394 op = opcodes.OpSetNodeParams(node_name=args[0],
395 master_candidate=candidate,
399 # even if here we process the result, we allow submit only
400 result = SubmitOrSend(op, opts)
403 ToStdout("Modified node %s", args[0])
404 for param, data in result:
405 ToStdout(" - %-5s -> %s", param, data)
410 'add': (AddNode, ARGS_ONE,
412 make_option("-s", "--secondary-ip", dest="secondary_ip",
413 help="Specify the secondary ip for the node",
414 metavar="ADDRESS", default=None),
415 make_option("--readd", dest="readd",
416 default=False, action="store_true",
417 help="Readd old node after replacing it"),
418 make_option("--no-ssh-key-check", dest="ssh_key_check",
419 default=True, action="store_false",
420 help="Disable SSH key fingerprint checking"),
422 "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
423 "Add a node to the cluster"),
424 'evacuate': (EvacuateNode, ARGS_FIXED(2),
425 [DEBUG_OPT, FORCE_OPT],
427 "Relocate the secondary instances from the first node"
428 " to the second one (only for instances with drbd disk template"
430 'failover': (FailoverNode, ARGS_ONE,
431 [DEBUG_OPT, FORCE_OPT,
432 make_option("--ignore-consistency", dest="ignore_consistency",
433 action="store_true", default=False,
434 help="Ignore the consistency of the disks on"
438 "Stops the primary instances on a node and start them on their"
439 " secondary node (only for instances with drbd disk template)"),
440 'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
441 "[<node_name>...]", "Show information about the node(s)"),
442 'list': (ListNodes, ARGS_NONE,
443 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
445 "", "Lists the nodes in the cluster. The available fields"
446 " are (see the man page for details): %s"
447 " The default field list is (in order): %s." %
448 (", ".join(_LIST_HEADERS), ", ".join(_LIST_DEF_FIELDS))),
449 'modify': (SetNodeParams, ARGS_ONE,
450 [DEBUG_OPT, FORCE_OPT,
452 make_option("-C", "--master-candidate", dest="master_candidate",
453 choices=('yes', 'no'), default=None,
454 help="Set the master_candidate flag on the node"),
455 make_option("-O", "--offline", dest="offline",
456 choices=('yes', 'no'), default=None,
457 help="Set the offline flag on the node"),
459 "<instance>", "Alters the parameters of an instance"),
460 'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
461 "<node_name>", "Removes a node from the cluster"),
462 'volumes': (ListVolumes, ARGS_ANY,
463 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
464 "[<node_name>...]", "List logical volumes on node(s)"),
465 'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
466 "<node_name>", "List the tags of the given node"),
467 'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
468 "<node_name> tag...", "Add tags to the given node"),
469 'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
470 "<node_name> tag...", "Remove tags from the given node"),
474 if __name__ == '__main__':
475 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))