gnt-node 11.7 KB
Newer Older
Iustin Pop's avatar
Iustin Pop committed
1
2
3
#!/usr/bin/python
#

4
# Copyright (C) 2006, 2007, 2008 Google Inc.
Iustin Pop's avatar
Iustin Pop committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.


import sys
from optparse import make_option

from ganeti.cli import *
from ganeti import opcodes
from ganeti import logger
from ganeti import utils
29
from ganeti import constants
Iustin Pop's avatar
Iustin Pop committed
30
from ganeti import errors
31
from ganeti import bootstrap
Iustin Pop's avatar
Iustin Pop committed
32
33


34
35
36
37
38
39
_LIST_DEF_FIELDS = [
  "name", "dtotal", "dfree",
  "mtotal", "mnode", "mfree",
  "pinst_cnt", "sinst_cnt",
  ]

Michael Hanselmann's avatar
Michael Hanselmann committed
40

Iustin Pop's avatar
Iustin Pop committed
41
def AddNode(opts, args):
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
  """Add node cli-to-processor bridge.

  """
  dns_data = utils.HostInfo(args[0])
  node = dns_data.name

  if not opts.readd:
    op = opcodes.OpQueryNodes(output_fields=['name'], names=[node])
    try:
      output = SubmitOpCode(op)
    except (errors.OpPrereqError, errors.OpExecError):
      pass
    else:
      logger.ToStderr("Node %s already in the cluster (as %s)"
                      " - please use --readd" % (args[0], output[0][0]))
      return 1

59
60
61
  logger.ToStderr("-- WARNING -- \n"
    "Performing this operation is going to replace the ssh daemon keypair\n"
    "on the target machine (%s) with the ones of the current one\n"
62
63
    "and grant full intra-cluster ssh root access to/from it\n" % node)

64
65
  bootstrap.SetupNodeDaemon(node)

66
67
  op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
                         readd=opts.readd)
Iustin Pop's avatar
Iustin Pop committed
68
69
70
71
72
73
74
75
  SubmitOpCode(op)


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

  """
  if opts.output is None:
76
77
78
    selected_fields = _LIST_DEF_FIELDS
  elif opts.output.startswith("+"):
    selected_fields = _LIST_DEF_FIELDS + opts.output[1:].split(",")
Iustin Pop's avatar
Iustin Pop committed
79
80
81
  else:
    selected_fields = opts.output.split(",")

82
  output = GetClient().QueryNodes([], selected_fields)
Iustin Pop's avatar
Iustin Pop committed
83
84

  if not opts.no_headers:
85
86
87
88
89
90
91
92
    headers = {
      "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
      "pinst_list": "PriInstances", "sinst_list": "SecInstances",
      "pip": "PrimaryIP", "sip": "SecondaryIP",
      "dtotal": "DTotal", "dfree": "DFree",
      "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
      "bootid": "BootID",
      "ctotal": "CTotal",
93
      "tags": "Tags",
94
      }
95
96
97
98
99
100
101
102
  else:
    headers = None

  if opts.human_readable:
    unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
  else:
    unitfields = None

103
104
  numfields = ["dtotal", "dfree",
               "mtotal", "mnode", "mfree",
105
106
               "pinst_cnt", "sinst_cnt",
               "ctotal"]
107

108
  list_type_fields = ("pinst_list", "sinst_list", "tags")
109
110
111
112
  # change raw values to nicer strings
  for row in output:
    for idx, field in enumerate(selected_fields):
      val = row[idx]
113
      if field in list_type_fields:
114
115
116
117
        val = ",".join(val)
      elif val is None:
        val = "?"
      row[idx] = str(val)
118

119
120
121
122
123
  data = GenerateTable(separator=opts.separator, headers=headers,
                       fields=selected_fields, unitfields=unitfields,
                       numfields=numfields, data=output)
  for line in data:
    logger.ToStdout(line)
Iustin Pop's avatar
Iustin Pop committed
124
125
126
127

  return 0


Iustin Pop's avatar
Iustin Pop committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
def EvacuateNode(opts, args):
  """Relocate all secondary instance from a node.

  """
  force = opts.force
  selected_fields = ["name", "sinst_list"]
  src_node, dst_node = args

  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
  result = SubmitOpCode(op)
  src_node, sinst = result[0]
  op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
  result = SubmitOpCode(op)
  dst_node = result[0][0]

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

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

  sinst = utils.NiceSort(sinst)

  retcode = constants.EXIT_SUCCESS

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

  good_cnt = bad_cnt = 0
  for iname in sinst:
    op = opcodes.OpReplaceDisks(instance_name=iname,
165
166
167
                                remote_node=dst_node,
                                mode=constants.REPLACE_DISK_ALL,
                                disks=["sda", "sdb"])
Iustin Pop's avatar
Iustin Pop committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
    try:
      logger.ToStdout("Replacing disks for instance %s" % iname)
      SubmitOpCode(op)
      logger.ToStdout("Instance %s has been relocated" % iname)
      good_cnt += 1
    except errors.GenericError, err:
      nret, msg = FormatError(err)
      retcode |= nret
      logger.ToStderr("Error replacing disks for instance %s: %s" %
                      (iname, msg))
      bad_cnt += 1

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


Iustin Pop's avatar
Iustin Pop committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
def FailoverNode(opts, args):
  """Failover all primary instance on a node.

  """
  force = opts.force
  selected_fields = ["name", "pinst_list"]

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

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

  pinst = utils.NiceSort(pinst)

  retcode = 0

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

  good_cnt = bad_cnt = 0
  for iname in pinst:
    op = opcodes.OpFailoverInstance(instance_name=iname,
                                    ignore_consistency=opts.ignore_consistency)
    try:
      logger.ToStdout("Failing over instance %s" % iname)
      SubmitOpCode(op)
      logger.ToStdout("Instance %s has been failed over" % iname)
      good_cnt += 1
    except errors.GenericError, err:
      nret, msg = FormatError(err)
      retcode |= nret
      logger.ToStderr("Error failing over instance %s: %s" % (iname, msg))
      bad_cnt += 1

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


Iustin Pop's avatar
Iustin Pop committed
236
237
238
239
def ShowNodeConfig(opts, args):
  """Show node information.

  """
240
241
  op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
                                           "pinst_list", "sinst_list"],
242
                            names=args)
Iustin Pop's avatar
Iustin Pop committed
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
  result = SubmitOpCode(op)

  for name, primary_ip, secondary_ip, pinst, sinst in result:
    logger.ToStdout("Node name: %s" % name)
    logger.ToStdout("  primary ip: %s" % primary_ip)
    logger.ToStdout("  secondary ip: %s" % secondary_ip)
    if pinst:
      logger.ToStdout("  primary for instances:")
      for iname in pinst:
        logger.ToStdout("    - %s" % iname)
    else:
      logger.ToStdout("  primary for no instances")
    if sinst:
      logger.ToStdout("  secondary for instances:")
      for iname in sinst:
        logger.ToStdout("    - %s" % iname)
    else:
      logger.ToStdout("  secondary for no instances")

  return 0


def RemoveNode(opts, args):
  """Remove node cli-to-processor bridge."""
  op = opcodes.OpRemoveNode(node_name=args[0])
  SubmitOpCode(op)


271
272
273
274
275
276
277
278
279
280
281
282
283
284
def ListVolumes(opts, args):
  """List logical volumes on node(s).

  """
  if opts.output is None:
    selected_fields = ["node", "phys", "vg",
                       "name", "size", "instance"]
  else:
    selected_fields = opts.output.split(",")

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

  if not opts.no_headers:
285
286
287
288
289
290
291
292
293
294
295
296
297
    headers = {"node": "Node", "phys": "PhysDev",
               "vg": "VG", "name": "Name",
               "size": "Size", "instance": "Instance"}
  else:
    headers = None

  if opts.human_readable:
    unitfields = ["size"]
  else:
    unitfields = None

  numfields = ["size"]

298
299
300
301
302
303
  data = GenerateTable(separator=opts.separator, headers=headers,
                       fields=selected_fields, unitfields=unitfields,
                       numfields=numfields, data=output)

  for line in data:
    logger.ToStdout(line)
304
305
306
307

  return 0


Iustin Pop's avatar
Iustin Pop committed
308
309
310
311
312
commands = {
  'add': (AddNode, ARGS_ONE,
          [DEBUG_OPT,
           make_option("-s", "--secondary-ip", dest="secondary_ip",
                       help="Specify the secondary ip for the node",
313
314
315
316
317
                       metavar="ADDRESS", default=None),
           make_option("--readd", dest="readd",
                       default=False, action="store_true",
                       help="Readd old node after replacing it"),
           ],
318
          "[-s ip] [--readd] <node_name>", "Add a node to the cluster"),
Iustin Pop's avatar
Iustin Pop committed
319
320
  'evacuate': (EvacuateNode, ARGS_FIXED(2),
               [DEBUG_OPT, FORCE_OPT],
321
               "[-f] <src> <dst>",
Iustin Pop's avatar
Iustin Pop committed
322
               "Relocate the secondary instances from the first node"
323
324
               " to the second one (only for instances with drbd disk template"
               ),
Iustin Pop's avatar
Iustin Pop committed
325
326
327
328
329
330
331
  'failover': (FailoverNode, ARGS_ONE,
               [DEBUG_OPT, FORCE_OPT,
                make_option("--ignore-consistency", dest="ignore_consistency",
                            action="store_true", default=False,
                            help="Ignore the consistency of the disks on"
                            " the secondary"),
                ],
332
               "[-f] <node>",
Iustin Pop's avatar
Iustin Pop committed
333
               "Stops the primary instances on a node and start them on their"
334
               " secondary node (only for instances with drbd disk template)"),
Iustin Pop's avatar
Iustin Pop committed
335
  'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
336
           "[<node_name>...]", "Show information about the node(s)"),
Iustin Pop's avatar
Iustin Pop committed
337
  'list': (ListNodes, ARGS_NONE,
338
339
           [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT,
            SUBMIT_OPT],
340
           "", "Lists the nodes in the cluster. The available fields"
341
342
           " are (see the man page for details): name, pinst_cnt, pinst_list,"
           " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
343
           " mfree, bootid, cpu_count. The default field list is"
344
345
           " (in order): %s." % ", ".join(_LIST_DEF_FIELDS),
           ),
Iustin Pop's avatar
Iustin Pop committed
346
  'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
347
             "<node_name>", "Removes a node from the cluster"),
348
349
  'volumes': (ListVolumes, ARGS_ANY,
              [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
350
              "[<node_name>...]", "List logical volumes on node(s)"),
351
  'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
352
                "<node_name>", "List the tags of the given node"),
353
  'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
354
               "<node_name> tag...", "Add tags to the given node"),
355
  'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
356
                  "<node_name> tag...", "Remove tags from the given node"),
Iustin Pop's avatar
Iustin Pop committed
357
358
359
360
  }


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