Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_cluster.py @ fcad7225

History | View | Annotate | Download (42.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011 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
"""Cluster related commands"""
22

    
23
# pylint: disable-msg=W0401,W0613,W0614,C0103
24
# W0401: Wildcard import ganeti.cli
25
# W0613: Unused argument, since all functions follow the same API
26
# W0614: Unused import %s from wildcard import (since we need cli)
27
# C0103: Invalid name gnt-cluster
28

    
29
import os.path
30
import time
31
import OpenSSL
32
import itertools
33

    
34
from ganeti.cli import *
35
from ganeti import opcodes
36
from ganeti import constants
37
from ganeti import errors
38
from ganeti import utils
39
from ganeti import bootstrap
40
from ganeti import ssh
41
from ganeti import objects
42
from ganeti import uidpool
43
from ganeti import compat
44
from ganeti import netutils
45

    
46

    
47
ON_OPT = cli_option("--on", default=False,
48
                    action="store_true", dest="on",
49
                    help="Recover from an EPO")
50

    
51
GROUPS_OPT = cli_option("--groups", default=False,
52
                    action="store_true", dest="groups",
53
                    help="Arguments are node groups instead of nodes")
54

    
55
_EPO_PING_INTERVAL = 30 # 30 seconds between pings
56
_EPO_PING_TIMEOUT = 1 # 1 second
57
_EPO_REACHABLE_TIMEOUT = 15 * 60 # 15 minutes
58

    
59

    
60
@UsesRPC
61
def InitCluster(opts, args):
62
  """Initialize the cluster.
63

64
  @param opts: the command line options selected by the user
65
  @type args: list
66
  @param args: should contain only one element, the desired
67
      cluster name
68
  @rtype: int
69
  @return: the desired exit code
70

71
  """
72
  if not opts.lvm_storage and opts.vg_name:
73
    ToStderr("Options --no-lvm-storage and --vg-name conflict.")
74
    return 1
75

    
76
  vg_name = opts.vg_name
77
  if opts.lvm_storage and not opts.vg_name:
78
    vg_name = constants.DEFAULT_VG
79

    
80
  if not opts.drbd_storage and opts.drbd_helper:
81
    ToStderr("Options --no-drbd-storage and --drbd-usermode-helper conflict.")
82
    return 1
83

    
84
  drbd_helper = opts.drbd_helper
85
  if opts.drbd_storage and not opts.drbd_helper:
86
    drbd_helper = constants.DEFAULT_DRBD_HELPER
87

    
88
  master_netdev = opts.master_netdev
89
  if master_netdev is None:
90
    master_netdev = constants.DEFAULT_BRIDGE
91

    
92
  hvlist = opts.enabled_hypervisors
93
  if hvlist is None:
94
    hvlist = constants.DEFAULT_ENABLED_HYPERVISOR
95
  hvlist = hvlist.split(",")
96

    
97
  hvparams = dict(opts.hvparams)
98
  beparams = opts.beparams
99
  nicparams = opts.nicparams
100

    
101
  # prepare beparams dict
102
  beparams = objects.FillDict(constants.BEC_DEFAULTS, beparams)
103
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
104

    
105
  # prepare nicparams dict
106
  nicparams = objects.FillDict(constants.NICC_DEFAULTS, nicparams)
107
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
108

    
109
  # prepare ndparams dict
110
  if opts.ndparams is None:
111
    ndparams = dict(constants.NDC_DEFAULTS)
112
  else:
113
    ndparams = objects.FillDict(constants.NDC_DEFAULTS, opts.ndparams)
114
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
115

    
116
  # prepare hvparams dict
117
  for hv in constants.HYPER_TYPES:
118
    if hv not in hvparams:
119
      hvparams[hv] = {}
120
    hvparams[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], hvparams[hv])
121
    utils.ForceDictType(hvparams[hv], constants.HVS_PARAMETER_TYPES)
122

    
123
  if opts.candidate_pool_size is None:
124
    opts.candidate_pool_size = constants.MASTER_POOL_SIZE_DEFAULT
125

    
126
  if opts.mac_prefix is None:
127
    opts.mac_prefix = constants.DEFAULT_MAC_PREFIX
128

    
129
  uid_pool = opts.uid_pool
130
  if uid_pool is not None:
131
    uid_pool = uidpool.ParseUidPool(uid_pool)
132

    
133
  if opts.prealloc_wipe_disks is None:
134
    opts.prealloc_wipe_disks = False
135

    
136
  try:
137
    primary_ip_version = int(opts.primary_ip_version)
138
  except (ValueError, TypeError), err:
139
    ToStderr("Invalid primary ip version value: %s" % str(err))
140
    return 1
141

    
142
  bootstrap.InitCluster(cluster_name=args[0],
143
                        secondary_ip=opts.secondary_ip,
144
                        vg_name=vg_name,
145
                        mac_prefix=opts.mac_prefix,
146
                        master_netdev=master_netdev,
147
                        file_storage_dir=opts.file_storage_dir,
148
                        shared_file_storage_dir=opts.shared_file_storage_dir,
149
                        enabled_hypervisors=hvlist,
150
                        hvparams=hvparams,
151
                        beparams=beparams,
152
                        nicparams=nicparams,
153
                        ndparams=ndparams,
154
                        candidate_pool_size=opts.candidate_pool_size,
155
                        modify_etc_hosts=opts.modify_etc_hosts,
156
                        modify_ssh_setup=opts.modify_ssh_setup,
157
                        maintain_node_health=opts.maintain_node_health,
158
                        drbd_helper=drbd_helper,
159
                        uid_pool=uid_pool,
160
                        default_iallocator=opts.default_iallocator,
161
                        primary_ip_version=primary_ip_version,
162
                        prealloc_wipe_disks=opts.prealloc_wipe_disks,
163
                        )
164
  op = opcodes.OpClusterPostInit()
165
  SubmitOpCode(op, opts=opts)
166
  return 0
167

    
168

    
169
@UsesRPC
170
def DestroyCluster(opts, args):
171
  """Destroy the cluster.
172

173
  @param opts: the command line options selected by the user
174
  @type args: list
175
  @param args: should be an empty list
176
  @rtype: int
177
  @return: the desired exit code
178

179
  """
180
  if not opts.yes_do_it:
181
    ToStderr("Destroying a cluster is irreversible. If you really want"
182
             " destroy this cluster, supply the --yes-do-it option.")
183
    return 1
184

    
185
  op = opcodes.OpClusterDestroy()
186
  master = SubmitOpCode(op, opts=opts)
187
  # if we reached this, the opcode didn't fail; we can proceed to
188
  # shutdown all the daemons
189
  bootstrap.FinalizeClusterDestroy(master)
190
  return 0
191

    
192

    
193
def RenameCluster(opts, args):
194
  """Rename the cluster.
195

196
  @param opts: the command line options selected by the user
197
  @type args: list
198
  @param args: should contain only one element, the new cluster name
199
  @rtype: int
200
  @return: the desired exit code
201

202
  """
203
  cl = GetClient()
204

    
205
  (cluster_name, ) = cl.QueryConfigValues(["cluster_name"])
206

    
207
  new_name = args[0]
208
  if not opts.force:
209
    usertext = ("This will rename the cluster from '%s' to '%s'. If you are"
210
                " connected over the network to the cluster name, the"
211
                " operation is very dangerous as the IP address will be"
212
                " removed from the node and the change may not go through."
213
                " Continue?") % (cluster_name, new_name)
214
    if not AskUser(usertext):
215
      return 1
216

    
217
  op = opcodes.OpClusterRename(name=new_name)
218
  result = SubmitOpCode(op, opts=opts, cl=cl)
219

    
220
  if result:
221
    ToStdout("Cluster renamed from '%s' to '%s'", cluster_name, result)
222

    
223
  return 0
224

    
225

    
226
def RedistributeConfig(opts, args):
227
  """Forces push of the cluster configuration.
228

229
  @param opts: the command line options selected by the user
230
  @type args: list
231
  @param args: empty list
232
  @rtype: int
233
  @return: the desired exit code
234

235
  """
236
  op = opcodes.OpClusterRedistConf()
237
  SubmitOrSend(op, opts)
238
  return 0
239

    
240

    
241
def ShowClusterVersion(opts, args):
242
  """Write version of ganeti software to the standard output.
243

244
  @param opts: the command line options selected by the user
245
  @type args: list
246
  @param args: should be an empty list
247
  @rtype: int
248
  @return: the desired exit code
249

250
  """
251
  cl = GetClient()
252
  result = cl.QueryClusterInfo()
253
  ToStdout("Software version: %s", result["software_version"])
254
  ToStdout("Internode protocol: %s", result["protocol_version"])
255
  ToStdout("Configuration format: %s", result["config_version"])
256
  ToStdout("OS api version: %s", result["os_api_version"])
257
  ToStdout("Export interface: %s", result["export_version"])
258
  return 0
259

    
260

    
261
def ShowClusterMaster(opts, args):
262
  """Write name of master node to the standard output.
263

264
  @param opts: the command line options selected by the user
265
  @type args: list
266
  @param args: should be an empty list
267
  @rtype: int
268
  @return: the desired exit code
269

270
  """
271
  master = bootstrap.GetMaster()
272
  ToStdout(master)
273
  return 0
274

    
275

    
276
def _PrintGroupedParams(paramsdict, level=1, roman=False):
277
  """Print Grouped parameters (be, nic, disk) by group.
278

279
  @type paramsdict: dict of dicts
280
  @param paramsdict: {group: {param: value, ...}, ...}
281
  @type level: int
282
  @param level: Level of indention
283

284
  """
285
  indent = "  " * level
286
  for item, val in sorted(paramsdict.items()):
287
    if isinstance(val, dict):
288
      ToStdout("%s- %s:", indent, item)
289
      _PrintGroupedParams(val, level=level + 1, roman=roman)
290
    elif roman and isinstance(val, int):
291
      ToStdout("%s  %s: %s", indent, item, compat.TryToRoman(val))
292
    else:
293
      ToStdout("%s  %s: %s", indent, item, val)
294

    
295

    
296
def ShowClusterConfig(opts, args):
297
  """Shows cluster information.
298

299
  @param opts: the command line options selected by the user
300
  @type args: list
301
  @param args: should be an empty list
302
  @rtype: int
303
  @return: the desired exit code
304

305
  """
306
  cl = GetClient()
307
  result = cl.QueryClusterInfo()
308

    
309
  ToStdout("Cluster name: %s", result["name"])
310
  ToStdout("Cluster UUID: %s", result["uuid"])
311

    
312
  ToStdout("Creation time: %s", utils.FormatTime(result["ctime"]))
313
  ToStdout("Modification time: %s", utils.FormatTime(result["mtime"]))
314

    
315
  ToStdout("Master node: %s", result["master"])
316

    
317
  ToStdout("Architecture (this node): %s (%s)",
318
           result["architecture"][0], result["architecture"][1])
319

    
320
  if result["tags"]:
321
    tags = utils.CommaJoin(utils.NiceSort(result["tags"]))
322
  else:
323
    tags = "(none)"
324

    
325
  ToStdout("Tags: %s", tags)
326

    
327
  ToStdout("Default hypervisor: %s", result["default_hypervisor"])
328
  ToStdout("Enabled hypervisors: %s",
329
           utils.CommaJoin(result["enabled_hypervisors"]))
330

    
331
  ToStdout("Hypervisor parameters:")
332
  _PrintGroupedParams(result["hvparams"])
333

    
334
  ToStdout("OS-specific hypervisor parameters:")
335
  _PrintGroupedParams(result["os_hvp"])
336

    
337
  ToStdout("OS parameters:")
338
  _PrintGroupedParams(result["osparams"])
339

    
340
  ToStdout("Hidden OSes: %s", utils.CommaJoin(result["hidden_os"]))
341
  ToStdout("Blacklisted OSes: %s", utils.CommaJoin(result["blacklisted_os"]))
342

    
343
  ToStdout("Cluster parameters:")
344
  ToStdout("  - candidate pool size: %s",
345
            compat.TryToRoman(result["candidate_pool_size"],
346
                              convert=opts.roman_integers))
347
  ToStdout("  - master netdev: %s", result["master_netdev"])
348
  ToStdout("  - lvm volume group: %s", result["volume_group_name"])
349
  if result["reserved_lvs"]:
350
    reserved_lvs = utils.CommaJoin(result["reserved_lvs"])
351
  else:
352
    reserved_lvs = "(none)"
353
  ToStdout("  - lvm reserved volumes: %s", reserved_lvs)
354
  ToStdout("  - drbd usermode helper: %s", result["drbd_usermode_helper"])
355
  ToStdout("  - file storage path: %s", result["file_storage_dir"])
356
  ToStdout("  - shared file storage path: %s",
357
           result["shared_file_storage_dir"])
358
  ToStdout("  - maintenance of node health: %s",
359
           result["maintain_node_health"])
360
  ToStdout("  - uid pool: %s",
361
            uidpool.FormatUidPool(result["uid_pool"],
362
                                  roman=opts.roman_integers))
363
  ToStdout("  - default instance allocator: %s", result["default_iallocator"])
364
  ToStdout("  - primary ip version: %d", result["primary_ip_version"])
365
  ToStdout("  - preallocation wipe disks: %s", result["prealloc_wipe_disks"])
366
  ToStdout("  - OS search path: %s", utils.CommaJoin(constants.OS_SEARCH_PATH))
367

    
368
  ToStdout("Default node parameters:")
369
  _PrintGroupedParams(result["ndparams"], roman=opts.roman_integers)
370

    
371
  ToStdout("Default instance parameters:")
372
  _PrintGroupedParams(result["beparams"], roman=opts.roman_integers)
373

    
374
  ToStdout("Default nic parameters:")
375
  _PrintGroupedParams(result["nicparams"], roman=opts.roman_integers)
376

    
377
  return 0
378

    
379

    
380
def ClusterCopyFile(opts, args):
381
  """Copy a file from master to some nodes.
382

383
  @param opts: the command line options selected by the user
384
  @type args: list
385
  @param args: should contain only one element, the path of
386
      the file to be copied
387
  @rtype: int
388
  @return: the desired exit code
389

390
  """
391
  filename = args[0]
392
  if not os.path.exists(filename):
393
    raise errors.OpPrereqError("No such filename '%s'" % filename,
394
                               errors.ECODE_INVAL)
395

    
396
  cl = GetClient()
397

    
398
  cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
399

    
400
  results = GetOnlineNodes(nodes=opts.nodes, cl=cl, filter_master=True,
401
                           secondary_ips=opts.use_replication_network,
402
                           nodegroup=opts.nodegroup)
403

    
404
  srun = ssh.SshRunner(cluster_name=cluster_name)
405
  for node in results:
406
    if not srun.CopyFileToNode(node, filename):
407
      ToStderr("Copy of file %s to node %s failed", filename, node)
408

    
409
  return 0
410

    
411

    
412
def RunClusterCommand(opts, args):
413
  """Run a command on some nodes.
414

415
  @param opts: the command line options selected by the user
416
  @type args: list
417
  @param args: should contain the command to be run and its arguments
418
  @rtype: int
419
  @return: the desired exit code
420

421
  """
422
  cl = GetClient()
423

    
424
  command = " ".join(args)
425

    
426
  nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl, nodegroup=opts.nodegroup)
427

    
428
  cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
429
                                                    "master_node"])
430

    
431
  srun = ssh.SshRunner(cluster_name=cluster_name)
432

    
433
  # Make sure master node is at list end
434
  if master_node in nodes:
435
    nodes.remove(master_node)
436
    nodes.append(master_node)
437

    
438
  for name in nodes:
439
    result = srun.Run(name, "root", command)
440
    ToStdout("------------------------------------------------")
441
    ToStdout("node: %s", name)
442
    ToStdout("%s", result.output)
443
    ToStdout("return code = %s", result.exit_code)
444

    
445
  return 0
446

    
447

    
448
def VerifyCluster(opts, args):
449
  """Verify integrity of cluster, performing various test on nodes.
450

451
  @param opts: the command line options selected by the user
452
  @type args: list
453
  @param args: should be an empty list
454
  @rtype: int
455
  @return: the desired exit code
456

457
  """
458
  skip_checks = []
459

    
460
  if opts.skip_nplusone_mem:
461
    skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
462

    
463
  cl = GetClient()
464

    
465
  op = opcodes.OpClusterVerify(verbose=opts.verbose,
466
                               error_codes=opts.error_codes,
467
                               debug_simulate_errors=opts.simulate_errors,
468
                               skip_checks=skip_checks,
469
                               group_name=opts.nodegroup)
470
  result = SubmitOpCode(op, cl=cl, opts=opts)
471

    
472
  # Keep track of submitted jobs
473
  jex = JobExecutor(cl=cl, opts=opts)
474

    
475
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
476
    jex.AddJobId(None, status, job_id)
477

    
478
  results = jex.GetResults()
479
  bad_cnt = len([row for row in results if not row[0]])
480
  if bad_cnt == 0:
481
    rcode = constants.EXIT_SUCCESS
482
  else:
483
    ToStdout("%s job(s) failed while verifying the cluster.", bad_cnt)
484
    rcode = constants.EXIT_FAILURE
485

    
486
  return rcode
487

    
488

    
489
def VerifyDisks(opts, args):
490
  """Verify integrity of cluster disks.
491

492
  @param opts: the command line options selected by the user
493
  @type args: list
494
  @param args: should be an empty list
495
  @rtype: int
496
  @return: the desired exit code
497

498
  """
499
  cl = GetClient()
500

    
501
  op = opcodes.OpClusterVerifyDisks()
502

    
503
  result = SubmitOpCode(op, cl=cl, opts=opts)
504

    
505
  # Keep track of submitted jobs
506
  jex = JobExecutor(cl=cl, opts=opts)
507

    
508
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
509
    jex.AddJobId(None, status, job_id)
510

    
511
  retcode = constants.EXIT_SUCCESS
512

    
513
  for (status, result) in jex.GetResults():
514
    if not status:
515
      ToStdout("Job failed: %s", result)
516
      continue
517

    
518
    ((bad_nodes, instances, missing), ) = result
519

    
520
    for node, text in bad_nodes.items():
521
      ToStdout("Error gathering data on node %s: %s",
522
               node, utils.SafeEncode(text[-400:]))
523
      retcode = constants.EXIT_FAILURE
524
      ToStdout("You need to fix these nodes first before fixing instances")
525

    
526
    for iname in instances:
527
      if iname in missing:
528
        continue
529
      op = opcodes.OpInstanceActivateDisks(instance_name=iname)
530
      try:
531
        ToStdout("Activating disks for instance '%s'", iname)
532
        SubmitOpCode(op, opts=opts, cl=cl)
533
      except errors.GenericError, err:
534
        nret, msg = FormatError(err)
535
        retcode |= nret
536
        ToStderr("Error activating disks for instance %s: %s", iname, msg)
537

    
538
    if missing:
539
      for iname, ival in missing.iteritems():
540
        all_missing = compat.all(x[0] in bad_nodes for x in ival)
541
        if all_missing:
542
          ToStdout("Instance %s cannot be verified as it lives on"
543
                   " broken nodes", iname)
544
        else:
545
          ToStdout("Instance %s has missing logical volumes:", iname)
546
          ival.sort()
547
          for node, vol in ival:
548
            if node in bad_nodes:
549
              ToStdout("\tbroken node %s /dev/%s", node, vol)
550
            else:
551
              ToStdout("\t%s /dev/%s", node, vol)
552

    
553
      ToStdout("You need to replace or recreate disks for all the above"
554
               " instances if this message persists after fixing broken nodes.")
555
      retcode = constants.EXIT_FAILURE
556

    
557
  return retcode
558

    
559

    
560
def RepairDiskSizes(opts, args):
561
  """Verify sizes of cluster disks.
562

563
  @param opts: the command line options selected by the user
564
  @type args: list
565
  @param args: optional list of instances to restrict check to
566
  @rtype: int
567
  @return: the desired exit code
568

569
  """
570
  op = opcodes.OpClusterRepairDiskSizes(instances=args)
571
  SubmitOpCode(op, opts=opts)
572

    
573

    
574
@UsesRPC
575
def MasterFailover(opts, args):
576
  """Failover the master node.
577

578
  This command, when run on a non-master node, will cause the current
579
  master to cease being master, and the non-master to become new
580
  master.
581

582
  @param opts: the command line options selected by the user
583
  @type args: list
584
  @param args: should be an empty list
585
  @rtype: int
586
  @return: the desired exit code
587

588
  """
589
  if opts.no_voting:
590
    usertext = ("This will perform the failover even if most other nodes"
591
                " are down, or if this node is outdated. This is dangerous"
592
                " as it can lead to a non-consistent cluster. Check the"
593
                " gnt-cluster(8) man page before proceeding. Continue?")
594
    if not AskUser(usertext):
595
      return 1
596

    
597
  return bootstrap.MasterFailover(no_voting=opts.no_voting)
598

    
599

    
600
def MasterPing(opts, args):
601
  """Checks if the master is alive.
602

603
  @param opts: the command line options selected by the user
604
  @type args: list
605
  @param args: should be an empty list
606
  @rtype: int
607
  @return: the desired exit code
608

609
  """
610
  try:
611
    cl = GetClient()
612
    cl.QueryClusterInfo()
613
    return 0
614
  except Exception: # pylint: disable-msg=W0703
615
    return 1
616

    
617

    
618
def SearchTags(opts, args):
619
  """Searches the tags on all the cluster.
620

621
  @param opts: the command line options selected by the user
622
  @type args: list
623
  @param args: should contain only one element, the tag pattern
624
  @rtype: int
625
  @return: the desired exit code
626

627
  """
628
  op = opcodes.OpTagsSearch(pattern=args[0])
629
  result = SubmitOpCode(op, opts=opts)
630
  if not result:
631
    return 1
632
  result = list(result)
633
  result.sort()
634
  for path, tag in result:
635
    ToStdout("%s %s", path, tag)
636

    
637

    
638
def _RenewCrypto(new_cluster_cert, new_rapi_cert, rapi_cert_filename,
639
                 new_confd_hmac_key, new_cds, cds_filename,
640
                 force):
641
  """Renews cluster certificates, keys and secrets.
642

643
  @type new_cluster_cert: bool
644
  @param new_cluster_cert: Whether to generate a new cluster certificate
645
  @type new_rapi_cert: bool
646
  @param new_rapi_cert: Whether to generate a new RAPI certificate
647
  @type rapi_cert_filename: string
648
  @param rapi_cert_filename: Path to file containing new RAPI certificate
649
  @type new_confd_hmac_key: bool
650
  @param new_confd_hmac_key: Whether to generate a new HMAC key
651
  @type new_cds: bool
652
  @param new_cds: Whether to generate a new cluster domain secret
653
  @type cds_filename: string
654
  @param cds_filename: Path to file containing new cluster domain secret
655
  @type force: bool
656
  @param force: Whether to ask user for confirmation
657

658
  """
659
  if new_rapi_cert and rapi_cert_filename:
660
    ToStderr("Only one of the --new-rapi-certficate and --rapi-certificate"
661
             " options can be specified at the same time.")
662
    return 1
663

    
664
  if new_cds and cds_filename:
665
    ToStderr("Only one of the --new-cluster-domain-secret and"
666
             " --cluster-domain-secret options can be specified at"
667
             " the same time.")
668
    return 1
669

    
670
  if rapi_cert_filename:
671
    # Read and verify new certificate
672
    try:
673
      rapi_cert_pem = utils.ReadFile(rapi_cert_filename)
674

    
675
      OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
676
                                      rapi_cert_pem)
677
    except Exception, err: # pylint: disable-msg=W0703
678
      ToStderr("Can't load new RAPI certificate from %s: %s" %
679
               (rapi_cert_filename, str(err)))
680
      return 1
681

    
682
    try:
683
      OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, rapi_cert_pem)
684
    except Exception, err: # pylint: disable-msg=W0703
685
      ToStderr("Can't load new RAPI private key from %s: %s" %
686
               (rapi_cert_filename, str(err)))
687
      return 1
688

    
689
  else:
690
    rapi_cert_pem = None
691

    
692
  if cds_filename:
693
    try:
694
      cds = utils.ReadFile(cds_filename)
695
    except Exception, err: # pylint: disable-msg=W0703
696
      ToStderr("Can't load new cluster domain secret from %s: %s" %
697
               (cds_filename, str(err)))
698
      return 1
699
  else:
700
    cds = None
701

    
702
  if not force:
703
    usertext = ("This requires all daemons on all nodes to be restarted and"
704
                " may take some time. Continue?")
705
    if not AskUser(usertext):
706
      return 1
707

    
708
  def _RenewCryptoInner(ctx):
709
    ctx.feedback_fn("Updating certificates and keys")
710
    bootstrap.GenerateClusterCrypto(new_cluster_cert, new_rapi_cert,
711
                                    new_confd_hmac_key,
712
                                    new_cds,
713
                                    rapi_cert_pem=rapi_cert_pem,
714
                                    cds=cds)
715

    
716
    files_to_copy = []
717

    
718
    if new_cluster_cert:
719
      files_to_copy.append(constants.NODED_CERT_FILE)
720

    
721
    if new_rapi_cert or rapi_cert_pem:
722
      files_to_copy.append(constants.RAPI_CERT_FILE)
723

    
724
    if new_confd_hmac_key:
725
      files_to_copy.append(constants.CONFD_HMAC_KEY)
726

    
727
    if new_cds or cds:
728
      files_to_copy.append(constants.CLUSTER_DOMAIN_SECRET_FILE)
729

    
730
    if files_to_copy:
731
      for node_name in ctx.nonmaster_nodes:
732
        ctx.feedback_fn("Copying %s to %s" %
733
                        (", ".join(files_to_copy), node_name))
734
        for file_name in files_to_copy:
735
          ctx.ssh.CopyFileToNode(node_name, file_name)
736

    
737
  RunWhileClusterStopped(ToStdout, _RenewCryptoInner)
738

    
739
  ToStdout("All requested certificates and keys have been replaced."
740
           " Running \"gnt-cluster verify\" now is recommended.")
741

    
742
  return 0
743

    
744

    
745
def RenewCrypto(opts, args):
746
  """Renews cluster certificates, keys and secrets.
747

748
  """
749
  return _RenewCrypto(opts.new_cluster_cert,
750
                      opts.new_rapi_cert,
751
                      opts.rapi_cert,
752
                      opts.new_confd_hmac_key,
753
                      opts.new_cluster_domain_secret,
754
                      opts.cluster_domain_secret,
755
                      opts.force)
756

    
757

    
758
def SetClusterParams(opts, args):
759
  """Modify the cluster.
760

761
  @param opts: the command line options selected by the user
762
  @type args: list
763
  @param args: should be an empty list
764
  @rtype: int
765
  @return: the desired exit code
766

767
  """
768
  if not (not opts.lvm_storage or opts.vg_name or
769
          not opts.drbd_storage or opts.drbd_helper or
770
          opts.enabled_hypervisors or opts.hvparams or
771
          opts.beparams or opts.nicparams or opts.ndparams or
772
          opts.candidate_pool_size is not None or
773
          opts.uid_pool is not None or
774
          opts.maintain_node_health is not None or
775
          opts.add_uids is not None or
776
          opts.remove_uids is not None or
777
          opts.default_iallocator is not None or
778
          opts.reserved_lvs is not None or
779
          opts.master_netdev is not None or
780
          opts.prealloc_wipe_disks is not None):
781
    ToStderr("Please give at least one of the parameters.")
782
    return 1
783

    
784
  vg_name = opts.vg_name
785
  if not opts.lvm_storage and opts.vg_name:
786
    ToStderr("Options --no-lvm-storage and --vg-name conflict.")
787
    return 1
788

    
789
  if not opts.lvm_storage:
790
    vg_name = ""
791

    
792
  drbd_helper = opts.drbd_helper
793
  if not opts.drbd_storage and opts.drbd_helper:
794
    ToStderr("Options --no-drbd-storage and --drbd-usermode-helper conflict.")
795
    return 1
796

    
797
  if not opts.drbd_storage:
798
    drbd_helper = ""
799

    
800
  hvlist = opts.enabled_hypervisors
801
  if hvlist is not None:
802
    hvlist = hvlist.split(",")
803

    
804
  # a list of (name, dict) we can pass directly to dict() (or [])
805
  hvparams = dict(opts.hvparams)
806
  for hv_params in hvparams.values():
807
    utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
808

    
809
  beparams = opts.beparams
810
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
811

    
812
  nicparams = opts.nicparams
813
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
814

    
815
  ndparams = opts.ndparams
816
  if ndparams is not None:
817
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
818

    
819
  mnh = opts.maintain_node_health
820

    
821
  uid_pool = opts.uid_pool
822
  if uid_pool is not None:
823
    uid_pool = uidpool.ParseUidPool(uid_pool)
824

    
825
  add_uids = opts.add_uids
826
  if add_uids is not None:
827
    add_uids = uidpool.ParseUidPool(add_uids)
828

    
829
  remove_uids = opts.remove_uids
830
  if remove_uids is not None:
831
    remove_uids = uidpool.ParseUidPool(remove_uids)
832

    
833
  if opts.reserved_lvs is not None:
834
    if opts.reserved_lvs == "":
835
      opts.reserved_lvs = []
836
    else:
837
      opts.reserved_lvs = utils.UnescapeAndSplit(opts.reserved_lvs, sep=",")
838

    
839
  op = opcodes.OpClusterSetParams(vg_name=vg_name,
840
                                  drbd_helper=drbd_helper,
841
                                  enabled_hypervisors=hvlist,
842
                                  hvparams=hvparams,
843
                                  os_hvp=None,
844
                                  beparams=beparams,
845
                                  nicparams=nicparams,
846
                                  ndparams=ndparams,
847
                                  candidate_pool_size=opts.candidate_pool_size,
848
                                  maintain_node_health=mnh,
849
                                  uid_pool=uid_pool,
850
                                  add_uids=add_uids,
851
                                  remove_uids=remove_uids,
852
                                  default_iallocator=opts.default_iallocator,
853
                                  prealloc_wipe_disks=opts.prealloc_wipe_disks,
854
                                  master_netdev=opts.master_netdev,
855
                                  reserved_lvs=opts.reserved_lvs)
856
  SubmitOpCode(op, opts=opts)
857
  return 0
858

    
859

    
860
def QueueOps(opts, args):
861
  """Queue operations.
862

863
  @param opts: the command line options selected by the user
864
  @type args: list
865
  @param args: should contain only one element, the subcommand
866
  @rtype: int
867
  @return: the desired exit code
868

869
  """
870
  command = args[0]
871
  client = GetClient()
872
  if command in ("drain", "undrain"):
873
    drain_flag = command == "drain"
874
    client.SetQueueDrainFlag(drain_flag)
875
  elif command == "info":
876
    result = client.QueryConfigValues(["drain_flag"])
877
    if result[0]:
878
      val = "set"
879
    else:
880
      val = "unset"
881
    ToStdout("The drain flag is %s" % val)
882
  else:
883
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
884
                               errors.ECODE_INVAL)
885

    
886
  return 0
887

    
888

    
889
def _ShowWatcherPause(until):
890
  if until is None or until < time.time():
891
    ToStdout("The watcher is not paused.")
892
  else:
893
    ToStdout("The watcher is paused until %s.", time.ctime(until))
894

    
895

    
896
def WatcherOps(opts, args):
897
  """Watcher operations.
898

899
  @param opts: the command line options selected by the user
900
  @type args: list
901
  @param args: should contain only one element, the subcommand
902
  @rtype: int
903
  @return: the desired exit code
904

905
  """
906
  command = args[0]
907
  client = GetClient()
908

    
909
  if command == "continue":
910
    client.SetWatcherPause(None)
911
    ToStdout("The watcher is no longer paused.")
912

    
913
  elif command == "pause":
914
    if len(args) < 2:
915
      raise errors.OpPrereqError("Missing pause duration", errors.ECODE_INVAL)
916

    
917
    result = client.SetWatcherPause(time.time() + ParseTimespec(args[1]))
918
    _ShowWatcherPause(result)
919

    
920
  elif command == "info":
921
    result = client.QueryConfigValues(["watcher_pause"])
922
    _ShowWatcherPause(result[0])
923

    
924
  else:
925
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
926
                               errors.ECODE_INVAL)
927

    
928
  return 0
929

    
930

    
931
def _OobPower(opts, node_list, power):
932
  """Puts the node in the list to desired power state.
933

934
  @param opts: The command line options selected by the user
935
  @param node_list: The list of nodes to operate on
936
  @param power: True if they should be powered on, False otherwise
937
  @return: The success of the operation (none failed)
938

939
  """
940
  if power:
941
    command = constants.OOB_POWER_ON
942
  else:
943
    command = constants.OOB_POWER_OFF
944

    
945
  op = opcodes.OpOobCommand(node_names=node_list,
946
                            command=command,
947
                            ignore_status=True,
948
                            timeout=opts.oob_timeout,
949
                            power_delay=opts.power_delay)
950
  result = SubmitOpCode(op, opts=opts)
951
  errs = 0
952
  for node_result in result:
953
    (node_tuple, data_tuple) = node_result
954
    (_, node_name) = node_tuple
955
    (data_status, _) = data_tuple
956
    if data_status != constants.RS_NORMAL:
957
      assert data_status != constants.RS_UNAVAIL
958
      errs += 1
959
      ToStderr("There was a problem changing power for %s, please investigate",
960
               node_name)
961

    
962
  if errs > 0:
963
    return False
964

    
965
  return True
966

    
967

    
968
def _InstanceStart(opts, inst_list, start):
969
  """Puts the instances in the list to desired state.
970

971
  @param opts: The command line options selected by the user
972
  @param inst_list: The list of instances to operate on
973
  @param start: True if they should be started, False for shutdown
974
  @return: The success of the operation (none failed)
975

976
  """
977
  if start:
978
    opcls = opcodes.OpInstanceStartup
979
    text_submit, text_success, text_failed = ("startup", "started", "starting")
980
  else:
981
    opcls = compat.partial(opcodes.OpInstanceShutdown,
982
                           timeout=opts.shutdown_timeout)
983
    text_submit, text_success, text_failed = ("shutdown", "stopped", "stopping")
984

    
985
  jex = JobExecutor(opts=opts)
986

    
987
  for inst in inst_list:
988
    ToStdout("Submit %s of instance %s", text_submit, inst)
989
    op = opcls(instance_name=inst)
990
    jex.QueueJob(inst, op)
991

    
992
  results = jex.GetResults()
993
  bad_cnt = len([1 for (success, _) in results if not success])
994

    
995
  if bad_cnt == 0:
996
    ToStdout("All instances have been %s successfully", text_success)
997
  else:
998
    ToStderr("There were errors while %s instances:\n"
999
             "%d error(s) out of %d instance(s)", text_failed, bad_cnt,
1000
             len(results))
1001
    return False
1002

    
1003
  return True
1004

    
1005

    
1006
class _RunWhenNodesReachableHelper:
1007
  """Helper class to make shared internal state sharing easier.
1008

1009
  @ivar success: Indicates if all action_cb calls were successful
1010

1011
  """
1012
  def __init__(self, node_list, action_cb, node2ip, port, feedback_fn,
1013
               _ping_fn=netutils.TcpPing, _sleep_fn=time.sleep):
1014
    """Init the object.
1015

1016
    @param node_list: The list of nodes to be reachable
1017
    @param action_cb: Callback called when a new host is reachable
1018
    @type node2ip: dict
1019
    @param node2ip: Node to ip mapping
1020
    @param port: The port to use for the TCP ping
1021
    @param feedback_fn: The function used for feedback
1022
    @param _ping_fn: Function to check reachabilty (for unittest use only)
1023
    @param _sleep_fn: Function to sleep (for unittest use only)
1024

1025
    """
1026
    self.down = set(node_list)
1027
    self.up = set()
1028
    self.node2ip = node2ip
1029
    self.success = True
1030
    self.action_cb = action_cb
1031
    self.port = port
1032
    self.feedback_fn = feedback_fn
1033
    self._ping_fn = _ping_fn
1034
    self._sleep_fn = _sleep_fn
1035

    
1036
  def __call__(self):
1037
    """When called we run action_cb.
1038

1039
    @raises utils.RetryAgain: When there are still down nodes
1040

1041
    """
1042
    if not self.action_cb(self.up):
1043
      self.success = False
1044

    
1045
    if self.down:
1046
      raise utils.RetryAgain()
1047
    else:
1048
      return self.success
1049

    
1050
  def Wait(self, secs):
1051
    """Checks if a host is up or waits remaining seconds.
1052

1053
    @param secs: The secs remaining
1054

1055
    """
1056
    start = time.time()
1057
    for node in self.down:
1058
      if self._ping_fn(self.node2ip[node], self.port, timeout=_EPO_PING_TIMEOUT,
1059
                       live_port_needed=True):
1060
        self.feedback_fn("Node %s became available" % node)
1061
        self.up.add(node)
1062
        self.down -= self.up
1063
        # If we have a node available there is the possibility to run the
1064
        # action callback successfully, therefore we don't wait and return
1065
        return
1066

    
1067
    self._sleep_fn(max(0.0, start + secs - time.time()))
1068

    
1069

    
1070
def _RunWhenNodesReachable(node_list, action_cb, interval):
1071
  """Run action_cb when nodes become reachable.
1072

1073
  @param node_list: The list of nodes to be reachable
1074
  @param action_cb: Callback called when a new host is reachable
1075
  @param interval: The earliest time to retry
1076

1077
  """
1078
  client = GetClient()
1079
  cluster_info = client.QueryClusterInfo()
1080
  if cluster_info["primary_ip_version"] == constants.IP4_VERSION:
1081
    family = netutils.IPAddress.family
1082
  else:
1083
    family = netutils.IP6Address.family
1084

    
1085
  node2ip = dict((node, netutils.GetHostname(node, family=family).ip)
1086
                 for node in node_list)
1087

    
1088
  port = netutils.GetDaemonPort(constants.NODED)
1089
  helper = _RunWhenNodesReachableHelper(node_list, action_cb, node2ip, port,
1090
                                        ToStdout)
1091

    
1092
  try:
1093
    return utils.Retry(helper, interval, _EPO_REACHABLE_TIMEOUT,
1094
                       wait_fn=helper.Wait)
1095
  except utils.RetryTimeout:
1096
    ToStderr("Time exceeded while waiting for nodes to become reachable"
1097
             " again:\n  - %s", "  - ".join(helper.down))
1098
    return False
1099

    
1100

    
1101
def _MaybeInstanceStartup(opts, inst_map, nodes_online,
1102
                          _instance_start_fn=_InstanceStart):
1103
  """Start the instances conditional based on node_states.
1104

1105
  @param opts: The command line options selected by the user
1106
  @param inst_map: A dict of inst -> nodes mapping
1107
  @param nodes_online: A list of nodes online
1108
  @param _instance_start_fn: Callback to start instances (unittest use only)
1109
  @return: Success of the operation on all instances
1110

1111
  """
1112
  start_inst_list = []
1113
  for (inst, nodes) in inst_map.items():
1114
    if not (nodes - nodes_online):
1115
      # All nodes the instance lives on are back online
1116
      start_inst_list.append(inst)
1117

    
1118
  for inst in start_inst_list:
1119
    del inst_map[inst]
1120

    
1121
  if start_inst_list:
1122
    return _instance_start_fn(opts, start_inst_list, True)
1123

    
1124
  return True
1125

    
1126

    
1127
def _EpoOn(opts, full_node_list, node_list, inst_map):
1128
  """Does the actual power on.
1129

1130
  @param opts: The command line options selected by the user
1131
  @param full_node_list: All nodes to operate on (includes nodes not supporting
1132
                         OOB)
1133
  @param node_list: The list of nodes to operate on (all need to support OOB)
1134
  @param inst_map: A dict of inst -> nodes mapping
1135
  @return: The desired exit status
1136

1137
  """
1138
  if node_list and not _OobPower(opts, node_list, False):
1139
    ToStderr("Not all nodes seem to get back up, investigate and start"
1140
             " manually if needed")
1141

    
1142
  # Wait for the nodes to be back up
1143
  action_cb = compat.partial(_MaybeInstanceStartup, opts, dict(inst_map))
1144

    
1145
  ToStdout("Waiting until all nodes are available again")
1146
  if not _RunWhenNodesReachable(full_node_list, action_cb, _EPO_PING_INTERVAL):
1147
    ToStderr("Please investigate and start stopped instances manually")
1148
    return constants.EXIT_FAILURE
1149

    
1150
  return constants.EXIT_SUCCESS
1151

    
1152

    
1153
def _EpoOff(opts, node_list, inst_map):
1154
  """Does the actual power off.
1155

1156
  @param opts: The command line options selected by the user
1157
  @param node_list: The list of nodes to operate on (all need to support OOB)
1158
  @param inst_map: A dict of inst -> nodes mapping
1159
  @return: The desired exit status
1160

1161
  """
1162
  if not _InstanceStart(opts, inst_map.keys(), False):
1163
    ToStderr("Please investigate and stop instances manually before continuing")
1164
    return constants.EXIT_FAILURE
1165

    
1166
  if not node_list:
1167
    return constants.EXIT_SUCCESS
1168

    
1169
  if _OobPower(opts, node_list, False):
1170
    return constants.EXIT_SUCCESS
1171
  else:
1172
    return constants.EXIT_FAILURE
1173

    
1174

    
1175
def Epo(opts, args):
1176
  """EPO operations.
1177

1178
  @param opts: the command line options selected by the user
1179
  @type args: list
1180
  @param args: should contain only one element, the subcommand
1181
  @rtype: int
1182
  @return: the desired exit code
1183

1184
  """
1185
  if opts.groups and opts.show_all:
1186
    ToStderr("Only one of --groups or --all are allowed")
1187
    return constants.EXIT_FAILURE
1188
  elif args and opts.show_all:
1189
    ToStderr("Arguments in combination with --all are not allowed")
1190
    return constants.EXIT_FAILURE
1191

    
1192
  client = GetClient()
1193

    
1194
  if opts.groups:
1195
    node_query_list = itertools.chain(*client.QueryGroups(names=args,
1196
                                                          fields=["node_list"],
1197
                                                          use_locking=False))
1198
  else:
1199
    node_query_list = args
1200

    
1201
  result = client.QueryNodes(names=node_query_list,
1202
                             fields=["name", "master", "pinst_list",
1203
                                     "sinst_list", "powered", "offline"],
1204
                             use_locking=False)
1205
  node_list = []
1206
  inst_map = {}
1207
  for (idx, (node, master, pinsts, sinsts, powered,
1208
             offline)) in enumerate(result):
1209
    # Normalize the node_query_list as well
1210
    if not opts.show_all:
1211
      node_query_list[idx] = node
1212
    if not offline:
1213
      for inst in (pinsts + sinsts):
1214
        if inst in inst_map:
1215
          if not master:
1216
            inst_map[inst].add(node)
1217
        elif master:
1218
          inst_map[inst] = set()
1219
        else:
1220
          inst_map[inst] = set([node])
1221

    
1222
    if master and opts.on:
1223
      # We ignore the master for turning on the machines, in fact we are
1224
      # already operating on the master at this point :)
1225
      continue
1226
    elif master and not opts.show_all:
1227
      ToStderr("%s is the master node, please do a master-failover to another"
1228
               " node not affected by the EPO or use --all if you intend to"
1229
               " shutdown the whole cluster", node)
1230
      return constants.EXIT_FAILURE
1231
    elif powered is None:
1232
      ToStdout("Node %s does not support out-of-band handling, it can not be"
1233
               " handled in a fully automated manner", node)
1234
    elif powered == opts.on:
1235
      ToStdout("Node %s is already in desired power state, skipping", node)
1236
    elif not offline or (offline and powered):
1237
      node_list.append(node)
1238

    
1239
  if not opts.force and not ConfirmOperation(node_query_list, "nodes", "epo"):
1240
    return constants.EXIT_FAILURE
1241

    
1242
  if opts.on:
1243
    return _EpoOn(opts, node_query_list, node_list, inst_map)
1244
  else:
1245
    return _EpoOff(opts, node_list, inst_map)
1246

    
1247

    
1248
commands = {
1249
  "init": (
1250
    InitCluster, [ArgHost(min=1, max=1)],
1251
    [BACKEND_OPT, CP_SIZE_OPT, ENABLED_HV_OPT, GLOBAL_FILEDIR_OPT,
1252
     HVLIST_OPT, MAC_PREFIX_OPT, MASTER_NETDEV_OPT, NIC_PARAMS_OPT,
1253
     NOLVM_STORAGE_OPT, NOMODIFY_ETCHOSTS_OPT, NOMODIFY_SSH_SETUP_OPT,
1254
     SECONDARY_IP_OPT, VG_NAME_OPT, MAINTAIN_NODE_HEALTH_OPT,
1255
     UIDPOOL_OPT, DRBD_HELPER_OPT, NODRBD_STORAGE_OPT,
1256
     DEFAULT_IALLOCATOR_OPT, PRIMARY_IP_VERSION_OPT, PREALLOC_WIPE_DISKS_OPT,
1257
     NODE_PARAMS_OPT, GLOBAL_SHARED_FILEDIR_OPT],
1258
    "[opts...] <cluster_name>", "Initialises a new cluster configuration"),
1259
  "destroy": (
1260
    DestroyCluster, ARGS_NONE, [YES_DOIT_OPT],
1261
    "", "Destroy cluster"),
1262
  "rename": (
1263
    RenameCluster, [ArgHost(min=1, max=1)],
1264
    [FORCE_OPT, DRY_RUN_OPT],
1265
    "<new_name>",
1266
    "Renames the cluster"),
1267
  "redist-conf": (
1268
    RedistributeConfig, ARGS_NONE, [SUBMIT_OPT, DRY_RUN_OPT, PRIORITY_OPT],
1269
    "", "Forces a push of the configuration file and ssconf files"
1270
    " to the nodes in the cluster"),
1271
  "verify": (
1272
    VerifyCluster, ARGS_NONE,
1273
    [VERBOSE_OPT, DEBUG_SIMERR_OPT, ERROR_CODES_OPT, NONPLUS1_OPT,
1274
     DRY_RUN_OPT, PRIORITY_OPT, NODEGROUP_OPT],
1275
    "", "Does a check on the cluster configuration"),
1276
  "verify-disks": (
1277
    VerifyDisks, ARGS_NONE, [PRIORITY_OPT],
1278
    "", "Does a check on the cluster disk status"),
1279
  "repair-disk-sizes": (
1280
    RepairDiskSizes, ARGS_MANY_INSTANCES, [DRY_RUN_OPT, PRIORITY_OPT],
1281
    "", "Updates mismatches in recorded disk sizes"),
1282
  "master-failover": (
1283
    MasterFailover, ARGS_NONE, [NOVOTING_OPT],
1284
    "", "Makes the current node the master"),
1285
  "master-ping": (
1286
    MasterPing, ARGS_NONE, [],
1287
    "", "Checks if the master is alive"),
1288
  "version": (
1289
    ShowClusterVersion, ARGS_NONE, [],
1290
    "", "Shows the cluster version"),
1291
  "getmaster": (
1292
    ShowClusterMaster, ARGS_NONE, [],
1293
    "", "Shows the cluster master"),
1294
  "copyfile": (
1295
    ClusterCopyFile, [ArgFile(min=1, max=1)],
1296
    [NODE_LIST_OPT, USE_REPL_NET_OPT, NODEGROUP_OPT],
1297
    "[-n node...] <filename>", "Copies a file to all (or only some) nodes"),
1298
  "command": (
1299
    RunClusterCommand, [ArgCommand(min=1)],
1300
    [NODE_LIST_OPT, NODEGROUP_OPT],
1301
    "[-n node...] <command>", "Runs a command on all (or only some) nodes"),
1302
  "info": (
1303
    ShowClusterConfig, ARGS_NONE, [ROMAN_OPT],
1304
    "[--roman]", "Show cluster configuration"),
1305
  "list-tags": (
1306
    ListTags, ARGS_NONE, [], "", "List the tags of the cluster"),
1307
  "add-tags": (
1308
    AddTags, [ArgUnknown()], [TAG_SRC_OPT, PRIORITY_OPT],
1309
    "tag...", "Add tags to the cluster"),
1310
  "remove-tags": (
1311
    RemoveTags, [ArgUnknown()], [TAG_SRC_OPT, PRIORITY_OPT],
1312
    "tag...", "Remove tags from the cluster"),
1313
  "search-tags": (
1314
    SearchTags, [ArgUnknown(min=1, max=1)], [PRIORITY_OPT], "",
1315
    "Searches the tags on all objects on"
1316
    " the cluster for a given pattern (regex)"),
1317
  "queue": (
1318
    QueueOps,
1319
    [ArgChoice(min=1, max=1, choices=["drain", "undrain", "info"])],
1320
    [], "drain|undrain|info", "Change queue properties"),
1321
  "watcher": (
1322
    WatcherOps,
1323
    [ArgChoice(min=1, max=1, choices=["pause", "continue", "info"]),
1324
     ArgSuggest(min=0, max=1, choices=["30m", "1h", "4h"])],
1325
    [],
1326
    "{pause <timespec>|continue|info}", "Change watcher properties"),
1327
  "modify": (
1328
    SetClusterParams, ARGS_NONE,
1329
    [BACKEND_OPT, CP_SIZE_OPT, ENABLED_HV_OPT, HVLIST_OPT, MASTER_NETDEV_OPT,
1330
     NIC_PARAMS_OPT, NOLVM_STORAGE_OPT, VG_NAME_OPT, MAINTAIN_NODE_HEALTH_OPT,
1331
     UIDPOOL_OPT, ADD_UIDS_OPT, REMOVE_UIDS_OPT, DRBD_HELPER_OPT,
1332
     NODRBD_STORAGE_OPT, DEFAULT_IALLOCATOR_OPT, RESERVED_LVS_OPT,
1333
     DRY_RUN_OPT, PRIORITY_OPT, PREALLOC_WIPE_DISKS_OPT, NODE_PARAMS_OPT],
1334
    "[opts...]",
1335
    "Alters the parameters of the cluster"),
1336
  "renew-crypto": (
1337
    RenewCrypto, ARGS_NONE,
1338
    [NEW_CLUSTER_CERT_OPT, NEW_RAPI_CERT_OPT, RAPI_CERT_OPT,
1339
     NEW_CONFD_HMAC_KEY_OPT, FORCE_OPT,
1340
     NEW_CLUSTER_DOMAIN_SECRET_OPT, CLUSTER_DOMAIN_SECRET_OPT],
1341
    "[opts...]",
1342
    "Renews cluster certificates, keys and secrets"),
1343
  "epo": (
1344
    Epo, [ArgUnknown()],
1345
    [FORCE_OPT, ON_OPT, GROUPS_OPT, ALL_OPT, OOB_TIMEOUT_OPT,
1346
     SHUTDOWN_TIMEOUT_OPT, POWER_DELAY_OPT],
1347
    "[opts...] [args]",
1348
    "Performs an emergency power-off on given args"),
1349
  }
1350

    
1351

    
1352
#: dictionary with aliases for commands
1353
aliases = {
1354
  "masterfailover": "master-failover",
1355
}
1356

    
1357

    
1358
def Main():
1359
  return GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER},
1360
                     aliases=aliases)