Add very basic online help to devel/upload
[ganeti-local] / scripts / gnt-node
1 #!/usr/bin/python
2 #
3
4 # Copyright (C) 2006, 2007, 2008 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
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
35
36
37 #: default list of field for L{ListNodes}
38 _LIST_DEF_FIELDS = [
39   "name", "dtotal", "dfree",
40   "mtotal", "mnode", "mfree",
41   "pinst_cnt", "sinst_cnt",
42   ]
43
44
45 @UsesRPC
46 def AddNode(opts, args):
47   """Add a node to the cluster.
48
49   @param opts: the command line options selected by the user
50   @type args: list
51   @param args: should contain only one element, the new node name
52   @rtype: int
53   @return: the desired exit code
54
55   """
56   dns_data = utils.HostInfo(args[0])
57   node = dns_data.name
58
59   if not opts.readd:
60     op = opcodes.OpQueryNodes(output_fields=['name'], names=[node])
61     try:
62       output = SubmitOpCode(op)
63     except (errors.OpPrereqError, errors.OpExecError):
64       pass
65     else:
66       ToStderr("Node %s already in the cluster (as %s)"
67                " - please use --readd", args[0], output[0][0])
68       return 1
69
70   ToStderr("-- WARNING -- \n"
71            "Performing this operation is going to replace the ssh daemon"
72            " keypair\n"
73            "on the target machine (%s) with the ones of the"
74            " current one\n"
75            "and grant full intra-cluster ssh root access to/from it\n", node)
76
77   bootstrap.SetupNodeDaemon(node, opts.ssh_key_check)
78
79   op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
80                          readd=opts.readd)
81   SubmitOpCode(op)
82
83
84 def ListNodes(opts, args):
85   """List nodes and their properties.
86
87   @param opts: the command line options selected by the user
88   @type args: list
89   @param args: should be an empty list
90   @rtype: int
91   @return: the desired exit code
92
93   """
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(",")
98   else:
99     selected_fields = opts.output.split(",")
100
101   output = GetClient().QueryNodes([], selected_fields)
102
103   if not opts.no_headers:
104     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",
110       "bootid": "BootID",
111       "ctotal": "CTotal",
112       "tags": "Tags",
113       "serial_no": "SerialNo",
114       }
115   else:
116     headers = None
117
118   unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
119
120   numfields = ["dtotal", "dfree",
121                "mtotal", "mnode", "mfree",
122                "pinst_cnt", "sinst_cnt",
123                "ctotal", "serial_no"]
124
125   list_type_fields = ("pinst_list", "sinst_list", "tags")
126   # change raw values to nicer strings
127   for row in output:
128     for idx, field in enumerate(selected_fields):
129       val = row[idx]
130       if field in list_type_fields:
131         val = ",".join(val)
132       elif val is None:
133         val = "?"
134       row[idx] = str(val)
135
136   data = GenerateTable(separator=opts.separator, headers=headers,
137                        fields=selected_fields, unitfields=unitfields,
138                        numfields=numfields, data=output, units=opts.units)
139   for line in data:
140     ToStdout(line)
141
142   return 0
143
144
145 def EvacuateNode(opts, args):
146   """Relocate all secondary instance from a node.
147
148   @param opts: the command line options selected by the user
149   @type args: list
150   @param args: should be an empty list
151   @rtype: int
152   @return: the desired exit code
153
154   """
155   force = opts.force
156   selected_fields = ["name", "sinst_list"]
157   src_node, dst_node = args
158
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]
165
166   if src_node == dst_node:
167     raise errors.OpPrereqError("Evacuate node needs different source and"
168                                " target nodes (node %s given twice)" %
169                                src_node)
170
171   if not sinst:
172     ToStderr("No secondary instances on node %s, exiting.", src_node)
173     return constants.EXIT_SUCCESS
174
175   sinst = utils.NiceSort(sinst)
176
177   retcode = constants.EXIT_SUCCESS
178
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
184
185   good_cnt = bad_cnt = 0
186   for iname in sinst:
187     op = opcodes.OpReplaceDisks(instance_name=iname,
188                                 remote_node=dst_node,
189                                 mode=constants.REPLACE_DISK_ALL,
190                                 disks=["sda", "sdb"])
191     try:
192       ToStdout("Replacing disks for instance %s", iname)
193       SubmitOpCode(op)
194       ToStdout("Instance %s has been relocated", iname)
195       good_cnt += 1
196     except errors.GenericError, err:
197       nret, msg = FormatError(err)
198       retcode |= nret
199       ToStderr("Error replacing disks for instance %s: %s", iname, msg)
200       bad_cnt += 1
201
202   if retcode == constants.EXIT_SUCCESS:
203     ToStdout("All %d instance(s) relocated successfully.", good_cnt)
204   else:
205     ToStdout("There were errors during the relocation:\n"
206              "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
207   return retcode
208
209
210 def FailoverNode(opts, args):
211   """Failover all primary instance on a node.
212
213   @param opts: the command line options selected by the user
214   @type args: list
215   @param args: should be an empty list
216   @rtype: int
217   @return: the desired exit code
218
219   """
220   force = opts.force
221   selected_fields = ["name", "pinst_list"]
222
223   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
224   result = SubmitOpCode(op)
225   node, pinst = result[0]
226
227   if not pinst:
228     ToStderr("No primary instances on node %s, exiting.", node)
229     return 0
230
231   pinst = utils.NiceSort(pinst)
232
233   retcode = 0
234
235   if not force and not AskUser("Fail over instance(s) %s?" %
236                                (",".join("'%s'" % name for name in pinst))):
237     return 2
238
239   good_cnt = bad_cnt = 0
240   for iname in pinst:
241     op = opcodes.OpFailoverInstance(instance_name=iname,
242                                     ignore_consistency=opts.ignore_consistency)
243     try:
244       ToStdout("Failing over instance %s", iname)
245       SubmitOpCode(op)
246       ToStdout("Instance %s has been failed over", iname)
247       good_cnt += 1
248     except errors.GenericError, err:
249       nret, msg = FormatError(err)
250       retcode |= nret
251       ToStderr("Error failing over instance %s: %s", iname, msg)
252       bad_cnt += 1
253
254   if retcode == 0:
255     ToStdout("All %d instance(s) failed over successfully.", good_cnt)
256   else:
257     ToStdout("There were errors during the failover:\n"
258              "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
259   return retcode
260
261
262 def ShowNodeConfig(opts, args):
263   """Show node information.
264
265   @param opts: the command line options selected by the user
266   @type args: list
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
270   @rtype: int
271   @return: the desired exit code
272
273   """
274   op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
275                                            "pinst_list", "sinst_list"],
276                             names=args)
277   result = SubmitOpCode(op)
278
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)
283     if pinst:
284       ToStdout("  primary for instances:")
285       for iname in pinst:
286         ToStdout("    - %s", iname)
287     else:
288       ToStdout("  primary for no instances")
289     if sinst:
290       ToStdout("  secondary for instances:")
291       for iname in sinst:
292         ToStdout("    - %s", iname)
293     else:
294       ToStdout("  secondary for no instances")
295
296   return 0
297
298
299 def RemoveNode(opts, args):
300   """Remove a node from the cluster.
301
302   @param opts: the command line options selected by the user
303   @type args: list
304   @param args: should contain only one element, the name of
305       the node to be removed
306   @rtype: int
307   @return: the desired exit code
308
309   """
310   op = opcodes.OpRemoveNode(node_name=args[0])
311   SubmitOpCode(op)
312   return 0
313
314
315 def ListVolumes(opts, args):
316   """List logical volumes on node(s).
317
318   @param opts: the command line options selected by the user
319   @type args: list
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
323   @rtype: int
324   @return: the desired exit code
325
326   """
327   if opts.output is None:
328     selected_fields = ["node", "phys", "vg",
329                        "name", "size", "instance"]
330   else:
331     selected_fields = opts.output.split(",")
332
333   op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
334   output = SubmitOpCode(op)
335
336   if not opts.no_headers:
337     headers = {"node": "Node", "phys": "PhysDev",
338                "vg": "VG", "name": "Name",
339                "size": "Size", "instance": "Instance"}
340   else:
341     headers = None
342
343   unitfields = ["size"]
344
345   numfields = ["size"]
346
347   data = GenerateTable(separator=opts.separator, headers=headers,
348                        fields=selected_fields, unitfields=unitfields,
349                        numfields=numfields, data=output, units=opts.units)
350
351   for line in data:
352     ToStdout(line)
353
354   return 0
355
356
357 commands = {
358   'add': (AddNode, ARGS_ONE,
359           [DEBUG_OPT,
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"),
369            ],
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],
374                "[-f] <src> <dst>",
375                "Relocate the secondary instances from the first node"
376                " to the second one (only for instances with drbd disk template"
377                ),
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"
383                             " the secondary"),
384                 ],
385                "[-f] <node>",
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,
392             SUBMIT_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),
399            ),
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"),
411   }
412
413
414 if __name__ == '__main__':
415   sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))