Update online help and manpage to include drbd disk type.
[ganeti-local] / scripts / gnt-node
1 #!/usr/bin/python
2 #
3
4 # Copyright (C) 2006, 2007 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 import sys
23 from optparse import make_option
24
25 from ganeti.cli import *
26 from ganeti import opcodes
27 from ganeti import logger
28 from ganeti import utils
29 from ganeti import constants
30 from ganeti import errors
31
32
33 def AddNode(opts, args):
34   """Add node cli-to-processor bridge."""
35   logger.ToStderr("-- WARNING -- \n"
36     "Performing this operation is going to replace the ssh daemon keypair\n"
37     "on the target machine (%s) with the ones of the current one\n"
38     "and grant full intra-cluster ssh root access to/from it\n" % args[0])
39   op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip)
40   SubmitOpCode(op)
41
42
43 def ListNodes(opts, args):
44   """List nodes and their properties.
45
46   """
47   if opts.output is None:
48     selected_fields = ["name", "dtotal", "dfree",
49                        "mtotal", "mnode", "mfree",
50                        "pinst_cnt", "sinst_cnt"]
51   else:
52     selected_fields = opts.output.split(",")
53
54   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[])
55   output = SubmitOpCode(op)
56
57   if not opts.no_headers:
58     headers = {"name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
59                "pinst_list": "PriInstances", "sinst_list": "SecInstances",
60                "pip": "PrimaryIP", "sip": "SecondaryIP",
61                "dtotal": "DTotal", "dfree": "DFree",
62                "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
63                "bootid": "BootID"}
64   else:
65     headers = None
66
67   if opts.human_readable:
68     unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
69   else:
70     unitfields = None
71
72   numfields = ["dtotal", "dfree",
73                "mtotal", "mnode", "mfree",
74                "pinst_cnt", "sinst_cnt"]
75
76   # change raw values to nicer strings
77   for row in output:
78     for idx, field in enumerate(selected_fields):
79       val = row[idx]
80       if field == "pinst_list":
81         val = ",".join(val)
82       elif field == "sinst_list":
83         val = ",".join(val)
84       elif val is None:
85         val = "?"
86       row[idx] = str(val)
87
88   data = GenerateTable(separator=opts.separator, headers=headers,
89                        fields=selected_fields, unitfields=unitfields,
90                        numfields=numfields, data=output)
91   for line in data:
92     logger.ToStdout(line)
93
94   return 0
95
96
97 def EvacuateNode(opts, args):
98   """Relocate all secondary instance from a node.
99
100   """
101   force = opts.force
102   selected_fields = ["name", "sinst_list"]
103   src_node, dst_node = args
104
105   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
106   result = SubmitOpCode(op)
107   src_node, sinst = result[0]
108   op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
109   result = SubmitOpCode(op)
110   dst_node = result[0][0]
111
112   if src_node == dst_node:
113     raise errors.OpPrereqError("Evacuate node needs different source and"
114                                " target nodes (node %s given twice)" %
115                                src_node)
116
117   if not sinst:
118     logger.ToStderr("No secondary instances on node %s, exiting." % src_node)
119     return constants.EXIT_SUCCESS
120
121   sinst = utils.NiceSort(sinst)
122
123   retcode = constants.EXIT_SUCCESS
124
125   if not force and not AskUser("Relocate instance(s) %s from node\n"
126                                " %s to node\n %s?" %
127                                (",".join("'%s'" % name for name in sinst),
128                                src_node, dst_node)):
129     return constants.EXIT_CONFIRMATION
130
131   good_cnt = bad_cnt = 0
132   for iname in sinst:
133     op = opcodes.OpReplaceDisks(instance_name=iname,
134                                 remote_node=dst_node,
135                                 mode=constants.REPLACE_DISK_ALL,
136                                 disks=["sda", "sdb"])
137     try:
138       logger.ToStdout("Replacing disks for instance %s" % iname)
139       SubmitOpCode(op)
140       logger.ToStdout("Instance %s has been relocated" % iname)
141       good_cnt += 1
142     except errors.GenericError, err:
143       nret, msg = FormatError(err)
144       retcode |= nret
145       logger.ToStderr("Error replacing disks for instance %s: %s" %
146                       (iname, msg))
147       bad_cnt += 1
148
149   if retcode == constants.EXIT_SUCCESS:
150     logger.ToStdout("All %d instance(s) relocated successfully." % good_cnt)
151   else:
152     logger.ToStdout("There were errors during the relocation:\n"
153                     "%d error(s) out of %d instance(s)." %
154                     (bad_cnt, good_cnt + bad_cnt))
155   return retcode
156
157
158 def FailoverNode(opts, args):
159   """Failover all primary instance on a node.
160
161   """
162   force = opts.force
163   selected_fields = ["name", "pinst_list"]
164
165   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
166   result = SubmitOpCode(op)
167   node, pinst = result[0]
168
169   if not pinst:
170     logger.ToStderr("No primary instances on node %s, exiting." % node)
171     return 0
172
173   pinst = utils.NiceSort(pinst)
174
175   retcode = 0
176
177   if not force and not AskUser("Fail over instance(s) %s?" %
178                                (",".join("'%s'" % name for name in pinst))):
179     return 2
180
181   good_cnt = bad_cnt = 0
182   for iname in pinst:
183     op = opcodes.OpFailoverInstance(instance_name=iname,
184                                     ignore_consistency=opts.ignore_consistency)
185     try:
186       logger.ToStdout("Failing over instance %s" % iname)
187       SubmitOpCode(op)
188       logger.ToStdout("Instance %s has been failed over" % iname)
189       good_cnt += 1
190     except errors.GenericError, err:
191       nret, msg = FormatError(err)
192       retcode |= nret
193       logger.ToStderr("Error failing over instance %s: %s" % (iname, msg))
194       bad_cnt += 1
195
196   if retcode == 0:
197     logger.ToStdout("All %d instance(s) failed over successfully." % good_cnt)
198   else:
199     logger.ToStdout("There were errors during the failover:\n"
200                     "%d error(s) out of %d instance(s)." %
201                     (bad_cnt, good_cnt + bad_cnt))
202   return retcode
203
204
205 def ShowNodeConfig(opts, args):
206   """Show node information.
207
208   """
209   op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
210                                            "pinst_list", "sinst_list"],
211                             names=args)
212   result = SubmitOpCode(op)
213
214   for name, primary_ip, secondary_ip, pinst, sinst in result:
215     logger.ToStdout("Node name: %s" % name)
216     logger.ToStdout("  primary ip: %s" % primary_ip)
217     logger.ToStdout("  secondary ip: %s" % secondary_ip)
218     if pinst:
219       logger.ToStdout("  primary for instances:")
220       for iname in pinst:
221         logger.ToStdout("    - %s" % iname)
222     else:
223       logger.ToStdout("  primary for no instances")
224     if sinst:
225       logger.ToStdout("  secondary for instances:")
226       for iname in sinst:
227         logger.ToStdout("    - %s" % iname)
228     else:
229       logger.ToStdout("  secondary for no instances")
230
231   return 0
232
233
234 def RemoveNode(opts, args):
235   """Remove node cli-to-processor bridge."""
236   op = opcodes.OpRemoveNode(node_name=args[0])
237   SubmitOpCode(op)
238
239
240 def ListVolumes(opts, args):
241   """List logical volumes on node(s).
242
243   """
244   if opts.output is None:
245     selected_fields = ["node", "phys", "vg",
246                        "name", "size", "instance"]
247   else:
248     selected_fields = opts.output.split(",")
249
250   op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
251   output = SubmitOpCode(op)
252
253   if not opts.no_headers:
254     headers = {"node": "Node", "phys": "PhysDev",
255                "vg": "VG", "name": "Name",
256                "size": "Size", "instance": "Instance"}
257   else:
258     headers = None
259
260   if opts.human_readable:
261     unitfields = ["size"]
262   else:
263     unitfields = None
264
265   numfields = ["size"]
266
267   data = GenerateTable(separator=opts.separator, headers=headers,
268                        fields=selected_fields, unitfields=unitfields,
269                        numfields=numfields, data=output)
270
271   for line in data:
272     logger.ToStdout(line)
273
274   return 0
275
276
277 commands = {
278   'add': (AddNode, ARGS_ONE,
279           [DEBUG_OPT,
280            make_option("-s", "--secondary-ip", dest="secondary_ip",
281                        help="Specify the secondary ip for the node",
282                        metavar="ADDRESS", default=None),],
283           "[-s ip] <node_name>", "Add a node to the cluster"),
284   'evacuate': (EvacuateNode, ARGS_FIXED(2),
285                [DEBUG_OPT, FORCE_OPT],
286                "[-f] <src_node> <dst_node>",
287                "Relocate the secondary instances from the first node"
288                " to the second one (only for instances of type remote_raid1"
289                " drbd)"),
290   'failover': (FailoverNode, ARGS_ONE,
291                [DEBUG_OPT, FORCE_OPT,
292                 make_option("--ignore-consistency", dest="ignore_consistency",
293                             action="store_true", default=False,
294                             help="Ignore the consistency of the disks on"
295                             " the secondary"),
296                 ],
297                "[-f] <node>",
298                "Stops the primary instances on a node and start them on their"
299                " secondary node (only for instances of type remote_raid1)"),
300   'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
301            "[<node_name>...]", "Show information about the node(s)"),
302   'list': (ListNodes, ARGS_NONE,
303            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
304            "", "Lists the nodes in the cluster. The available fields"
305            " are (see the man page for details): name, pinst_cnt, pinst_list,"
306            " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
307            " mfree, bootid. The default field list is (in order): name,"
308            " dtotal, dfree, mtotal, mnode, mfree, pinst_cnt, sinst_cnt."),
309   'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
310              "<node_name>", "Removes a node from the cluster"),
311   'volumes': (ListVolumes, ARGS_ANY,
312               [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
313               "[<node_name>...]", "List logical volumes on node(s)"),
314   'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
315                 "<node_name>", "List the tags of the given node"),
316   'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
317                "<node_name> tag...", "Add tags to the given node"),
318   'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
319                   "<node_name> tag...", "Remove tags from the given node"),
320   }
321
322
323 if __name__ == '__main__':
324   sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))