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
57 dns_data = utils.HostInfo(args[0])
62 output = cl.QueryNodes(names=[node], fields=['name'])
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 # read the cluster name from the master
71 output = cl.QueryConfigValues(['cluster_name'])
72 cluster_name = output[0]
74 ToStderr("-- WARNING -- \n"
75 "Performing this operation is going to replace the ssh daemon"
77 "on the target machine (%s) with the ones of the"
79 "and grant full intra-cluster ssh root access to/from it\n", node)
81 bootstrap.SetupNodeDaemon(cluster_name, node, opts.ssh_key_check)
83 op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
88 def ListNodes(opts, args):
89 """List nodes and their properties.
91 @param opts: the command line options selected by the user
93 @param args: should be an empty list
95 @return: the desired exit code
98 if opts.output is None:
99 selected_fields = _LIST_DEF_FIELDS
100 elif opts.output.startswith("+"):
101 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
103 selected_fields = opts.output.split(",")
105 output = GetClient().QueryNodes([], selected_fields)
107 if not opts.no_headers:
109 "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
110 "pinst_list": "PriInstances", "sinst_list": "SecInstances",
111 "pip": "PrimaryIP", "sip": "SecondaryIP",
112 "dtotal": "DTotal", "dfree": "DFree",
113 "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
117 "serial_no": "SerialNo",
118 "master_candidate": "MasterC",
119 "master": "IsMaster",
124 unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
126 numfields = ["dtotal", "dfree",
127 "mtotal", "mnode", "mfree",
128 "pinst_cnt", "sinst_cnt",
129 "ctotal", "serial_no"]
131 list_type_fields = ("pinst_list", "sinst_list", "tags")
132 # change raw values to nicer strings
134 for idx, field in enumerate(selected_fields):
136 if field in list_type_fields:
138 elif field in ('master', 'master_candidate'):
147 data = GenerateTable(separator=opts.separator, headers=headers,
148 fields=selected_fields, unitfields=unitfields,
149 numfields=numfields, data=output, units=opts.units)
156 def EvacuateNode(opts, args):
157 """Relocate all secondary instance from a node.
159 @param opts: the command line options selected by the user
161 @param args: should be an empty list
163 @return: the desired exit code
167 selected_fields = ["name", "sinst_list"]
168 src_node, dst_node = args
170 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
171 result = SubmitOpCode(op)
172 src_node, sinst = result[0]
173 op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
174 result = SubmitOpCode(op)
175 dst_node = result[0][0]
177 if src_node == dst_node:
178 raise errors.OpPrereqError("Evacuate node needs different source and"
179 " target nodes (node %s given twice)" %
183 ToStderr("No secondary instances on node %s, exiting.", src_node)
184 return constants.EXIT_SUCCESS
186 sinst = utils.NiceSort(sinst)
188 retcode = constants.EXIT_SUCCESS
190 if not force and not AskUser("Relocate instance(s) %s from node\n"
191 " %s to node\n %s?" %
192 (",".join("'%s'" % name for name in sinst),
193 src_node, dst_node)):
194 return constants.EXIT_CONFIRMATION
196 good_cnt = bad_cnt = 0
198 op = opcodes.OpReplaceDisks(instance_name=iname,
199 remote_node=dst_node,
200 mode=constants.REPLACE_DISK_ALL,
201 disks=["sda", "sdb"])
203 ToStdout("Replacing disks for instance %s", iname)
205 ToStdout("Instance %s has been relocated", iname)
207 except errors.GenericError, err:
208 nret, msg = FormatError(err)
210 ToStderr("Error replacing disks for instance %s: %s", iname, msg)
213 if retcode == constants.EXIT_SUCCESS:
214 ToStdout("All %d instance(s) relocated successfully.", good_cnt)
216 ToStdout("There were errors during the relocation:\n"
217 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
221 def FailoverNode(opts, args):
222 """Failover all primary instance on a node.
224 @param opts: the command line options selected by the user
226 @param args: should be an empty list
228 @return: the desired exit code
232 selected_fields = ["name", "pinst_list"]
234 op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
235 result = SubmitOpCode(op)
236 node, pinst = result[0]
239 ToStderr("No primary instances on node %s, exiting.", node)
242 pinst = utils.NiceSort(pinst)
246 if not force and not AskUser("Fail over instance(s) %s?" %
247 (",".join("'%s'" % name for name in pinst))):
250 good_cnt = bad_cnt = 0
252 op = opcodes.OpFailoverInstance(instance_name=iname,
253 ignore_consistency=opts.ignore_consistency)
255 ToStdout("Failing over instance %s", iname)
257 ToStdout("Instance %s has been failed over", iname)
259 except errors.GenericError, err:
260 nret, msg = FormatError(err)
262 ToStderr("Error failing over instance %s: %s", iname, msg)
266 ToStdout("All %d instance(s) failed over successfully.", good_cnt)
268 ToStdout("There were errors during the failover:\n"
269 "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
273 def ShowNodeConfig(opts, args):
274 """Show node information.
276 @param opts: the command line options selected by the user
278 @param args: should either be an empty list, in which case
279 we show information about all nodes, or should contain
280 a list of nodes to be queried for information
282 @return: the desired exit code
285 op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
286 "pinst_list", "sinst_list"],
288 result = SubmitOpCode(op)
290 for name, primary_ip, secondary_ip, pinst, sinst in result:
291 ToStdout("Node name: %s", name)
292 ToStdout(" primary ip: %s", primary_ip)
293 ToStdout(" secondary ip: %s", secondary_ip)
295 ToStdout(" primary for instances:")
297 ToStdout(" - %s", iname)
299 ToStdout(" primary for no instances")
301 ToStdout(" secondary for instances:")
303 ToStdout(" - %s", iname)
305 ToStdout(" secondary for no instances")
310 def RemoveNode(opts, args):
311 """Remove a node from the cluster.
313 @param opts: the command line options selected by the user
315 @param args: should contain only one element, the name of
316 the node to be removed
318 @return: the desired exit code
321 op = opcodes.OpRemoveNode(node_name=args[0])
326 def ListVolumes(opts, args):
327 """List logical volumes on node(s).
329 @param opts: the command line options selected by the user
331 @param args: should either be an empty list, in which case
332 we list data for all nodes, or contain a list of nodes
333 to display data only for those
335 @return: the desired exit code
338 if opts.output is None:
339 selected_fields = ["node", "phys", "vg",
340 "name", "size", "instance"]
342 selected_fields = opts.output.split(",")
344 op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
345 output = SubmitOpCode(op)
347 if not opts.no_headers:
348 headers = {"node": "Node", "phys": "PhysDev",
349 "vg": "VG", "name": "Name",
350 "size": "Size", "instance": "Instance"}
354 unitfields = ["size"]
358 data = GenerateTable(separator=opts.separator, headers=headers,
359 fields=selected_fields, unitfields=unitfields,
360 numfields=numfields, data=output, units=opts.units)
369 'add': (AddNode, ARGS_ONE,
371 make_option("-s", "--secondary-ip", dest="secondary_ip",
372 help="Specify the secondary ip for the node",
373 metavar="ADDRESS", default=None),
374 make_option("--readd", dest="readd",
375 default=False, action="store_true",
376 help="Readd old node after replacing it"),
377 make_option("--no-ssh-key-check", dest="ssh_key_check",
378 default=True, action="store_false",
379 help="Disable SSH key fingerprint checking"),
381 "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
382 "Add a node to the cluster"),
383 'evacuate': (EvacuateNode, ARGS_FIXED(2),
384 [DEBUG_OPT, FORCE_OPT],
386 "Relocate the secondary instances from the first node"
387 " to the second one (only for instances with drbd disk template"
389 'failover': (FailoverNode, ARGS_ONE,
390 [DEBUG_OPT, FORCE_OPT,
391 make_option("--ignore-consistency", dest="ignore_consistency",
392 action="store_true", default=False,
393 help="Ignore the consistency of the disks on"
397 "Stops the primary instances on a node and start them on their"
398 " secondary node (only for instances with drbd disk template)"),
399 'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
400 "[<node_name>...]", "Show information about the node(s)"),
401 'list': (ListNodes, ARGS_NONE,
402 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
404 "", "Lists the nodes in the cluster. The available fields"
405 " are (see the man page for details): name, pinst_cnt, pinst_list,"
406 " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
407 " mfree, bootid, cpu_count, serial_no."
408 " The default field list is"
409 " (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
411 'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
412 "<node_name>", "Removes a node from the cluster"),
413 'volumes': (ListVolumes, ARGS_ANY,
414 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
415 "[<node_name>...]", "List logical volumes on node(s)"),
416 'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
417 "<node_name>", "List the tags of the given node"),
418 'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
419 "<node_name> tag...", "Add tags to the given node"),
420 'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
421 "<node_name> tag...", "Remove tags from the given node"),
425 if __name__ == '__main__':
426 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))