Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-node @ 0e67cdbe

History | View | Annotate | Download (13.6 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
      "master_candidate": "MasterC",
119
      "master": "IsMaster",
120
      }
121
  else:
122
    headers = None
123

    
124
  unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
125

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

    
131
  list_type_fields = ("pinst_list", "sinst_list", "tags")
132
  # change raw values to nicer strings
133
  for row in output:
134
    for idx, field in enumerate(selected_fields):
135
      val = row[idx]
136
      if field in list_type_fields:
137
        val = ",".join(val)
138
      elif field in ('master', 'master_candidate'):
139
        if val:
140
          val = 'Y'
141
        else:
142
          val = 'N'
143
      elif val is None:
144
        val = "?"
145
      row[idx] = str(val)
146

    
147
  data = GenerateTable(separator=opts.separator, headers=headers,
148
                       fields=selected_fields, unitfields=unitfields,
149
                       numfields=numfields, data=output, units=opts.units)
150
  for line in data:
151
    ToStdout(line)
152

    
153
  return 0
154

    
155

    
156
def EvacuateNode(opts, args):
157
  """Relocate all secondary instance from a node.
158

    
159
  @param opts: the command line options selected by the user
160
  @type args: list
161
  @param args: should be an empty list
162
  @rtype: int
163
  @return: the desired exit code
164

    
165
  """
166
  force = opts.force
167
  selected_fields = ["name", "sinst_list"]
168
  src_node, dst_node = args
169

    
170
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
171
  result = SubmitOpCode(op)
172
  src_node, sinst = result[0]
173
  op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
174
  result = SubmitOpCode(op)
175
  dst_node = result[0][0]
176

    
177
  if src_node == dst_node:
178
    raise errors.OpPrereqError("Evacuate node needs different source and"
179
                               " target nodes (node %s given twice)" %
180
                               src_node)
181

    
182
  if not sinst:
183
    ToStderr("No secondary instances on node %s, exiting.", src_node)
184
    return constants.EXIT_SUCCESS
185

    
186
  sinst = utils.NiceSort(sinst)
187

    
188
  retcode = constants.EXIT_SUCCESS
189

    
190
  if not force and not AskUser("Relocate instance(s) %s from node\n"
191
                               " %s to node\n %s?" %
192
                               (",".join("'%s'" % name for name in sinst),
193
                               src_node, dst_node)):
194
    return constants.EXIT_CONFIRMATION
195

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

    
213
  if retcode == constants.EXIT_SUCCESS:
214
    ToStdout("All %d instance(s) relocated successfully.", good_cnt)
215
  else:
216
    ToStdout("There were errors during the relocation:\n"
217
             "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
218
  return retcode
219

    
220

    
221
def FailoverNode(opts, args):
222
  """Failover all primary instance on a node.
223

    
224
  @param opts: the command line options selected by the user
225
  @type args: list
226
  @param args: should be an empty list
227
  @rtype: int
228
  @return: the desired exit code
229

    
230
  """
231
  force = opts.force
232
  selected_fields = ["name", "pinst_list"]
233

    
234
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=args)
235
  result = SubmitOpCode(op)
236
  node, pinst = result[0]
237

    
238
  if not pinst:
239
    ToStderr("No primary instances on node %s, exiting.", node)
240
    return 0
241

    
242
  pinst = utils.NiceSort(pinst)
243

    
244
  retcode = 0
245

    
246
  if not force and not AskUser("Fail over instance(s) %s?" %
247
                               (",".join("'%s'" % name for name in pinst))):
248
    return 2
249

    
250
  good_cnt = bad_cnt = 0
251
  for iname in pinst:
252
    op = opcodes.OpFailoverInstance(instance_name=iname,
253
                                    ignore_consistency=opts.ignore_consistency)
254
    try:
255
      ToStdout("Failing over instance %s", iname)
256
      SubmitOpCode(op)
257
      ToStdout("Instance %s has been failed over", iname)
258
      good_cnt += 1
259
    except errors.GenericError, err:
260
      nret, msg = FormatError(err)
261
      retcode |= nret
262
      ToStderr("Error failing over instance %s: %s", iname, msg)
263
      bad_cnt += 1
264

    
265
  if retcode == 0:
266
    ToStdout("All %d instance(s) failed over successfully.", good_cnt)
267
  else:
268
    ToStdout("There were errors during the failover:\n"
269
             "%d error(s) out of %d instance(s).", bad_cnt, good_cnt + bad_cnt)
270
  return retcode
271

    
272

    
273
def ShowNodeConfig(opts, args):
274
  """Show node information.
275

    
276
  @param opts: the command line options selected by the user
277
  @type args: list
278
  @param args: should either be an empty list, in which case
279
      we show information about all nodes, or should contain
280
      a list of nodes to be queried for information
281
  @rtype: int
282
  @return: the desired exit code
283

    
284
  """
285
  op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
286
                                           "pinst_list", "sinst_list"],
287
                            names=args)
288
  result = SubmitOpCode(op)
289

    
290
  for name, primary_ip, secondary_ip, pinst, sinst in result:
291
    ToStdout("Node name: %s", name)
292
    ToStdout("  primary ip: %s", primary_ip)
293
    ToStdout("  secondary ip: %s", secondary_ip)
294
    if pinst:
295
      ToStdout("  primary for instances:")
296
      for iname in pinst:
297
        ToStdout("    - %s", iname)
298
    else:
299
      ToStdout("  primary for no instances")
300
    if sinst:
301
      ToStdout("  secondary for instances:")
302
      for iname in sinst:
303
        ToStdout("    - %s", iname)
304
    else:
305
      ToStdout("  secondary for no instances")
306

    
307
  return 0
308

    
309

    
310
def RemoveNode(opts, args):
311
  """Remove a node from the cluster.
312

    
313
  @param opts: the command line options selected by the user
314
  @type args: list
315
  @param args: should contain only one element, the name of
316
      the node to be removed
317
  @rtype: int
318
  @return: the desired exit code
319

    
320
  """
321
  op = opcodes.OpRemoveNode(node_name=args[0])
322
  SubmitOpCode(op)
323
  return 0
324

    
325

    
326
def ListVolumes(opts, args):
327
  """List logical volumes on node(s).
328

    
329
  @param opts: the command line options selected by the user
330
  @type args: list
331
  @param args: should either be an empty list, in which case
332
      we list data for all nodes, or contain a list of nodes
333
      to display data only for those
334
  @rtype: int
335
  @return: the desired exit code
336

    
337
  """
338
  if opts.output is None:
339
    selected_fields = ["node", "phys", "vg",
340
                       "name", "size", "instance"]
341
  else:
342
    selected_fields = opts.output.split(",")
343

    
344
  op = opcodes.OpQueryNodeVolumes(nodes=args, output_fields=selected_fields)
345
  output = SubmitOpCode(op)
346

    
347
  if not opts.no_headers:
348
    headers = {"node": "Node", "phys": "PhysDev",
349
               "vg": "VG", "name": "Name",
350
               "size": "Size", "instance": "Instance"}
351
  else:
352
    headers = None
353

    
354
  unitfields = ["size"]
355

    
356
  numfields = ["size"]
357

    
358
  data = GenerateTable(separator=opts.separator, headers=headers,
359
                       fields=selected_fields, unitfields=unitfields,
360
                       numfields=numfields, data=output, units=opts.units)
361

    
362
  for line in data:
363
    ToStdout(line)
364

    
365
  return 0
366

    
367

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

    
424

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