Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-node @ 87622829

History | View | Annotate | Download (13.4 kB)

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
  cl = GetClient()
57
  dns_data = utils.HostInfo(args[0])
58
  node = dns_data.name
59

    
60
  if not opts.readd:
61
    try:
62
      output = cl.QueryNodes(names=[node], fields=['name'])
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
  # read the cluster name from the master
71
  output = cl.QueryConfigValues(['cluster_name'])
72
  cluster_name = output[0]
73

    
74
  ToStderr("-- WARNING -- \n"
75
           "Performing this operation is going to replace the ssh daemon"
76
           " keypair\n"
77
           "on the target machine (%s) with the ones of the"
78
           " current one\n"
79
           "and grant full intra-cluster ssh root access to/from it\n", node)
80

    
81
  bootstrap.SetupNodeDaemon(cluster_name, node, opts.ssh_key_check)
82

    
83
  op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
84
                         readd=opts.readd)
85
  SubmitOpCode(op)
86

    
87

    
88
def ListNodes(opts, args):
89
  """List nodes and their properties.
90

    
91
  @param opts: the command line options selected by the user
92
  @type args: list
93
  @param args: should be an empty list
94
  @rtype: int
95
  @return: the desired exit code
96

    
97
  """
98
  if opts.output is None:
99
    selected_fields = _LIST_DEF_FIELDS
100
  elif opts.output.startswith("+"):
101
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
102
  else:
103
    selected_fields = opts.output.split(",")
104

    
105
  output = GetClient().QueryNodes([], selected_fields)
106

    
107
  if not opts.no_headers:
108
    headers = {
109
      "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
110
      "pinst_list": "PriInstances", "sinst_list": "SecInstances",
111
      "pip": "PrimaryIP", "sip": "SecondaryIP",
112
      "dtotal": "DTotal", "dfree": "DFree",
113
      "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
114
      "bootid": "BootID",
115
      "ctotal": "CTotal",
116
      "tags": "Tags",
117
      "serial_no": "SerialNo",
118
      }
119
  else:
120
    headers = None
121

    
122
  unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
123

    
124
  numfields = ["dtotal", "dfree",
125
               "mtotal", "mnode", "mfree",
126
               "pinst_cnt", "sinst_cnt",
127
               "ctotal", "serial_no"]
128

    
129
  list_type_fields = ("pinst_list", "sinst_list", "tags")
130
  # change raw values to nicer strings
131
  for row in output:
132
    for idx, field in enumerate(selected_fields):
133
      val = row[idx]
134
      if field in list_type_fields:
135
        val = ",".join(val)
136
      elif val is None:
137
        val = "?"
138
      row[idx] = str(val)
139

    
140
  data = GenerateTable(separator=opts.separator, headers=headers,
141
                       fields=selected_fields, unitfields=unitfields,
142
                       numfields=numfields, data=output, units=opts.units)
143
  for line in data:
144
    ToStdout(line)
145

    
146
  return 0
147

    
148

    
149
def EvacuateNode(opts, args):
150
  """Relocate all secondary instance from a node.
151

    
152
  @param opts: the command line options selected by the user
153
  @type args: list
154
  @param args: should be an empty list
155
  @rtype: int
156
  @return: the desired exit code
157

    
158
  """
159
  force = opts.force
160
  selected_fields = ["name", "sinst_list"]
161
  src_node, dst_node = args
162

    
163
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
164
  result = SubmitOpCode(op)
165
  src_node, sinst = result[0]
166
  op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
167
  result = SubmitOpCode(op)
168
  dst_node = result[0][0]
169

    
170
  if src_node == dst_node:
171
    raise errors.OpPrereqError("Evacuate node needs different source and"
172
                               " target nodes (node %s given twice)" %
173
                               src_node)
174

    
175
  if not sinst:
176
    ToStderr("No secondary instances on node %s, exiting.", src_node)
177
    return constants.EXIT_SUCCESS
178

    
179
  sinst = utils.NiceSort(sinst)
180

    
181
  retcode = constants.EXIT_SUCCESS
182

    
183
  if not force and not AskUser("Relocate instance(s) %s from node\n"
184
                               " %s to node\n %s?" %
185
                               (",".join("'%s'" % name for name in sinst),
186
                               src_node, dst_node)):
187
    return constants.EXIT_CONFIRMATION
188

    
189
  good_cnt = bad_cnt = 0
190
  for iname in sinst:
191
    op = opcodes.OpReplaceDisks(instance_name=iname,
192
                                remote_node=dst_node,
193
                                mode=constants.REPLACE_DISK_ALL,
194
                                disks=["sda", "sdb"])
195
    try:
196
      ToStdout("Replacing disks for instance %s", iname)
197
      SubmitOpCode(op)
198
      ToStdout("Instance %s has been relocated", iname)
199
      good_cnt += 1
200
    except errors.GenericError, err:
201
      nret, msg = FormatError(err)
202
      retcode |= nret
203
      ToStderr("Error replacing disks for instance %s: %s", iname, msg)
204
      bad_cnt += 1
205

    
206
  if retcode == constants.EXIT_SUCCESS:
207
    ToStdout("All %d instance(s) relocated successfully.", good_cnt)
208
  else:
209
    ToStdout("There were errors during the relocation:\n"
210
             "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
211
  return retcode
212

    
213

    
214
def FailoverNode(opts, args):
215
  """Failover all primary instance on a node.
216

    
217
  @param opts: the command line options selected by the user
218
  @type args: list
219
  @param args: should be an empty list
220
  @rtype: int
221
  @return: the desired exit code
222

    
223
  """
224
  force = opts.force
225
  selected_fields = ["name", "pinst_list"]
226

    
227
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
228
  result = SubmitOpCode(op)
229
  node, pinst = result[0]
230

    
231
  if not pinst:
232
    ToStderr("No primary instances on node %s, exiting.", node)
233
    return 0
234

    
235
  pinst = utils.NiceSort(pinst)
236

    
237
  retcode = 0
238

    
239
  if not force and not AskUser("Fail over instance(s) %s?" %
240
                               (",".join("'%s'" % name for name in pinst))):
241
    return 2
242

    
243
  good_cnt = bad_cnt = 0
244
  for iname in pinst:
245
    op = opcodes.OpFailoverInstance(instance_name=iname,
246
                                    ignore_consistency=opts.ignore_consistency)
247
    try:
248
      ToStdout("Failing over instance %s", iname)
249
      SubmitOpCode(op)
250
      ToStdout("Instance %s has been failed over", iname)
251
      good_cnt += 1
252
    except errors.GenericError, err:
253
      nret, msg = FormatError(err)
254
      retcode |= nret
255
      ToStderr("Error failing over instance %s: %s", iname, msg)
256
      bad_cnt += 1
257

    
258
  if retcode == 0:
259
    ToStdout("All %d instance(s) failed over successfully.", good_cnt)
260
  else:
261
    ToStdout("There were errors during the failover:\n"
262
             "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
263
  return retcode
264

    
265

    
266
def ShowNodeConfig(opts, args):
267
  """Show node information.
268

    
269
  @param opts: the command line options selected by the user
270
  @type args: list
271
  @param args: should either be an empty list, in which case
272
      we show information about all nodes, or should contain
273
      a list of nodes to be queried for information
274
  @rtype: int
275
  @return: the desired exit code
276

    
277
  """
278
  op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
279
                                           "pinst_list", "sinst_list"],
280
                            names=args)
281
  result = SubmitOpCode(op)
282

    
283
  for name, primary_ip, secondary_ip, pinst, sinst in result:
284
    ToStdout("Node name: %s", name)
285
    ToStdout("  primary ip: %s", primary_ip)
286
    ToStdout("  secondary ip: %s", secondary_ip)
287
    if pinst:
288
      ToStdout("  primary for instances:")
289
      for iname in pinst:
290
        ToStdout("    - %s", iname)
291
    else:
292
      ToStdout("  primary for no instances")
293
    if sinst:
294
      ToStdout("  secondary for instances:")
295
      for iname in sinst:
296
        ToStdout("    - %s", iname)
297
    else:
298
      ToStdout("  secondary for no instances")
299

    
300
  return 0
301

    
302

    
303
def RemoveNode(opts, args):
304
  """Remove a node from the cluster.
305

    
306
  @param opts: the command line options selected by the user
307
  @type args: list
308
  @param args: should contain only one element, the name of
309
      the node to be removed
310
  @rtype: int
311
  @return: the desired exit code
312

    
313
  """
314
  op = opcodes.OpRemoveNode(node_name=args[0])
315
  SubmitOpCode(op)
316
  return 0
317

    
318

    
319
def ListVolumes(opts, args):
320
  """List logical volumes on node(s).
321

    
322
  @param opts: the command line options selected by the user
323
  @type args: list
324
  @param args: should either be an empty list, in which case
325
      we list data for all nodes, or contain a list of nodes
326
      to display data only for those
327
  @rtype: int
328
  @return: the desired exit code
329

    
330
  """
331
  if opts.output is None:
332
    selected_fields = ["node", "phys", "vg",
333
                       "name", "size", "instance"]
334
  else:
335
    selected_fields = opts.output.split(",")
336

    
337
  op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
338
  output = SubmitOpCode(op)
339

    
340
  if not opts.no_headers:
341
    headers = {"node": "Node", "phys": "PhysDev",
342
               "vg": "VG", "name": "Name",
343
               "size": "Size", "instance": "Instance"}
344
  else:
345
    headers = None
346

    
347
  unitfields = ["size"]
348

    
349
  numfields = ["size"]
350

    
351
  data = GenerateTable(separator=opts.separator, headers=headers,
352
                       fields=selected_fields, unitfields=unitfields,
353
                       numfields=numfields, data=output, units=opts.units)
354

    
355
  for line in data:
356
    ToStdout(line)
357

    
358
  return 0
359

    
360

    
361
commands = {
362
  'add': (AddNode, ARGS_ONE,
363
          [DEBUG_OPT,
364
           make_option("-s", "--secondary-ip", dest="secondary_ip",
365
                       help="Specify the secondary ip for the node",
366
                       metavar="ADDRESS", default=None),
367
           make_option("--readd", dest="readd",
368
                       default=False, action="store_true",
369
                       help="Readd old node after replacing it"),
370
           make_option("--no-ssh-key-check", dest="ssh_key_check",
371
                       default=True, action="store_false",
372
                       help="Disable SSH key fingerprint checking"),
373
           ],
374
          "[-s ip] [--readd] [--no-ssh-key-check] <node_name>",
375
          "Add a node to the cluster"),
376
  'evacuate': (EvacuateNode, ARGS_FIXED(2),
377
               [DEBUG_OPT, FORCE_OPT],
378
               "[-f] <src> <dst>",
379
               "Relocate the secondary instances from the first node"
380
               " to the second one (only for instances with drbd disk template"
381
               ),
382
  'failover': (FailoverNode, ARGS_ONE,
383
               [DEBUG_OPT, FORCE_OPT,
384
                make_option("--ignore-consistency", dest="ignore_consistency",
385
                            action="store_true", default=False,
386
                            help="Ignore the consistency of the disks on"
387
                            " the secondary"),
388
                ],
389
               "[-f] <node>",
390
               "Stops the primary instances on a node and start them on their"
391
               " secondary node (only for instances with drbd disk template)"),
392
  'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
393
           "[<node_name>...]", "Show information about the node(s)"),
394
  'list': (ListNodes, ARGS_NONE,
395
           [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
396
            SUBMIT_OPT],
397
           "", "Lists the nodes in the cluster. The available fields"
398
           " are (see the man page for details): name, pinst_cnt, pinst_list,"
399
           " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
400
           " mfree, bootid, cpu_count, serial_no."
401
           " The default field list is"
402
           " (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
403
           ),
404
  'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
405
             "<node_name>", "Removes a node from the cluster"),
406
  'volumes': (ListVolumes, ARGS_ANY,
407
              [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
408
              "[<node_name>...]", "List logical volumes on node(s)"),
409
  'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
410
                "<node_name>", "List the tags of the given node"),
411
  'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
412
               "<node_name> tag...", "Add tags to the given node"),
413
  'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
414
                  "<node_name> tag...", "Remove tags from the given node"),
415
  }
416

    
417

    
418
if __name__ == '__main__':
419
  sys.exit(GenericMain(commands, override={"tag_type": constants.TAG_NODE}))