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 cli
31 from ganeti import opcodes
32 from ganeti import utils
33 from ganeti import constants
34 from ganeti import errors
35 from ganeti import bootstrap
38 #: default list of field for L{ListNodes}
40 "name", "dtotal", "dfree",
41 "mtotal", "mnode", "mfree",
42 "pinst_cnt", "sinst_cnt",
45 #: headers (and full field list for L{ListNodes}
47 "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
48 "pinst_list": "PriInstances", "sinst_list": "SecInstances",
49 "pip": "PrimaryIP", "sip": "SecondaryIP",
50 "dtotal": "DTotal", "dfree": "DFree",
51 "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
53 "ctotal": "CTotal", "cnodes": "CNodes", "csockets": "CSockets",
55 "serial_no": "SerialNo",
56 "master_candidate": "MasterC",
58 "offline": "Offline", "drained": "Drained",
63 def AddNode(opts, args):
64 """Add a node to the cluster.
66 @param opts: the command line options selected by the user
68 @param args: should contain only one element, the new node name
70 @return: the desired exit code
74 dns_data = utils.HostInfo(args[0])
79 output = cl.QueryNodes(names=[node], fields=['name', 'sip'],
81 node_exists, sip = output[0]
82 except (errors.OpPrereqError, errors.OpExecError):
88 ToStderr("Node %s not in the cluster"
89 " - please retry without '--readd'", node)
93 ToStderr("Node %s already in the cluster (as %s)"
94 " - please retry with '--readd'", node, node_exists)
96 sip = opts.secondary_ip
98 # read the cluster name from the master
99 output = cl.QueryConfigValues(['cluster_name'])
100 cluster_name = output[0]
103 # clear the offline and drain flags on the node
104 ToStdout("Resetting the 'offline' and 'drained' flags due to re-add")
105 op = opcodes.OpSetNodeParams(node_name=node, force=True,
106 offline=False, drained=False)
108 result = SubmitOpCode(op, cl=cl)
110 ToStdout("Modified:")
111 for param, data in result:
112 ToStdout(" - %-5s -> %s", param, data)
114 ToStderr("-- WARNING -- \n"
115 "Performing this operation is going to replace the ssh daemon"
117 "on the target machine (%s) with the ones of the"
119 "and grant full intra-cluster ssh root access to/from it\n", node)
121 bootstrap.SetupNodeDaemon(cluster_name, node, opts.ssh_key_check)
123 op = opcodes.OpAddNode(node_name=args[0], secondary_ip=sip,
128 def ListNodes(opts, args):
129 """List nodes and their properties.
131 @param opts: the command line options selected by the user
133 @param args: should be an empty list
135 @return: the desired exit code
138 if opts.output is None:
139 selected_fields = _LIST_DEF_FIELDS
140 elif opts.output.startswith("+"):
141 selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
143 selected_fields = opts.output.split(",")
145 output = GetClient().QueryNodes(args, selected_fields, opts.do_locking)
147 if not opts.no_headers:
148 headers = _LIST_HEADERS
152 unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
154 numfields = ["dtotal", "dfree",
155 "mtotal", "mnode", "mfree",
156 "pinst_cnt", "sinst_cnt",
157 "ctotal", "serial_no"]
159 list_type_fields = ("pinst_list", "sinst_list", "tags")
160 # change raw values to nicer strings
162 for idx, field in enumerate(selected_fields):
164 if field in list_type_fields:
166 elif field in ('master', 'master_candidate', 'offline', 'drained'):
175 data = GenerateTable(separator=opts.separator, headers=headers,
176 fields=selected_fields, unitfields=unitfields,
177 numfields=numfields, data=output, units=opts.units)
184 def EvacuateNode(opts, args):
185 """Relocate all secondary instance from a node.
187 @param opts: the command line options selected by the user
189 @param args: should be an empty list
191 @return: the desired exit code
197 dst_node = opts.dst_node
198 iallocator = opts.iallocator
200 cnt = [dst_node, iallocator].count(None)
202 raise errors.OpPrereqError("One and only one of the -n and -i"
203 " options must be passed")
205 selected_fields = ["name", "sinst_list"]
208 result = cl.QueryNodes(names=[src_node], fields=selected_fields,
210 src_node, sinst = result[0]
213 ToStderr("No secondary instances on node %s, exiting.", src_node)
214 return constants.EXIT_SUCCESS
216 if dst_node is not None:
217 result = cl.QueryNodes(names=[dst_node], fields=["name"],
219 dst_node = result[0][0]
221 if src_node == dst_node:
222 raise errors.OpPrereqError("Evacuate node needs different source and"
223 " target nodes (node %s given twice)" %
225 txt_msg = "to node %s" % dst_node
227 txt_msg = "using iallocator %s" % iallocator
229 sinst = utils.NiceSort(sinst)
231 if not force and not AskUser("Relocate instance(s) %s from node\n"
233 (",".join("'%s'" % name for name in sinst),
235 return constants.EXIT_CONFIRMATION
239 op = opcodes.OpReplaceDisks(instance_name=iname,
240 remote_node=dst_node,
241 mode=constants.REPLACE_DISK_CHG,
242 iallocator=iallocator,
246 job_id = cli.SendJob(ops, cl=cl)
247 cli.PollJob(job_id, cl=cl)
250 def FailoverNode(opts, args):
251 """Failover all primary instance on a node.
253 @param opts: the command line options selected by the user
255 @param args: should be an empty list
257 @return: the desired exit code
262 selected_fields = ["name", "pinst_list"]
264 # these fields are static data anyway, so it doesn't matter, but
265 # locking=True should be safer
266 result = cl.QueryNodes(names=args, fields=selected_fields,
268 node, pinst = result[0]
271 ToStderr("No primary instances on node %s, exiting.", node)
274 pinst = utils.NiceSort(pinst)
278 if not force and not AskUser("Fail over instance(s) %s?" %
279 (",".join("'%s'" % name for name in pinst))):
282 jex = JobExecutor(cl=cl)
284 op = opcodes.OpFailoverInstance(instance_name=iname,
285 ignore_consistency=opts.ignore_consistency)
286 jex.QueueJob(iname, op)
287 results = jex.GetResults()
288 bad_cnt = len([row for row in results if not row[0]])
290 ToStdout("All %d instance(s) failed over successfully.", len(results))
292 ToStdout("There were errors during the failover:\n"
293 "%d error(s) out of %d instance(s).", bad_cnt, len(results))
297 def MigrateNode(opts, args):
298 """Migrate all primary instance on a node.
303 selected_fields = ["name", "pinst_list"]
305 result = cl.QueryNodes(names=args, fields=selected_fields, use_locking=False)
306 node, pinst = result[0]
309 ToStdout("No primary instances on node %s, exiting." % node)
312 pinst = utils.NiceSort(pinst)
316 if not force and not AskUser("Migrate instance(s) %s?" %
317 (",".join("'%s'" % name for name in pinst))):
320 jex = JobExecutor(cl=cl)
322 op = opcodes.OpMigrateInstance(instance_name=iname, live=opts.live,
324 jex.QueueJob(iname, op)
326 results = jex.GetResults()
327 bad_cnt = len([row for row in results if not row[0]])
329 ToStdout("All %d instance(s) migrated successfully.", len(results))
331 ToStdout("There were errors during the migration:\n"
332 "%d error(s) out of %d instance(s).", bad_cnt, len(results))
336 def ShowNodeConfig(opts, args):
337 """Show node information.
339 @param opts: the command line options selected by the user
341 @param args: should either be an empty list, in which case
342 we show information about all nodes, or should contain
343 a list of nodes to be queried for information
345 @return: the desired exit code
349 result = cl.QueryNodes(fields=["name", "pip", "sip",
350 "pinst_list", "sinst_list",
351 "master_candidate", "drained", "offline"],
352 names=args, use_locking=False)
354 for (name, primary_ip, secondary_ip, pinst, sinst,
355 is_mc, drained, offline) in result:
356 ToStdout("Node name: %s", name)
357 ToStdout(" primary ip: %s", primary_ip)
358 ToStdout(" secondary ip: %s", secondary_ip)
359 ToStdout(" master candidate: %s", is_mc)
360 ToStdout(" drained: %s", drained)
361 ToStdout(" offline: %s", offline)
363 ToStdout(" primary for instances:")
364 for iname in utils.NiceSort(pinst):
365 ToStdout(" - %s", iname)
367 ToStdout(" primary for no instances")
369 ToStdout(" secondary for instances:")
370 for iname in utils.NiceSort(sinst):
371 ToStdout(" - %s", iname)
373 ToStdout(" secondary for no instances")
378 def RemoveNode(opts, args):
379 """Remove a node from the cluster.
381 @param opts: the command line options selected by the user
383 @param args: should contain only one element, the name of
384 the node to be removed
386 @return: the desired exit code
389 op = opcodes.OpRemoveNode(node_name=args[0])
394 def ListVolumes(opts, args):
395 """List logical volumes on node(s).
397 @param opts: the command line options selected by the user
399 @param args: should either be an empty list, in which case
400 we list data for all nodes, or contain a list of nodes
401 to display data only for those
403 @return: the desired exit code
406 if opts.output is None:
407 selected_fields = ["node", "phys", "vg",
408 "name", "size", "instance"]
410 selected_fields = opts.output.split(",")
412 op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
413 output = SubmitOpCode(op)
415 if not opts.no_headers:
416 headers = {"node": "Node", "phys": "PhysDev",
417 "vg": "VG", "name": "Name",
418 "size": "Size", "instance": "Instance"}
422 unitfields = ["size"]
426 data = GenerateTable(separator=opts.separator, headers=headers,
427 fields=selected_fields, unitfields=unitfields,
428 numfields=numfields, data=output, units=opts.units)
436 def SetNodeParams(opts, args):
439 @param opts: the command line options selected by the user
441 @param args: should contain only one element, the node name
443 @return: the desired exit code
446 if [opts.master_candidate, opts.drained, opts.offline].count(None) == 3:
447 ToStderr("Please give at least one of the parameters.")
450 if opts.master_candidate is not None:
451 candidate = opts.master_candidate == 'yes'
454 if opts.offline is not None:
455 offline = opts.offline == 'yes'
459 if opts.drained is not None:
460 drained = opts.drained == 'yes'
463 op = opcodes.OpSetNodeParams(node_name=args[0],
464 master_candidate=candidate,
469 # even if here we process the result, we allow submit only
470 result = SubmitOrSend(op, opts)
473 ToStdout("Modified node %s", args[0])
474 for param, data in result:
475 ToStdout(" - %-5s -> %s", param, data)
480 'add': (AddNode, ARGS_ONE,
482 make_option("-s", "--secondary-ip", dest="secondary_ip",
483 help="Specify the secondary ip for the node",
484 metavar="ADDRESS", default=None),
485 make_option("--readd", dest="readd",
486 default=False, action="store_true",
487 help="Readd old node after replacing it"),
488 make_option("--no-ssh-key-check", dest="ssh_key_check",
489 default=True, action="store_false",
490 help="Disable SSH key fingerprint checking"),
492 "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
493 "Add a node to the cluster"),
494 'evacuate': (EvacuateNode, ARGS_ONE,
495 [DEBUG_OPT, FORCE_OPT,
496 make_option("-n", "--new-secondary", dest="dst_node",
497 help="New secondary node", metavar="NODE",
499 make_option("-I", "--iallocator", metavar="<NAME>",
500 help="Select new secondary for the instance"
501 " automatically using the"
502 " <NAME> iallocator plugin",
503 default=None, type="string"),
505 "[-f] {-I <iallocator> | -n <dst>} <node>",
506 "Relocate the secondary instances from a node"
507 " to other nodes (only for instances with drbd disk template)"),
508 'failover': (FailoverNode, ARGS_ONE,
509 [DEBUG_OPT, FORCE_OPT,
510 make_option("--ignore-consistency", dest="ignore_consistency",
511 action="store_true", default=False,
512 help="Ignore the consistency of the disks on"
516 "Stops the primary instances on a node and start them on their"
517 " secondary node (only for instances with drbd disk template)"),
518 'migrate': (MigrateNode, ARGS_ONE,
519 [DEBUG_OPT, FORCE_OPT,
520 make_option("--non-live", dest="live",
521 default=True, action="store_false",
522 help="Do a non-live migration (this usually means"
523 " freeze the instance, save the state,"
524 " transfer and only then resume running on the"
528 "Migrate all the primary instance on a node away from it"
529 " (only for instances of type drbd)"),
530 'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
531 "[<node_name>...]", "Show information about the node(s)"),
532 'list': (ListNodes, ARGS_ANY,
533 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT, SYNC_OPT],
535 "Lists the nodes in the cluster. The available fields"
536 " are (see the man page for details): %s"
537 " The default field list is (in order): %s." %
538 (", ".join(_LIST_HEADERS), ", ".join(_LIST_DEF_FIELDS))),
539 'modify': (SetNodeParams, ARGS_ONE,
540 [DEBUG_OPT, FORCE_OPT,
542 make_option("-C", "--master-candidate", dest="master_candidate",
543 choices=('yes', 'no'), default=None,
545 help="Set the master_candidate flag on the node"),
547 make_option("-O", "--offline", dest="offline", metavar="yes|no",
548 choices=('yes', 'no'), default=None,
549 help="Set the offline flag on the node"),
550 make_option("-D", "--drained", dest="drained", metavar="yes|no",
551 choices=('yes', 'no'), default=None,
552 help="Set the drained flag on the node"),
554 "<instance>", "Alters the parameters of an instance"),
555 'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
556 "<node_name>", "Removes a node from the cluster"),
557 'volumes': (ListVolumes, ARGS_ANY,
558 [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
559 "[<node_name>...]", "List logical volumes on node(s)"),
560 'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
561 "<node_name>", "List the tags of the given node"),
562 'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
563 "<node_name> tag...", "Add tags to the given node"),
564 'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
565 "<node_name> tag...", "Remove tags from the given node"),
569 if __name__ == '__main__':
570 sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))