Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-node @ e8a4c138

History | View | Annotate | Download (11.1 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
import sys
23
from optparse import make_option
24

    
25
from ganeti.cli import *
26
from ganeti import opcodes
27
from ganeti import logger
28
from ganeti import utils
29
from ganeti import constants
30
from ganeti import errors
31

    
32

    
33
def AddNode(opts, args):
34
  """Add node cli-to-processor bridge."""
35
  logger.ToStderr("-- WARNING -- \n"
36
    "Performing this operation is going to replace the ssh daemon keypair\n"
37
    "on the target machine (%s) with the ones of the current one\n"
38
    "and grant full intra-cluster ssh root access to/from it\n" % args[0])
39
  op = opcodes.OpAddNode(node_name=args[0], secondary_ip=opts.secondary_ip,
40
                         readd=opts.readd)
41
  SubmitOpCode(op)
42

    
43

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

    
47
  """
48
  if opts.output is None:
49
    selected_fields = ["name", "dtotal", "dfree",
50
                       "mtotal", "mnode", "mfree",
51
                       "pinst_cnt", "sinst_cnt"]
52
  else:
53
    selected_fields = opts.output.split(",")
54

    
55
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[])
56
  output = SubmitOpCode(op)
57

    
58
  if not opts.no_headers:
59
    headers = {
60
      "name": "Node", "pinst_cnt": "Pinst", "sinst_cnt": "Sinst",
61
      "pinst_list": "PriInstances", "sinst_list": "SecInstances",
62
      "pip": "PrimaryIP", "sip": "SecondaryIP",
63
      "dtotal": "DTotal", "dfree": "DFree",
64
      "mtotal": "MTotal", "mnode": "MNode", "mfree": "MFree",
65
      "bootid": "BootID",
66
      "ctotal": "CTotal",
67
      }
68
  else:
69
    headers = None
70

    
71
  if opts.human_readable:
72
    unitfields = ["dtotal", "dfree", "mtotal", "mnode", "mfree"]
73
  else:
74
    unitfields = None
75

    
76
  numfields = ["dtotal", "dfree",
77
               "mtotal", "mnode", "mfree",
78
               "pinst_cnt", "sinst_cnt",
79
               "ctotal"]
80

    
81
  # change raw values to nicer strings
82
  for row in output:
83
    for idx, field in enumerate(selected_fields):
84
      val = row[idx]
85
      if field == "pinst_list":
86
        val = ",".join(val)
87
      elif field == "sinst_list":
88
        val = ",".join(val)
89
      elif val is None:
90
        val = "?"
91
      row[idx] = str(val)
92

    
93
  data = GenerateTable(separator=opts.separator, headers=headers,
94
                       fields=selected_fields, unitfields=unitfields,
95
                       numfields=numfields, data=output)
96
  for line in data:
97
    logger.ToStdout(line)
98

    
99
  return 0
100

    
101

    
102
def EvacuateNode(opts, args):
103
  """Relocate all secondary instance from a node.
104

    
105
  """
106
  force = opts.force
107
  selected_fields = ["name", "sinst_list"]
108
  src_node, dst_node = args
109

    
110
  op = opcodes.OpQueryNodes(output_fields=selected_fields, names=[src_node])
111
  result = SubmitOpCode(op)
112
  src_node, sinst = result[0]
113
  op = opcodes.OpQueryNodes(output_fields=["name"], names=[dst_node])
114
  result = SubmitOpCode(op)
115
  dst_node = result[0][0]
116

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

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

    
126
  sinst = utils.NiceSort(sinst)
127

    
128
  retcode = constants.EXIT_SUCCESS
129

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

    
136
  good_cnt = bad_cnt = 0
137
  for iname in sinst:
138
    op = opcodes.OpReplaceDisks(instance_name=iname,
139
                                remote_node=dst_node,
140
                                mode=constants.REPLACE_DISK_ALL,
141
                                disks=["sda", "sdb"])
142
    try:
143
      logger.ToStdout("Replacing disks for instance %s" % iname)
144
      SubmitOpCode(op)
145
      logger.ToStdout("Instance %s has been relocated" % iname)
146
      good_cnt += 1
147
    except errors.GenericError, err:
148
      nret, msg = FormatError(err)
149
      retcode |= nret
150
      logger.ToStderr("Error replacing disks for instance %s: %s" %
151
                      (iname, msg))
152
      bad_cnt += 1
153

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

    
162

    
163
def FailoverNode(opts, args):
164
  """Failover all primary instance on a node.
165

    
166
  """
167
  force = opts.force
168
  selected_fields = ["name", "pinst_list"]
169

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

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

    
178
  pinst = utils.NiceSort(pinst)
179

    
180
  retcode = 0
181

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

    
186
  good_cnt = bad_cnt = 0
187
  for iname in pinst:
188
    op = opcodes.OpFailoverInstance(instance_name=iname,
189
                                    ignore_consistency=opts.ignore_consistency)
190
    try:
191
      logger.ToStdout("Failing over instance %s" % iname)
192
      SubmitOpCode(op)
193
      logger.ToStdout("Instance %s has been failed over" % iname)
194
      good_cnt += 1
195
    except errors.GenericError, err:
196
      nret, msg = FormatError(err)
197
      retcode |= nret
198
      logger.ToStderr("Error failing over instance %s: %s" % (iname, msg))
199
      bad_cnt += 1
200

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

    
209

    
210
def ShowNodeConfig(opts, args):
211
  """Show node information.
212

    
213
  """
214
  op = opcodes.OpQueryNodes(output_fields=["name", "pip", "sip",
215
                                           "pinst_list", "sinst_list"],
216
                            names=args)
217
  result = SubmitOpCode(op)
218

    
219
  for name, primary_ip, secondary_ip, pinst, sinst in result:
220
    logger.ToStdout("Node name: %s" % name)
221
    logger.ToStdout("  primary ip: %s" % primary_ip)
222
    logger.ToStdout("  secondary ip: %s" % secondary_ip)
223
    if pinst:
224
      logger.ToStdout("  primary for instances:")
225
      for iname in pinst:
226
        logger.ToStdout("    - %s" % iname)
227
    else:
228
      logger.ToStdout("  primary for no instances")
229
    if sinst:
230
      logger.ToStdout("  secondary for instances:")
231
      for iname in sinst:
232
        logger.ToStdout("    - %s" % iname)
233
    else:
234
      logger.ToStdout("  secondary for no instances")
235

    
236
  return 0
237

    
238

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

    
244

    
245
def ListVolumes(opts, args):
246
  """List logical volumes on node(s).
247

    
248
  """
249
  if opts.output is None:
250
    selected_fields = ["node", "phys", "vg",
251
                       "name", "size", "instance"]
252
  else:
253
    selected_fields = opts.output.split(",")
254

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

    
258
  if not opts.no_headers:
259
    headers = {"node": "Node", "phys": "PhysDev",
260
               "vg": "VG", "name": "Name",
261
               "size": "Size", "instance": "Instance"}
262
  else:
263
    headers = None
264

    
265
  if opts.human_readable:
266
    unitfields = ["size"]
267
  else:
268
    unitfields = None
269

    
270
  numfields = ["size"]
271

    
272
  data = GenerateTable(separator=opts.separator, headers=headers,
273
                       fields=selected_fields, unitfields=unitfields,
274
                       numfields=numfields, data=output)
275

    
276
  for line in data:
277
    logger.ToStdout(line)
278

    
279
  return 0
280

    
281

    
282
commands = {
283
  'add': (AddNode, ARGS_ONE,
284
          [DEBUG_OPT,
285
           make_option("-s", "--secondary-ip", dest="secondary_ip",
286
                       help="Specify the secondary ip for the node",
287
                       metavar="ADDRESS", default=None),
288
           make_option("--readd", dest="readd",
289
                       default=False, action="store_true",
290
                       help="Readd old node after replacing it"),
291
           ],
292
          "[-s ip] <node_name>", "Add a node to the cluster"),
293
  'evacuate': (EvacuateNode, ARGS_FIXED(2),
294
               [DEBUG_OPT, FORCE_OPT],
295
               "[-f] <src_node> <dst_node>",
296
               "Relocate the secondary instances from the first node"
297
               " to the second one (only for instances of type remote_raid1"
298
               " drbd)"),
299
  'failover': (FailoverNode, ARGS_ONE,
300
               [DEBUG_OPT, FORCE_OPT,
301
                make_option("--ignore-consistency", dest="ignore_consistency",
302
                            action="store_true", default=False,
303
                            help="Ignore the consistency of the disks on"
304
                            " the secondary"),
305
                ],
306
               "[-f] <node>",
307
               "Stops the primary instances on a node and start them on their"
308
               " secondary node (only for instances of type remote_raid1)"),
309
  'info': (ShowNodeConfig, ARGS_ANY, [DEBUG_OPT],
310
           "[<node_name>...]", "Show information about the node(s)"),
311
  'list': (ListNodes, ARGS_NONE,
312
           [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
313
           "", "Lists the nodes in the cluster. The available fields"
314
           " are (see the man page for details): name, pinst_cnt, pinst_list,"
315
           " sinst_cnt, sinst_list, pip, sip, dtotal, dfree, mtotal, mnode,"
316
           " mfree, bootid, cpu_count. The default field list is"
317
           " (in order): name,"
318
           " dtotal, dfree, mtotal, mnode, mfree, pinst_cnt, sinst_cnt."),
319
  'remove': (RemoveNode, ARGS_ONE, [DEBUG_OPT],
320
             "<node_name>", "Removes a node from the cluster"),
321
  'volumes': (ListVolumes, ARGS_ANY,
322
              [DEBUG_OPT, NOHDR_OPT, SEP_OPT, USEUNITS_OPT, FIELDS_OPT],
323
              "[<node_name>...]", "List logical volumes on node(s)"),
324
  'list-tags': (ListTags, ARGS_ONE, [DEBUG_OPT],
325
                "<node_name>", "List the tags of the given node"),
326
  'add-tags': (AddTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
327
               "<node_name> tag...", "Add tags to the given node"),
328
  'remove-tags': (RemoveTags, ARGS_ATLEAST(1), [DEBUG_OPT, TAG_SRC_OPT],
329
                  "<node_name> tag...", "Remove tags from the given node"),
330
  }
331

    
332

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