Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-node @ 4331f6cd

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

    
59
  if not opts.readd:
60
    op = opcodes.OpQueryNodes(output_fields=['name'], names=[node])
61
    try:
62
      output = SubmitOpCode(op)
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
  ToStderr("-- WARNING -- \n"
71
           "Performing this operation is going to replace the ssh daemon"
72
           " keypair\n"
73
           "on the target machine (%s) with the ones of the"
74
           " current one\n"
75
           "and grant full intra-cluster ssh root access to/from it\n", node)
76

    
77
  bootstrap.SetupNodeDaemon(node, opts.ssh_key_check)
78

    
79
  op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
80
                         readd=opts.readd)
81
  SubmitOpCode(op)
82

    
83

    
84
def ListNodes(opts, args):
85
  """List nodes and their properties.
86

    
87
  @param opts: the command line options selected by the user
88
  @type args: list
89
  @param args: should be an empty list
90
  @rtype: int
91
  @return: the desired exit code
92

    
93
  """
94
  if opts.output is None:
95
    selected_fields = _LIST_DEF_FIELDS
96
  elif opts.output.startswith("+"):
97
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
98
  else:
99
    selected_fields = opts.output.split(",")
100

    
101
  output = GetClient().QueryNodes([], selected_fields)
102

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

    
118
  if opts.human_readable:
119
    unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
120
  else:
121
    unitfields = None
122

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

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

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

    
145
  return 0
146

    
147

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

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

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

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

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

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

    
178
  sinst = utils.NiceSort(sinst)
179

    
180
  retcode = constants.EXIT_SUCCESS
181

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

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

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

    
212

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

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

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

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

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

    
234
  pinst = utils.NiceSort(pinst)
235

    
236
  retcode = 0
237

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

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

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

    
264

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

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

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

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

    
299
  return 0
300

    
301

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

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

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

    
317

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

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

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

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

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

    
346
  if opts.human_readable:
347
    unitfields = ["size"]
348
  else:
349
    unitfields = None
350

    
351
  numfields = ["size"]
352

    
353
  data = GenerateTable(separator=opts.separator, headers=headers,
354
                       fields=selected_fields, unitfields=unitfields,
355
                       numfields=numfields, data=output)
356

    
357
  for line in data:
358
    ToStdout(line)
359

    
360
  return 0
361

    
362

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

    
419

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