Statistics
| Branch: | Tag: | Revision:

root / scripts / gnt-cluster @ 90b6aa3a

History | View | Annotate | Download (13.8 kB)

1
#!/usr/bin/python
2
#
3

    
4
# Copyright (C) 2006, 2007 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
import pprint
25

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

    
32

    
33
def InitCluster(opts, args):
34
  """Initialize the cluster.
35

    
36
  Args:
37
    opts - class with options as members
38
    args - list of arguments, expected to be [clustername]
39

    
40
  """
41
  if not opts.lvm_storage and opts.vg_name:
42
    print ("Options --no-lvm-storage and --vg-name conflict.")
43
    return 1
44

    
45
  vg_name = opts.vg_name
46
  if opts.lvm_storage and not opts.vg_name:
47
    vg_name = constants.DEFAULT_VG
48

    
49
  op = opcodes.OpInitCluster(cluster_name=args[0],
50
                             secondary_ip=opts.secondary_ip,
51
                             hypervisor_type=opts.hypervisor_type,
52
                             vg_name=vg_name,
53
                             mac_prefix=opts.mac_prefix,
54
                             def_bridge=opts.def_bridge,
55
                             master_netdev=opts.master_netdev,
56
                             file_storage_dir=opts.file_storage_dir)
57
  SubmitOpCode(op)
58
  return 0
59

    
60

    
61
def DestroyCluster(opts, args):
62
  """Destroy the cluster.
63

    
64
  Args:
65
    opts - class with options as members
66

    
67
  """
68
  if not opts.yes_do_it:
69
    print ("Destroying a cluster is irreversibly. If you really want destroy"
70
           " this cluster, supply the --yes-do-it option.")
71
    return 1
72

    
73
  op = opcodes.OpDestroyCluster()
74
  SubmitOpCode(op)
75
  return 0
76

    
77

    
78
def RenameCluster(opts, args):
79
  """Rename the cluster.
80

    
81
  Args:
82
    opts - class with options as members, we use force only
83
    args - list of arguments, expected to be [new_name]
84

    
85
  """
86
  name = args[0]
87
  if not opts.force:
88
    usertext = ("This will rename the cluster to '%s'. If you are connected"
89
                " over the network to the cluster name, the operation is very"
90
                " dangerous as the IP address will be removed from the node"
91
                " and the change may not go through. Continue?") % name
92
    if not AskUser(usertext):
93
      return 1
94

    
95
  op = opcodes.OpRenameCluster(name=name)
96
  SubmitOpCode(op)
97
  return 0
98

    
99

    
100
def ShowClusterVersion(opts, args):
101
  """Write version of ganeti software to the standard output.
102

    
103
  Args:
104
    opts - class with options as members
105

    
106
  """
107
  op = opcodes.OpQueryClusterInfo()
108
  result = SubmitOpCode(op)
109
  print ("Software version: %s" % result["software_version"])
110
  print ("Internode protocol: %s" % result["protocol_version"])
111
  print ("Configuration format: %s" % result["config_version"])
112
  print ("OS api version: %s" % result["os_api_version"])
113
  print ("Export interface: %s" % result["export_version"])
114
  return 0
115

    
116

    
117
def ShowClusterMaster(opts, args):
118
  """Write name of master node to the standard output.
119

    
120
  Args:
121
    opts - class with options as members
122

    
123
  """
124
  op = opcodes.OpQueryClusterInfo()
125
  result = SubmitOpCode(op)
126
  print (result["master"])
127
  return 0
128

    
129

    
130
def ShowClusterConfig(opts, args):
131
  """Shows cluster information.
132

    
133
  """
134
  op = opcodes.OpQueryClusterInfo()
135
  result = SubmitOpCode(op)
136

    
137
  print ("Cluster name: %s" % result["name"])
138

    
139
  print ("Master node: %s" % result["master"])
140

    
141
  print ("Architecture (this node): %s (%s)" %
142
         (result["architecture"][0], result["architecture"][1]))
143

    
144
  return 0
145

    
146

    
147
def ClusterCopyFile(opts, args):
148
  """Copy a file from master to some nodes.
149

    
150
  Args:
151
    opts - class with options as members
152
    args - list containing a single element, the file name
153
  Opts used:
154
    nodes - list containing the name of target nodes; if empty, all nodes
155

    
156
  """
157
  op = opcodes.OpClusterCopyFile(filename=args[0], nodes=opts.nodes)
158
  SubmitOpCode(op)
159
  return 0
160

    
161

    
162
def RunClusterCommand(opts, args):
163
  """Run a command on some nodes.
164

    
165
  Args:
166
    opts - class with options as members
167
    args - the command list as a list
168
  Opts used:
169
    nodes: list containing the name of target nodes; if empty, all nodes
170

    
171
  """
172
  command = " ".join(args)
173
  nodes = opts.nodes
174
  op = opcodes.OpRunClusterCommand(command=command, nodes=nodes)
175
  result = SubmitOpCode(op)
176
  for node, output, exit_code in result:
177
    print ("------------------------------------------------")
178
    print ("node: %s" % node)
179
    print ("%s" % output)
180
    print ("return code = %s" % exit_code)
181

    
182

    
183
def VerifyCluster(opts, args):
184
  """Verify integrity of cluster, performing various test on nodes.
185

    
186
  Args:
187
    opts - class with options as members
188

    
189
  """
190
  op = opcodes.OpVerifyCluster()
191
  result = SubmitOpCode(op)
192
  return result
193

    
194

    
195
def VerifyDisks(opts, args):
196
  """Verify integrity of cluster disks.
197

    
198
  Args:
199
    opts - class with options as members
200

    
201
  """
202
  op = opcodes.OpVerifyDisks()
203
  result = SubmitOpCode(op)
204
  if not isinstance(result, tuple) or len(result) != 4:
205
    raise errors.ProgrammerError("Unknown result type for OpVerifyDisks")
206

    
207
  nodes, nlvm, instances, missing = result
208

    
209
  if nodes:
210
    print "Nodes unreachable or with bad data:"
211
    for name in nodes:
212
      print "\t%s" % name
213
  retcode = constants.EXIT_SUCCESS
214

    
215
  if nlvm:
216
    for node, text in nlvm.iteritems():
217
      print ("Error on node %s: LVM error: %s" %
218
             (node, text[-400:].encode('string_escape')))
219
      retcode |= 1
220
      print "You need to fix these nodes first before fixing instances"
221

    
222
  if instances:
223
    for iname in instances:
224
      if iname in missing:
225
        continue
226
      op = opcodes.OpActivateInstanceDisks(instance_name=iname)
227
      try:
228
        print "Activating disks for instance '%s'" % iname
229
        SubmitOpCode(op)
230
      except errors.GenericError, err:
231
        nret, msg = FormatError(err)
232
        retcode |= nret
233
        print >> sys.stderr, ("Error activating disks for instance %s: %s" %
234
                              (iname, msg))
235

    
236
  if missing:
237
    for iname, ival in missing.iteritems():
238
      all_missing = utils.all(ival, lambda x: x[0] in nlvm)
239
      if all_missing:
240
        print ("Instance %s cannot be verified as it lives on"
241
               " broken nodes" % iname)
242
      else:
243
        print "Instance %s has missing logical volumes:" % iname
244
        ival.sort()
245
        for node, vol in ival:
246
          if node in nlvm:
247
            print ("\tbroken node %s /dev/xenvg/%s" % (node, vol))
248
          else:
249
            print ("\t%s /dev/xenvg/%s" % (node, vol))
250
    print ("You need to run replace_disks for all the above"
251
           " instances, if this message persist after fixing nodes.")
252
    retcode |= 1
253

    
254
  return retcode
255

    
256

    
257
def MasterFailover(opts, args):
258
  """Failover the master node.
259

    
260
  This command, when run on a non-master node, will cause the current
261
  master to cease being master, and the non-master to become new
262
  master.
263

    
264
  """
265
  op = opcodes.OpMasterFailover()
266
  SubmitOpCode(op)
267

    
268

    
269
def SearchTags(opts, args):
270
  """Searches the tags on all the cluster.
271

    
272
  """
273
  op = opcodes.OpSearchTags(pattern=args[0])
274
  result = SubmitOpCode(op)
275
  if not result:
276
    return 1
277
  result = list(result)
278
  result.sort()
279
  for path, tag in result:
280
    print "%s %s" % (path, tag)
281

    
282

    
283
def SetClusterParams(opts, args):
284
  """Modify the cluster.
285

    
286
  Args:
287
    opts - class with options as members
288

    
289
  """
290
  if not (not opts.lvm_storage or opts.vg_name):
291
    print "Please give at least one of the parameters."
292
    return 1
293

    
294
  vg_name = opts.vg_name
295
  if not opts.lvm_storage and opts.vg_name:
296
    print ("Options --no-lvm-storage and --vg-name conflict.")
297
    return 1
298

    
299
  op = opcodes.OpSetClusterParams(vg_name=opts.vg_name)
300
  SubmitOpCode(op)
301
  return 0
302

    
303

    
304
# this is an option common to more than one command, so we declare
305
# it here and reuse it
306
node_option = make_option("-n", "--node", action="append", dest="nodes",
307
                          help="Node to copy to (if not given, all nodes),"
308
                               " can be given multiple times",
309
                          metavar="<node>", default=[])
310

    
311
commands = {
312
  'init': (InitCluster, ARGS_ONE,
313
           [DEBUG_OPT,
314
            make_option("-s", "--secondary-ip", dest="secondary_ip",
315
                        help="Specify the secondary ip for this node;"
316
                        " if given, the entire cluster must have secondary"
317
                        " addresses",
318
                        metavar="ADDRESS", default=None),
319
            make_option("-t", "--hypervisor-type", dest="hypervisor_type",
320
                        help="Specify the hypervisor type "
321
                        "(xen-3.0, fake, xen-hvm-3.1)",
322
                        metavar="TYPE", choices=["xen-3.0",
323
                                                 "fake",
324
                                                 "xen-hvm-3.1"],
325
                        default="xen-3.0",),
326
            make_option("-m", "--mac-prefix", dest="mac_prefix",
327
                        help="Specify the mac prefix for the instance IP"
328
                        " addresses, in the format XX:XX:XX",
329
                        metavar="PREFIX",
330
                        default="aa:00:00",),
331
            make_option("-g", "--vg-name", dest="vg_name",
332
                        help="Specify the volume group name "
333
                        " (cluster-wide) for disk allocation [xenvg]",
334
                        metavar="VG",
335
                        default=None,),
336
            make_option("-b", "--bridge", dest="def_bridge",
337
                        help="Specify the default bridge name (cluster-wide)"
338
                          " to connect the instances to [%s]" %
339
                          constants.DEFAULT_BRIDGE,
340
                        metavar="BRIDGE",
341
                        default=constants.DEFAULT_BRIDGE,),
342
            make_option("--master-netdev", dest="master_netdev",
343
                        help="Specify the node interface (cluster-wide)"
344
                          " on which the master IP address will be added "
345
                          " [%s]" % constants.DEFAULT_BRIDGE,
346
                        metavar="NETDEV",
347
                        default=constants.DEFAULT_BRIDGE,),
348
            make_option("--file-storage-dir", dest="file_storage_dir",
349
                        help="Specify the default directory (cluster-wide)"
350
                             " for storing the file-based disks [%s]" %
351
                             constants.DEFAULT_FILE_STORAGE_DIR,
352
                        metavar="DIR",
353
                        default=constants.DEFAULT_FILE_STORAGE_DIR,),
354
            make_option("--no-lvm-storage", dest="lvm_storage",
355
                        help="No support for lvm based instances"
356
                             " (cluster-wide)",
357
                        action="store_false", default=True,),
358
            ],
359
           "[opts...] <cluster_name>",
360
           "Initialises a new cluster configuration"),
361
  'destroy': (DestroyCluster, ARGS_NONE,
362
              [DEBUG_OPT,
363
               make_option("--yes-do-it", dest="yes_do_it",
364
                           help="Destroy cluster",
365
                           action="store_true"),
366
              ],
367
              "", "Destroy cluster"),
368
  'rename': (RenameCluster, ARGS_ONE, [DEBUG_OPT, FORCE_OPT],
369
               "<new_name>",
370
               "Renames the cluster"),
371
  'verify': (VerifyCluster, ARGS_NONE, [DEBUG_OPT],
372
             "", "Does a check on the cluster configuration"),
373
  'verify-disks': (VerifyDisks, ARGS_NONE, [DEBUG_OPT],
374
                   "", "Does a check on the cluster disk status"),
375
  'masterfailover': (MasterFailover, ARGS_NONE, [DEBUG_OPT],
376
                     "", "Makes the current node the master"),
377
  'version': (ShowClusterVersion, ARGS_NONE, [DEBUG_OPT],
378
              "", "Shows the cluster version"),
379
  'getmaster': (ShowClusterMaster, ARGS_NONE, [DEBUG_OPT],
380
                "", "Shows the cluster master"),
381
  'copyfile': (ClusterCopyFile, ARGS_ONE, [DEBUG_OPT, node_option],
382
               "[-n node...] <filename>",
383
               "Copies a file to all (or only some) nodes"),
384
  'command': (RunClusterCommand, ARGS_ATLEAST(1), [DEBUG_OPT, node_option],
385
              "[-n node...] <command>",
386
              "Runs a command on all (or only some) nodes"),
387
  'info': (ShowClusterConfig, ARGS_NONE, [DEBUG_OPT],
388
                 "", "Show cluster configuration"),
389
  'list-tags': (ListTags, ARGS_NONE,
390
                [DEBUG_OPT], "", "List the tags of the cluster"),
391
  'add-tags': (AddTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
392
               "tag...", "Add tags to the cluster"),
393
  'remove-tags': (RemoveTags, ARGS_ANY, [DEBUG_OPT, TAG_SRC_OPT],
394
                  "tag...", "Remove tags from the cluster"),
395
  'search-tags': (SearchTags, ARGS_ONE,
396
                  [DEBUG_OPT], "", "Searches the tags on all objects on"
397
                  " the cluster for a given pattern (regex)"),
398
  'modify': (SetClusterParams, ARGS_NONE,
399
             [DEBUG_OPT,
400
              make_option("-g", "--vg-name", dest="vg_name",
401
                          help="Specify the volume group name "
402
                          " (cluster-wide) for disk allocation "
403
                          "and enable lvm based storage",
404
                          metavar="VG",),
405
              make_option("--no-lvm-storage", dest="lvm_storage",
406
                          help="Disable support for lvm based instances"
407
                               " (cluster-wide)",
408
                          action="store_false", default=True,),
409
              ],
410
             "[opts...]",
411
             "Alters the parameters of the cluster"),
412
  }
413

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