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",
46 def AddNode(opts, args):
47 """Add a node to the cluster.
49 @param opts: the command line options selected by the user
51 @param args: should contain only one element, the new node name
53 @return: the desired exit code
56 dns_data = utils.HostInfo(args[0])
60 op = opcodes.OpQueryNodes(output_fields=['name'], names=[node])
62 output = SubmitOpCode(op)
63 except (errors.OpPrereqError, errors.OpExecError):
66 ToStderr("Node %s already in the cluster (as %s)"
67 " - please use --readd", args[0], output[0][0])
70 ToStderr("-- WARNING -- \n"
71 "Performing this operation is going to replace the ssh daemon"
73 "on the target machine (%s) with the ones of the"
75 "and grant full intra-cluster ssh root access to/from it\n", node)
77 bootstrap.SetupNodeDaemon(node, opts.ssh_key_check)
79 op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
84 def ListNodes(opts, args):
85 """List nodes and their properties.
87 @param opts: the command line options selected by the user
89 @param args: should be an empty list
91 @return: the desired exit code
94 if opts.output is None:
95 selected_fields = _LIST_DEF_FIELDS
96 elif opts.output.startswith("+"):
97 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
99 selected_fields = opts.output.split(",")
101 output = GetClient().QueryNodes([], selected_fields)
103 if not opts.no_headers:
105 "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
106 "pinst_list": "PriInstances", "sinst_list": "SecInstances",
107 "pip": "PrimaryIP", "sip": "SecondaryIP",
108 "dtotal": "DTotal", "dfree": "DFree",
109 "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
113 "serial_no": "SerialNo",
118 unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
120 numfields = ["dtotal", "dfree",
121 "mtotal", "mnode", "mfree",
122 "pinst_cnt", "sinst_cnt",
123 "ctotal", "serial_no"]
125 list_type_fields = ("pinst_list", "sinst_list", "tags")
126 # change raw values to nicer strings
128 for idx, field in enumerate(selected_fields):
130 if field in list_type_fields:
136 data = GenerateTable(separator=opts.separator, headers=headers,
137 fields=selected_fields, unitfields=unitfields,
138 numfields=numfields, data=output, units=opts.units)
145 def EvacuateNode(opts, args):
146 """Relocate all secondary instance from a node.
148 @param opts: the command line options selected by the user
150 @param args: should be an empty list
152 @return: the desired exit code
156 selected_fields = ["name", "sinst_list"]
157 src_node, dst_node = args
159 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
160 result = SubmitOpCode(op)
161 src_node, sinst = result[0]
162 op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
163 result = SubmitOpCode(op)
164 dst_node = result[0][0]
166 if src_node == dst_node:
167 raise errors.OpPrereqError("Evacuate node needs different source and"
168 " target nodes (node %s given twice)" %
172 ToStderr("No secondary instances on node %s, exiting.", src_node)
173 return constants.EXIT_SUCCESS
175 sinst = utils.NiceSort(sinst)
177 retcode = constants.EXIT_SUCCESS
179 if not force and not AskUser("Relocate instance(s) %s from node\n"
180 " %s to node\n %s?" %
181 (",".join("'%s'" % name for name in sinst),
182 src_node, dst_node)):
183 return constants.EXIT_CONFIRMATION
185 good_cnt = bad_cnt = 0
187 op = opcodes.OpReplaceDisks(instance_name=iname,
188 remote_node=dst_node,
189 mode=constants.REPLACE_DISK_ALL,
190 disks=["sda", "sdb"])
192 ToStdout("Replacing disks for instance %s", iname)
194 ToStdout("Instance %s has been relocated", iname)
196 except errors.GenericError, err:
197 nret, msg = FormatError(err)
199 ToStderr("Error replacing disks for instance %s: %s", iname, msg)
202 if retcode == constants.EXIT_SUCCESS:
203 ToStdout("All %d instance(s) relocated successfully.", good_cnt)
205 ToStdout("There were errors during the relocation:\n"
206 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
210 def FailoverNode(opts, args):
211 """Failover all primary instance on a node.
213 @param opts: the command line options selected by the user
215 @param args: should be an empty list
217 @return: the desired exit code
221 selected_fields = ["name", "pinst_list"]
223 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
224 result = SubmitOpCode(op)
225 node, pinst = result[0]
228 ToStderr("No primary instances on node %s, exiting.", node)
231 pinst = utils.NiceSort(pinst)
235 if not force and not AskUser("Fail over instance(s) %s?" %
236 (",".join("'%s'" % name for name in pinst))):
239 good_cnt = bad_cnt = 0
241 op = opcodes.OpFailoverInstance(instance_name=iname,
242 ignore_consistency=opts.ignore_consistency)
244 ToStdout("Failing over instance %s", iname)
246 ToStdout("Instance %s has been failed over", iname)
248 except errors.GenericError, err:
249 nret, msg = FormatError(err)
251 ToStderr("Error failing over instance %s: %s", iname, msg)
255 ToStdout("All %d instance(s) failed over successfully.", good_cnt)
257 ToStdout("There were errors during the failover:\n"
258 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
262 def ShowNodeConfig(opts, args):
263 """Show node information.
265 @param opts: the command line options selected by the user
267 @param args: should either be an empty list, in which case
268 we show information about all nodes, or should contain
269 a list of nodes to be queried for information
271 @return: the desired exit code
274 op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
275 "pinst_list", "sinst_list"],
277 result = SubmitOpCode(op)
279 for name, primary_ip, secondary_ip, pinst, sinst in result:
280 ToStdout("Node name: %s", name)
281 ToStdout(" primary ip: %s", primary_ip)
282 ToStdout(" secondary ip: %s", secondary_ip)
284 ToStdout(" primary for instances:")
286 ToStdout(" - %s", iname)
288 ToStdout(" primary for no instances")
290 ToStdout(" secondary for instances:")
292 ToStdout(" - %s", iname)
294 ToStdout(" secondary for no instances")
299 def RemoveNode(opts, args):
300 """Remove a node from the cluster.
302 @param opts: the command line options selected by the user
304 @param args: should contain only one element, the name of
305 the node to be removed
307 @return: the desired exit code
310 op = opcodes.OpRemoveNode(node_name=args[0])
315 def ListVolumes(opts, args):
316 """List logical volumes on node(s).
318 @param opts: the command line options selected by the user
320 @param args: should either be an empty list, in which case
321 we list data for all nodes, or contain a list of nodes
322 to display data only for those
324 @return: the desired exit code
327 if opts.output is None:
328 selected_fields = ["node", "phys", "vg",
329 "name", "size", "instance"]
331 selected_fields = opts.output.split(",")
333 op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
334 output = SubmitOpCode(op)
336 if not opts.no_headers:
337 headers = {"node": "Node", "phys": "PhysDev",
338 "vg": "VG", "name": "Name",
339 "size": "Size", "instance": "Instance"}
343 unitfields = ["size"]
347 data = GenerateTable(separator=opts.separator, headers=headers,
348 fields=selected_fields, unitfields=unitfields,
349 numfields=numfields, data=output, units=opts.units)
358 'add': (AddNode, ARGS_ONE,
360 make_option("-s", "--secondary-ip", dest="secondary_ip",
361 help="Specify the secondary ip for the node",
362 metavar="ADDRESS", default=None),
363 make_option("--readd", dest="readd",
364 default=False, action="store_true",
365 help="Readd old node after replacing it"),
366 make_option("--no-ssh-key-check", dest="ssh_key_check",
367 default=True, action="store_false",
368 help="Disable SSH key fingerprint checking"),
370 "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
371 "Add a node to the cluster"),
372 'evacuate': (EvacuateNode, ARGS_FIXED(2),
373 [DEBUG_OPT, FORCE_OPT],
375 "Relocate the secondary instances from the first node"
376 " to the second one (only for instances with drbd disk template"
378 'failover': (FailoverNode, ARGS_ONE,
379 [DEBUG_OPT, FORCE_OPT,
380 make_option("--ignore-consistency", dest="ignore_consistency",
381 action="store_true", default=False,
382 help="Ignore the consistency of the disks on"
386 "Stops the primary instances on a node and start them on their"
387 " secondary node (only for instances with drbd disk template)"),
388 'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
389 "[<node_name>...]", "Show information about the node(s)"),
390 'list': (ListNodes, ARGS_NONE,
391 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
393 "", "Lists the nodes in the cluster. The available fields"
394 " are (see the man page for details): name, pinst_cnt, pinst_list,"
395 " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
396 " mfree, bootid, cpu_count, serial_no."
397 " The default field list is"
398 " (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
400 'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
401 "<node_name>", "Removes a node from the cluster"),
402 'volumes': (ListVolumes, ARGS_ANY,
403 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
404 "[<node_name>...]", "List logical volumes on node(s)"),
405 'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
406 "<node_name>", "List the tags of the given node"),
407 'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
408 "<node_name> tag...", "Add tags to the given node"),
409 'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
410 "<node_name> tag...", "Remove tags from the given node"),
414 if __name__ == '__main__':
415 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))