Implement gnt-node evacuate
[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     try:
136       logger.ToStdout("Replacing disks for instance %s" % iname)
137       SubmitOpCode(op)
138       logger.ToStdout("Instance %s has been relocated" % iname)
139       good_cnt += 1
140     except errors.GenericError, err:
141       nret, msg = FormatError(err)
142       retcode |= nret
143       logger.ToStderr("Error replacing disks for instance %s: %s" %
144                       (iname, msg))
145       bad_cnt += 1
146
147   if retcode == constants.EXIT_SUCCESS:
148     logger.ToStdout("All %d instance(s) relocated successfully." % good_cnt)
149   else:
150     logger.ToStdout("There were errors during the relocation:\n"
151                     "%d error(s) out of %d instance(s)." %
152                     (bad_cnt, good_cnt + bad_cnt))
153   return retcode
154
155
156 def FailoverNode(opts, args):
157   """Failover all primary instance on a node.
158
159   """
160   force = opts.force
161   selected_fields = ["name", "pinst_list"]
162
163   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
164   result = SubmitOpCode(op)
165   node, pinst = result[0]
166
167   if not pinst:
168     logger.ToStderr("No primary instances on node %s, exiting." % node)
169     return 0
170
171   pinst = utils.NiceSort(pinst)
172
173   retcode = 0
174
175   if not force and not AskUser("Fail over instance(s) %s?" %
176                                (",".join("'%s'" % name for name in pinst))):
177     return 2
178
179   good_cnt = bad_cnt = 0
180   for iname in pinst:
181     op = opcodes.OpFailoverInstance(instance_name=iname,
182                                     ignore_consistency=opts.ignore_consistency)
183     try:
184       logger.ToStdout("Failing over instance %s" % iname)
185       SubmitOpCode(op)
186       logger.ToStdout("Instance %s has been failed over" % iname)
187       good_cnt += 1
188     except errors.GenericError, err:
189       nret, msg = FormatError(err)
190       retcode |= nret
191       logger.ToStderr("Error failing over instance %s: %s" % (iname, msg))
192       bad_cnt += 1
193
194   if retcode == 0:
195     logger.ToStdout("All %d instance(s) failed over successfully." % good_cnt)
196   else:
197     logger.ToStdout("There were errors during the failover:\n"
198                     "%d error(s) out of %d instance(s)." %
199                     (bad_cnt, good_cnt + bad_cnt))
200   return retcode
201
202
203 def ShowNodeConfig(opts, args):
204   """Show node information.
205
206   """
207   op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
208                                            "pinst_list", "sinst_list"],
209                             names=args)
210   result = SubmitOpCode(op)
211
212   for name, primary_ip, secondary_ip, pinst, sinst in result:
213     logger.ToStdout("Node name: %s" % name)
214     logger.ToStdout("  primary ip: %s" % primary_ip)
215     logger.ToStdout("  secondary ip: %s" % secondary_ip)
216     if pinst:
217       logger.ToStdout("  primary for instances:")
218       for iname in pinst:
219         logger.ToStdout("    - %s" % iname)
220     else:
221       logger.ToStdout("  primary for no instances")
222     if sinst:
223       logger.ToStdout("  secondary for instances:")
224       for iname in sinst:
225         logger.ToStdout("    - %s" % iname)
226     else:
227       logger.ToStdout("  secondary for no instances")
228
229   return 0
230
231
232 def RemoveNode(opts, args):
233   """Remove node cli-to-processor bridge."""
234   op = opcodes.OpRemoveNode(node_name=args[0])
235   SubmitOpCode(op)
236
237
238 def ListVolumes(opts, args):
239   """List logical volumes on node(s).
240
241   """
242   if opts.output is None:
243     selected_fields = ["node", "phys", "vg",
244                        "name", "size", "instance"]
245   else:
246     selected_fields = opts.output.split(",")
247
248   op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
249   output = SubmitOpCode(op)
250
251   if not opts.no_headers:
252     headers = {"node": "Node", "phys": "PhysDev",
253                "vg": "VG", "name": "Name",
254                "size": "Size", "instance": "Instance"}
255   else:
256     headers = None
257
258   if opts.human_readable:
259     unitfields = ["size"]
260   else:
261     unitfields = None
262
263   numfields = ["size"]
264
265   data = GenerateTable(separator=opts.separator, headers=headers,
266                        fields=selected_fields, unitfields=unitfields,
267                        numfields=numfields, data=output)
268
269   for line in data:
270     logger.ToStdout(line)
271
272   return 0
273
274
275 commands = {
276   'add': (AddNode, ARGS_ONE,
277           [DEBUG_OPT,
278            make_option("-s", "--secondary-ip", dest="secondary_ip",
279                        help="Specify the secondary ip for the node",
280                        metavar="ADDRESS", default=None),],
281           "<node_name>", "Add a node to the cluster"),
282   'evacuate': (EvacuateNode, ARGS_FIXED(2),
283                [DEBUG_OPT, FORCE_OPT],
284                "[-f] <src_node> <dst_node>",
285                "Relocate the secondary instances from the first node"
286                " to the second one (only for instances of type remote_raid1)"),
287   'failover': (FailoverNode, ARGS_ONE,
288                [DEBUG_OPT, FORCE_OPT,
289                 make_option("--ignore-consistency", dest="ignore_consistency",
290                             action="store_true", default=False,
291                             help="Ignore the consistency of the disks on"
292                             " the secondary"),
293                 ],
294                "[-f] <node>",
295                "Stops the primary instances on a node and start them on their"
296                " secondary node (only for instances of type remote_raid1)"),
297   'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
298            "[<node_name>...]", "Show information about the node(s)"),
299   'list': (ListNodes, ARGS_NONE,
300            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
301            "", "Lists the nodes in the cluster"),
302   'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
303              "<node_name>", "Removes a node from the cluster"),
304   'volumes': (ListVolumes, ARGS_ANY,
305               [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
306               "[<node_name>...]", "List logical volumes on node(s)"),
307   'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
308                 "<node_name>", "List the tags of the given node"),
309   'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
310                "<node_name> tag...", "Add tags to the given node"),
311   'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
312                   "<node_name> tag...", "Remove tags from the given node"),
313   }
314
315
316 if __name__ == '__main__':
317   sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))