Fix _AdjustCandidatePool
[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 #: headers (and full field list for L{ListNodes}
45 _LIST_HEADERS = {
46   "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
47   "pinst_list": "PriInstances", "sinst_list": "SecInstances",
48   "pip": "PrimaryIP", "sip": "SecondaryIP",
49   "dtotal": "DTotal", "dfree": "DFree",
50   "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
51   "bootid": "BootID",
52   "ctotal": "CTotal",
53   "tags": "Tags",
54   "serial_no": "SerialNo",
55   "master_candidate": "MasterC",
56   "master": "IsMaster",
57   "offline": "Offline",
58   }
59
60
61 @UsesRPC
62 def AddNode(opts, args):
63   """Add a node to the cluster.
64
65   @param opts: the command line options selected by the user
66   @type args: list
67   @param args: should contain only one element, the new node name
68   @rtype: int
69   @return: the desired exit code
70
71   """
72   cl = GetClient()
73   dns_data = utils.HostInfo(args[0])
74   node = dns_data.name
75
76   if not opts.readd:
77     try:
78       output = cl.QueryNodes(names=[node], fields=['name'])
79     except (errors.OpPrereqError, errors.OpExecError):
80       pass
81     else:
82       ToStderr("Node %s already in the cluster (as %s)"
83                " - please use --readd", args[0], output[0][0])
84       return 1
85
86   # read the cluster name from the master
87   output = cl.QueryConfigValues(['cluster_name'])
88   cluster_name = output[0]
89
90   ToStderr("-- WARNING -- \n"
91            "Performing this operation is going to replace the ssh daemon"
92            " keypair\n"
93            "on the target machine (%s) with the ones of the"
94            " current one\n"
95            "and grant full intra-cluster ssh root access to/from it\n", node)
96
97   bootstrap.SetupNodeDaemon(cluster_name, node, opts.ssh_key_check)
98
99   op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
100                          readd=opts.readd)
101   SubmitOpCode(op)
102
103
104 def ListNodes(opts, args):
105   """List nodes and their properties.
106
107   @param opts: the command line options selected by the user
108   @type args: list
109   @param args: should be an empty list
110   @rtype: int
111   @return: the desired exit code
112
113   """
114   if opts.output is None:
115     selected_fields = _LIST_DEF_FIELDS
116   elif opts.output.startswith("+"):
117     selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
118   else:
119     selected_fields = opts.output.split(",")
120
121   output = GetClient().QueryNodes([], selected_fields)
122
123   if not opts.no_headers:
124     headers = _LIST_HEADERS
125   else:
126     headers = None
127
128   unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
129
130   numfields = ["dtotal", "dfree",
131                "mtotal", "mnode", "mfree",
132                "pinst_cnt", "sinst_cnt",
133                "ctotal", "serial_no"]
134
135   list_type_fields = ("pinst_list", "sinst_list", "tags")
136   # change raw values to nicer strings
137   for row in output:
138     for idx, field in enumerate(selected_fields):
139       val = row[idx]
140       if field in list_type_fields:
141         val = ",".join(val)
142       elif field in ('master', 'master_candidate', 'offline'):
143         if val:
144           val = 'Y'
145         else:
146           val = 'N'
147       elif val is None:
148         val = "?"
149       row[idx] = str(val)
150
151   data = GenerateTable(separator=opts.separator, headers=headers,
152                        fields=selected_fields, unitfields=unitfields,
153                        numfields=numfields, data=output, units=opts.units)
154   for line in data:
155     ToStdout(line)
156
157   return 0
158
159
160 def EvacuateNode(opts, args):
161   """Relocate all secondary instance from a node.
162
163   @param opts: the command line options selected by the user
164   @type args: list
165   @param args: should be an empty list
166   @rtype: int
167   @return: the desired exit code
168
169   """
170   force = opts.force
171   selected_fields = ["name", "sinst_list"]
172   src_node, dst_node = args
173
174   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
175   result = SubmitOpCode(op)
176   src_node, sinst = result[0]
177   op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
178   result = SubmitOpCode(op)
179   dst_node = result[0][0]
180
181   if src_node == dst_node:
182     raise errors.OpPrereqError("Evacuate node needs different source and"
183                                " target nodes (node %s given twice)" %
184                                src_node)
185
186   if not sinst:
187     ToStderr("No secondary instances on node %s, exiting.", src_node)
188     return constants.EXIT_SUCCESS
189
190   sinst = utils.NiceSort(sinst)
191
192   retcode = constants.EXIT_SUCCESS
193
194   if not force and not AskUser("Relocate instance(s) %s from node\n"
195                                " %s to node\n %s?" %
196                                (",".join("'%s'" % name for name in sinst),
197                                src_node, dst_node)):
198     return constants.EXIT_CONFIRMATION
199
200   good_cnt = bad_cnt = 0
201   for iname in sinst:
202     op = opcodes.OpReplaceDisks(instance_name=iname,
203                                 remote_node=dst_node,
204                                 mode=constants.REPLACE_DISK_ALL,
205                                 disks=["sda", "sdb"])
206     try:
207       ToStdout("Replacing disks for instance %s", iname)
208       SubmitOpCode(op)
209       ToStdout("Instance %s has been relocated", iname)
210       good_cnt += 1
211     except errors.GenericError, err:
212       nret, msg = FormatError(err)
213       retcode |= nret
214       ToStderr("Error replacing disks for instance %s: %s", iname, msg)
215       bad_cnt += 1
216
217   if retcode == constants.EXIT_SUCCESS:
218     ToStdout("All %d instance(s) relocated successfully.", good_cnt)
219   else:
220     ToStdout("There were errors during the relocation:\n"
221              "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
222   return retcode
223
224
225 def FailoverNode(opts, args):
226   """Failover all primary instance on a node.
227
228   @param opts: the command line options selected by the user
229   @type args: list
230   @param args: should be an empty list
231   @rtype: int
232   @return: the desired exit code
233
234   """
235   force = opts.force
236   selected_fields = ["name", "pinst_list"]
237
238   op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
239   result = SubmitOpCode(op)
240   node, pinst = result[0]
241
242   if not pinst:
243     ToStderr("No primary instances on node %s, exiting.", node)
244     return 0
245
246   pinst = utils.NiceSort(pinst)
247
248   retcode = 0
249
250   if not force and not AskUser("Fail over instance(s) %s?" %
251                                (",".join("'%s'" % name for name in pinst))):
252     return 2
253
254   good_cnt = bad_cnt = 0
255   for iname in pinst:
256     op = opcodes.OpFailoverInstance(instance_name=iname,
257                                     ignore_consistency=opts.ignore_consistency)
258     try:
259       ToStdout("Failing over instance %s", iname)
260       SubmitOpCode(op)
261       ToStdout("Instance %s has been failed over", iname)
262       good_cnt += 1
263     except errors.GenericError, err:
264       nret, msg = FormatError(err)
265       retcode |= nret
266       ToStderr("Error failing over instance %s: %s", iname, msg)
267       bad_cnt += 1
268
269   if retcode == 0:
270     ToStdout("All %d instance(s) failed over successfully.", good_cnt)
271   else:
272     ToStdout("There were errors during the failover:\n"
273              "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
274   return retcode
275
276
277 def ShowNodeConfig(opts, args):
278   """Show node information.
279
280   @param opts: the command line options selected by the user
281   @type args: list
282   @param args: should either be an empty list, in which case
283       we show information about all nodes, or should contain
284       a list of nodes to be queried for information
285   @rtype: int
286   @return: the desired exit code
287
288   """
289   op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
290                                            "pinst_list", "sinst_list"],
291                             names=args)
292   result = SubmitOpCode(op)
293
294   for name, primary_ip, secondary_ip, pinst, sinst in result:
295     ToStdout("Node name: %s", name)
296     ToStdout("  primary ip: %s", primary_ip)
297     ToStdout("  secondary ip: %s", secondary_ip)
298     if pinst:
299       ToStdout("  primary for instances:")
300       for iname in pinst:
301         ToStdout("    - %s", iname)
302     else:
303       ToStdout("  primary for no instances")
304     if sinst:
305       ToStdout("  secondary for instances:")
306       for iname in sinst:
307         ToStdout("    - %s", iname)
308     else:
309       ToStdout("  secondary for no instances")
310
311   return 0
312
313
314 def RemoveNode(opts, args):
315   """Remove a node from the cluster.
316
317   @param opts: the command line options selected by the user
318   @type args: list
319   @param args: should contain only one element, the name of
320       the node to be removed
321   @rtype: int
322   @return: the desired exit code
323
324   """
325   op = opcodes.OpRemoveNode(node_name=args[0])
326   SubmitOpCode(op)
327   return 0
328
329
330 def ListVolumes(opts, args):
331   """List logical volumes on node(s).
332
333   @param opts: the command line options selected by the user
334   @type args: list
335   @param args: should either be an empty list, in which case
336       we list data for all nodes, or contain a list of nodes
337       to display data only for those
338   @rtype: int
339   @return: the desired exit code
340
341   """
342   if opts.output is None:
343     selected_fields = ["node", "phys", "vg",
344                        "name", "size", "instance"]
345   else:
346     selected_fields = opts.output.split(",")
347
348   op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
349   output = SubmitOpCode(op)
350
351   if not opts.no_headers:
352     headers = {"node": "Node", "phys": "PhysDev",
353                "vg": "VG", "name": "Name",
354                "size": "Size", "instance": "Instance"}
355   else:
356     headers = None
357
358   unitfields = ["size"]
359
360   numfields = ["size"]
361
362   data = GenerateTable(separator=opts.separator, headers=headers,
363                        fields=selected_fields, unitfields=unitfields,
364                        numfields=numfields, data=output, units=opts.units)
365
366   for line in data:
367     ToStdout(line)
368
369   return 0
370
371
372 def SetNodeParams(opts, args):
373   """Modifies a node.
374
375   @param opts: the command line options selected by the user
376   @type args: list
377   @param args: should contain only one element, the node name
378   @rtype: int
379   @return: the desired exit code
380
381   """
382   if opts.master_candidate is None and opts.offline is None:
383     ToStderr("Please give at least one of the parameters.")
384     return 1
385
386   if opts.master_candidate is not None:
387     candidate = opts.master_candidate == 'yes'
388   else:
389     candidate = None
390   if opts.offline is not None:
391     offline = opts.offline == 'yes'
392   else:
393     offline = None
394   op = opcodes.OpSetNodeParams(node_name=args[0],
395                                master_candidate=candidate,
396                                offline=offline,
397                                force=opts.force)
398
399   # even if here we process the result, we allow submit only
400   result = SubmitOrSend(op, opts)
401
402   if result:
403     ToStdout("Modified node %s", args[0])
404     for param, data in result:
405       ToStdout(" - %-5s -> %s", param, data)
406   return 0
407
408
409 commands = {
410   'add': (AddNode, ARGS_ONE,
411           [DEBUG_OPT,
412            make_option("-s", "--secondary-ip", dest="secondary_ip",
413                        help="Specify the secondary ip for the node",
414                        metavar="ADDRESS", default=None),
415            make_option("--readd", dest="readd",
416                        default=False, action="store_true",
417                        help="Readd old node after replacing it"),
418            make_option("--no-ssh-key-check", dest="ssh_key_check",
419                        default=True, action="store_false",
420                        help="Disable SSH key fingerprint checking"),
421            ],
422           "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
423           "Add a node to the cluster"),
424   'evacuate': (EvacuateNode, ARGS_FIXED(2),
425                [DEBUG_OPT, FORCE_OPT],
426                "[-f] <src> <dst>",
427                "Relocate the secondary instances from the first node"
428                " to the second one (only for instances with drbd disk template"
429                ),
430   'failover': (FailoverNode, ARGS_ONE,
431                [DEBUG_OPT, FORCE_OPT,
432                 make_option("--ignore-consistency", dest="ignore_consistency",
433                             action="store_true", default=False,
434                             help="Ignore the consistency of the disks on"
435                             " the secondary"),
436                 ],
437                "[-f] <node>",
438                "Stops the primary instances on a node and start them on their"
439                " secondary node (only for instances with drbd disk template)"),
440   'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
441            "[<node_name>...]", "Show information about the node(s)"),
442   'list': (ListNodes, ARGS_NONE,
443            [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
444             SUBMIT_OPT],
445            "", "Lists the nodes in the cluster. The available fields"
446            " are (see the man page for details): %s"
447            " The default field list is (in order): %s." %
448            (", ".join(_LIST_HEADERS), ", ".join(_LIST_DEF_FIELDS))),
449   'modify': (SetNodeParams, ARGS_ONE,
450              [DEBUG_OPT, FORCE_OPT,
451               SUBMIT_OPT,
452               make_option("-C", "--master-candidate", dest="master_candidate",
453                           choices=('yes', 'no'), default=None,
454                           help="Set the master_candidate flag on the node"),
455               make_option("-O", "--offline", dest="offline",
456                           choices=('yes', 'no'), default=None,
457                           help="Set the offline flag on the node"),
458               ],
459              "<instance>", "Alters the parameters of an instance"),
460   'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
461              "<node_name>", "Removes a node from the cluster"),
462   'volumes': (ListVolumes, ARGS_ANY,
463               [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
464               "[<node_name>...]", "List logical volumes on node(s)"),
465   'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
466                 "<node_name>", "List the tags of the given node"),
467   'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
468                "<node_name> tag...", "Add tags to the given node"),
469   'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
470                   "<node_name> tag...", "Remove tags from the given node"),
471   }
472
473
474 if __name__ == '__main__':
475   sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))