Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_cluster.py @ 40167d65

History | View | Annotate | Download (42.7 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

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

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

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

    
376
  return 0
377

    
378

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

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

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

    
395
  cl = GetClient()
396

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

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

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

    
407
  return 0
408

    
409

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

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

419
  """
420
  cl = GetClient()
421

    
422
  command = " ".join(args)
423

    
424
  nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl)
425

    
426
  cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
427
                                                    "master_node"])
428

    
429
  srun = ssh.SshRunner(cluster_name=cluster_name)
430

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

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

    
443
  return 0
444

    
445

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

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

455
  """
456
  simulate = opts.simulate_errors
457
  skip_checks = []
458

    
459
  if opts.nodegroup is None:
460
    # Verify cluster config.
461
    op = opcodes.OpClusterVerifyConfig(verbose=opts.verbose,
462
                                       error_codes=opts.error_codes,
463
                                       debug_simulate_errors=simulate)
464

    
465
    success, all_groups = SubmitOpCode(op, opts=opts)
466
  else:
467
    success = True
468
    all_groups = [opts.nodegroup]
469

    
470
  if opts.skip_nplusone_mem:
471
    skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
472

    
473
  jex = JobExecutor(opts=opts, verbose=False)
474

    
475
  for group in all_groups:
476
    op = opcodes.OpClusterVerifyGroup(group_name=group,
477
                                      skip_checks=skip_checks,
478
                                      verbose=opts.verbose,
479
                                      error_codes=opts.error_codes,
480
                                      debug_simulate_errors=simulate)
481
    jex.QueueJob('group ' + group, op)
482

    
483
  results = jex.GetResults()
484
  success &= compat.all(r[1][0] for r in results)
485

    
486
  return (not success and 1 or 0)
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
  result = SubmitOpCode(op, opts=opts, cl=cl)
503
  if not isinstance(result, (list, tuple)) or len(result) != 3:
504
    raise errors.ProgrammerError("Unknown result type for OpClusterVerifyDisks")
505

    
506
  bad_nodes, instances, missing = result
507

    
508
  retcode = constants.EXIT_SUCCESS
509

    
510
  if bad_nodes:
511
    for node, text in bad_nodes.items():
512
      ToStdout("Error gathering data on node %s: %s",
513
               node, utils.SafeEncode(text[-400:]))
514
      retcode |= 1
515
      ToStdout("You need to fix these nodes first before fixing instances")
516

    
517
  if instances:
518
    for iname in instances:
519
      if iname in missing:
520
        continue
521
      op = opcodes.OpInstanceActivateDisks(instance_name=iname)
522
      try:
523
        ToStdout("Activating disks for instance '%s'", iname)
524
        SubmitOpCode(op, opts=opts, cl=cl)
525
      except errors.GenericError, err:
526
        nret, msg = FormatError(err)
527
        retcode |= nret
528
        ToStderr("Error activating disks for instance %s: %s", iname, msg)
529

    
530
  if missing:
531
    for iname, ival in missing.iteritems():
532
      all_missing = compat.all(x[0] in bad_nodes for x in ival)
533
      if all_missing:
534
        ToStdout("Instance %s cannot be verified as it lives on"
535
                 " broken nodes", iname)
536
      else:
537
        ToStdout("Instance %s has missing logical volumes:", iname)
538
        ival.sort()
539
        for node, vol in ival:
540
          if node in bad_nodes:
541
            ToStdout("\tbroken node %s /dev/%s", node, vol)
542
          else:
543
            ToStdout("\t%s /dev/%s", node, vol)
544

    
545
    ToStdout("You need to run replace or recreate disks for all the above"
546
             " instances, if this message persist after fixing nodes.")
547
    retcode |= 1
548

    
549
  return retcode
550

    
551

    
552
def RepairDiskSizes(opts, args):
553
  """Verify sizes of cluster disks.
554

555
  @param opts: the command line options selected by the user
556
  @type args: list
557
  @param args: optional list of instances to restrict check to
558
  @rtype: int
559
  @return: the desired exit code
560

561
  """
562
  op = opcodes.OpClusterRepairDiskSizes(instances=args)
563
  SubmitOpCode(op, opts=opts)
564

    
565

    
566
@UsesRPC
567
def MasterFailover(opts, args):
568
  """Failover the master node.
569

570
  This command, when run on a non-master node, will cause the current
571
  master to cease being master, and the non-master to become new
572
  master.
573

574
  @param opts: the command line options selected by the user
575
  @type args: list
576
  @param args: should be an empty list
577
  @rtype: int
578
  @return: the desired exit code
579

580
  """
581
  if opts.no_voting:
582
    usertext = ("This will perform the failover even if most other nodes"
583
                " are down, or if this node is outdated. This is dangerous"
584
                " as it can lead to a non-consistent cluster. Check the"
585
                " gnt-cluster(8) man page before proceeding. Continue?")
586
    if not AskUser(usertext):
587
      return 1
588

    
589
  return bootstrap.MasterFailover(no_voting=opts.no_voting)
590

    
591

    
592
def MasterPing(opts, args):
593
  """Checks if the master is alive.
594

595
  @param opts: the command line options selected by the user
596
  @type args: list
597
  @param args: should be an empty list
598
  @rtype: int
599
  @return: the desired exit code
600

601
  """
602
  try:
603
    cl = GetClient()
604
    cl.QueryClusterInfo()
605
    return 0
606
  except Exception: # pylint: disable-msg=W0703
607
    return 1
608

    
609

    
610
def SearchTags(opts, args):
611
  """Searches the tags on all the cluster.
612

613
  @param opts: the command line options selected by the user
614
  @type args: list
615
  @param args: should contain only one element, the tag pattern
616
  @rtype: int
617
  @return: the desired exit code
618

619
  """
620
  op = opcodes.OpTagsSearch(pattern=args[0])
621
  result = SubmitOpCode(op, opts=opts)
622
  if not result:
623
    return 1
624
  result = list(result)
625
  result.sort()
626
  for path, tag in result:
627
    ToStdout("%s %s", path, tag)
628

    
629

    
630
def _RenewCrypto(new_cluster_cert, new_rapi_cert, rapi_cert_filename,
631
                 new_confd_hmac_key, new_cds, cds_filename,
632
                 force):
633
  """Renews cluster certificates, keys and secrets.
634

635
  @type new_cluster_cert: bool
636
  @param new_cluster_cert: Whether to generate a new cluster certificate
637
  @type new_rapi_cert: bool
638
  @param new_rapi_cert: Whether to generate a new RAPI certificate
639
  @type rapi_cert_filename: string
640
  @param rapi_cert_filename: Path to file containing new RAPI certificate
641
  @type new_confd_hmac_key: bool
642
  @param new_confd_hmac_key: Whether to generate a new HMAC key
643
  @type new_cds: bool
644
  @param new_cds: Whether to generate a new cluster domain secret
645
  @type cds_filename: string
646
  @param cds_filename: Path to file containing new cluster domain secret
647
  @type force: bool
648
  @param force: Whether to ask user for confirmation
649

650
  """
651
  if new_rapi_cert and rapi_cert_filename:
652
    ToStderr("Only one of the --new-rapi-certficate and --rapi-certificate"
653
             " options can be specified at the same time.")
654
    return 1
655

    
656
  if new_cds and cds_filename:
657
    ToStderr("Only one of the --new-cluster-domain-secret and"
658
             " --cluster-domain-secret options can be specified at"
659
             " the same time.")
660
    return 1
661

    
662
  if rapi_cert_filename:
663
    # Read and verify new certificate
664
    try:
665
      rapi_cert_pem = utils.ReadFile(rapi_cert_filename)
666

    
667
      OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
668
                                      rapi_cert_pem)
669
    except Exception, err: # pylint: disable-msg=W0703
670
      ToStderr("Can't load new RAPI certificate from %s: %s" %
671
               (rapi_cert_filename, str(err)))
672
      return 1
673

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

    
681
  else:
682
    rapi_cert_pem = None
683

    
684
  if cds_filename:
685
    try:
686
      cds = utils.ReadFile(cds_filename)
687
    except Exception, err: # pylint: disable-msg=W0703
688
      ToStderr("Can't load new cluster domain secret from %s: %s" %
689
               (cds_filename, str(err)))
690
      return 1
691
  else:
692
    cds = None
693

    
694
  if not force:
695
    usertext = ("This requires all daemons on all nodes to be restarted and"
696
                " may take some time. Continue?")
697
    if not AskUser(usertext):
698
      return 1
699

    
700
  def _RenewCryptoInner(ctx):
701
    ctx.feedback_fn("Updating certificates and keys")
702
    bootstrap.GenerateClusterCrypto(new_cluster_cert, new_rapi_cert,
703
                                    new_confd_hmac_key,
704
                                    new_cds,
705
                                    rapi_cert_pem=rapi_cert_pem,
706
                                    cds=cds)
707

    
708
    files_to_copy = []
709

    
710
    if new_cluster_cert:
711
      files_to_copy.append(constants.NODED_CERT_FILE)
712

    
713
    if new_rapi_cert or rapi_cert_pem:
714
      files_to_copy.append(constants.RAPI_CERT_FILE)
715

    
716
    if new_confd_hmac_key:
717
      files_to_copy.append(constants.CONFD_HMAC_KEY)
718

    
719
    if new_cds or cds:
720
      files_to_copy.append(constants.CLUSTER_DOMAIN_SECRET_FILE)
721

    
722
    if files_to_copy:
723
      for node_name in ctx.nonmaster_nodes:
724
        ctx.feedback_fn("Copying %s to %s" %
725
                        (", ".join(files_to_copy), node_name))
726
        for file_name in files_to_copy:
727
          ctx.ssh.CopyFileToNode(node_name, file_name)
728

    
729
  RunWhileClusterStopped(ToStdout, _RenewCryptoInner)
730

    
731
  ToStdout("All requested certificates and keys have been replaced."
732
           " Running \"gnt-cluster verify\" now is recommended.")
733

    
734
  return 0
735

    
736

    
737
def RenewCrypto(opts, args):
738
  """Renews cluster certificates, keys and secrets.
739

740
  """
741
  return _RenewCrypto(opts.new_cluster_cert,
742
                      opts.new_rapi_cert,
743
                      opts.rapi_cert,
744
                      opts.new_confd_hmac_key,
745
                      opts.new_cluster_domain_secret,
746
                      opts.cluster_domain_secret,
747
                      opts.force)
748

    
749

    
750
def SetClusterParams(opts, args):
751
  """Modify the cluster.
752

753
  @param opts: the command line options selected by the user
754
  @type args: list
755
  @param args: should be an empty list
756
  @rtype: int
757
  @return: the desired exit code
758

759
  """
760
  if not (not opts.lvm_storage or opts.vg_name or
761
          not opts.drbd_storage or opts.drbd_helper or
762
          opts.enabled_hypervisors or opts.hvparams or
763
          opts.beparams or opts.nicparams or opts.ndparams or
764
          opts.candidate_pool_size is not None or
765
          opts.uid_pool is not None or
766
          opts.maintain_node_health is not None or
767
          opts.add_uids is not None or
768
          opts.remove_uids is not None or
769
          opts.default_iallocator is not None or
770
          opts.reserved_lvs is not None or
771
          opts.master_netdev is not None or
772
          opts.prealloc_wipe_disks is not None):
773
    ToStderr("Please give at least one of the parameters.")
774
    return 1
775

    
776
  vg_name = opts.vg_name
777
  if not opts.lvm_storage and opts.vg_name:
778
    ToStderr("Options --no-lvm-storage and --vg-name conflict.")
779
    return 1
780

    
781
  if not opts.lvm_storage:
782
    vg_name = ""
783

    
784
  drbd_helper = opts.drbd_helper
785
  if not opts.drbd_storage and opts.drbd_helper:
786
    ToStderr("Options --no-drbd-storage and --drbd-usermode-helper conflict.")
787
    return 1
788

    
789
  if not opts.drbd_storage:
790
    drbd_helper = ""
791

    
792
  hvlist = opts.enabled_hypervisors
793
  if hvlist is not None:
794
    hvlist = hvlist.split(",")
795

    
796
  # a list of (name, dict) we can pass directly to dict() (or [])
797
  hvparams = dict(opts.hvparams)
798
  for hv_params in hvparams.values():
799
    utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
800

    
801
  beparams = opts.beparams
802
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
803

    
804
  nicparams = opts.nicparams
805
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
806

    
807
  ndparams = opts.ndparams
808
  if ndparams is not None:
809
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
810

    
811
  mnh = opts.maintain_node_health
812

    
813
  uid_pool = opts.uid_pool
814
  if uid_pool is not None:
815
    uid_pool = uidpool.ParseUidPool(uid_pool)
816

    
817
  add_uids = opts.add_uids
818
  if add_uids is not None:
819
    add_uids = uidpool.ParseUidPool(add_uids)
820

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

    
825
  if opts.reserved_lvs is not None:
826
    if opts.reserved_lvs == "":
827
      opts.reserved_lvs = []
828
    else:
829
      opts.reserved_lvs = utils.UnescapeAndSplit(opts.reserved_lvs, sep=",")
830

    
831
  op = opcodes.OpClusterSetParams(vg_name=vg_name,
832
                                  drbd_helper=drbd_helper,
833
                                  enabled_hypervisors=hvlist,
834
                                  hvparams=hvparams,
835
                                  os_hvp=None,
836
                                  beparams=beparams,
837
                                  nicparams=nicparams,
838
                                  ndparams=ndparams,
839
                                  candidate_pool_size=opts.candidate_pool_size,
840
                                  maintain_node_health=mnh,
841
                                  uid_pool=uid_pool,
842
                                  add_uids=add_uids,
843
                                  remove_uids=remove_uids,
844
                                  default_iallocator=opts.default_iallocator,
845
                                  prealloc_wipe_disks=opts.prealloc_wipe_disks,
846
                                  master_netdev=opts.master_netdev,
847
                                  reserved_lvs=opts.reserved_lvs)
848
  SubmitOpCode(op, opts=opts)
849
  return 0
850

    
851

    
852
def QueueOps(opts, args):
853
  """Queue operations.
854

855
  @param opts: the command line options selected by the user
856
  @type args: list
857
  @param args: should contain only one element, the subcommand
858
  @rtype: int
859
  @return: the desired exit code
860

861
  """
862
  command = args[0]
863
  client = GetClient()
864
  if command in ("drain", "undrain"):
865
    drain_flag = command == "drain"
866
    client.SetQueueDrainFlag(drain_flag)
867
  elif command == "info":
868
    result = client.QueryConfigValues(["drain_flag"])
869
    if result[0]:
870
      val = "set"
871
    else:
872
      val = "unset"
873
    ToStdout("The drain flag is %s" % val)
874
  else:
875
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
876
                               errors.ECODE_INVAL)
877

    
878
  return 0
879

    
880

    
881
def _ShowWatcherPause(until):
882
  if until is None or until < time.time():
883
    ToStdout("The watcher is not paused.")
884
  else:
885
    ToStdout("The watcher is paused until %s.", time.ctime(until))
886

    
887

    
888
def WatcherOps(opts, args):
889
  """Watcher operations.
890

891
  @param opts: the command line options selected by the user
892
  @type args: list
893
  @param args: should contain only one element, the subcommand
894
  @rtype: int
895
  @return: the desired exit code
896

897
  """
898
  command = args[0]
899
  client = GetClient()
900

    
901
  if command == "continue":
902
    client.SetWatcherPause(None)
903
    ToStdout("The watcher is no longer paused.")
904

    
905
  elif command == "pause":
906
    if len(args) < 2:
907
      raise errors.OpPrereqError("Missing pause duration", errors.ECODE_INVAL)
908

    
909
    result = client.SetWatcherPause(time.time() + ParseTimespec(args[1]))
910
    _ShowWatcherPause(result)
911

    
912
  elif command == "info":
913
    result = client.QueryConfigValues(["watcher_pause"])
914
    _ShowWatcherPause(result[0])
915

    
916
  else:
917
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
918
                               errors.ECODE_INVAL)
919

    
920
  return 0
921

    
922

    
923
def _OobPower(opts, node_list, power):
924
  """Puts the node in the list to desired power state.
925

926
  @param opts: The command line options selected by the user
927
  @param node_list: The list of nodes to operate on
928
  @param power: True if they should be powered on, False otherwise
929
  @return: The success of the operation (none failed)
930

931
  """
932
  if power:
933
    command = constants.OOB_POWER_ON
934
  else:
935
    command = constants.OOB_POWER_OFF
936

    
937
  op = opcodes.OpOobCommand(node_names=node_list,
938
                            command=command,
939
                            ignore_status=True,
940
                            timeout=opts.oob_timeout,
941
                            power_delay=opts.power_delay)
942
  result = SubmitOpCode(op, opts=opts)
943
  errs = 0
944
  for node_result in result:
945
    (node_tuple, data_tuple) = node_result
946
    (_, node_name) = node_tuple
947
    (data_status, _) = data_tuple
948
    if data_status != constants.RS_NORMAL:
949
      assert data_status != constants.RS_UNAVAIL
950
      errs += 1
951
      ToStderr("There was a problem changing power for %s, please investigate",
952
               node_name)
953

    
954
  if errs > 0:
955
    return False
956

    
957
  return True
958

    
959

    
960
def _InstanceStart(opts, inst_list, start):
961
  """Puts the instances in the list to desired state.
962

963
  @param opts: The command line options selected by the user
964
  @param inst_list: The list of instances to operate on
965
  @param start: True if they should be started, False for shutdown
966
  @return: The success of the operation (none failed)
967

968
  """
969
  if start:
970
    opcls = opcodes.OpInstanceStartup
971
    text_submit, text_success, text_failed = ("startup", "started", "starting")
972
  else:
973
    opcls = compat.partial(opcodes.OpInstanceShutdown,
974
                           timeout=opts.shutdown_timeout)
975
    text_submit, text_success, text_failed = ("shutdown", "stopped", "stopping")
976

    
977
  jex = JobExecutor(opts=opts)
978

    
979
  for inst in inst_list:
980
    ToStdout("Submit %s of instance %s", text_submit, inst)
981
    op = opcls(instance_name=inst)
982
    jex.QueueJob(inst, op)
983

    
984
  results = jex.GetResults()
985
  bad_cnt = len([1 for (success, _) in results if not success])
986

    
987
  if bad_cnt == 0:
988
    ToStdout("All instances have been %s successfully", text_success)
989
  else:
990
    ToStderr("There were errors while %s instances:\n"
991
             "%d error(s) out of %d instance(s)", text_failed, bad_cnt,
992
             len(results))
993
    return False
994

    
995
  return True
996

    
997

    
998
class _RunWhenNodesReachableHelper:
999
  """Helper class to make shared internal state sharing easier.
1000

1001
  @ivar success: Indicates if all action_cb calls were successful
1002

1003
  """
1004
  def __init__(self, node_list, action_cb, node2ip, port, feedback_fn,
1005
               _ping_fn=netutils.TcpPing, _sleep_fn=time.sleep):
1006
    """Init the object.
1007

1008
    @param node_list: The list of nodes to be reachable
1009
    @param action_cb: Callback called when a new host is reachable
1010
    @type node2ip: dict
1011
    @param node2ip: Node to ip mapping
1012
    @param port: The port to use for the TCP ping
1013
    @param feedback_fn: The function used for feedback
1014
    @param _ping_fn: Function to check reachabilty (for unittest use only)
1015
    @param _sleep_fn: Function to sleep (for unittest use only)
1016

1017
    """
1018
    self.down = set(node_list)
1019
    self.up = set()
1020
    self.node2ip = node2ip
1021
    self.success = True
1022
    self.action_cb = action_cb
1023
    self.port = port
1024
    self.feedback_fn = feedback_fn
1025
    self._ping_fn = _ping_fn
1026
    self._sleep_fn = _sleep_fn
1027

    
1028
  def __call__(self):
1029
    """When called we run action_cb.
1030

1031
    @raises utils.RetryAgain: When there are still down nodes
1032

1033
    """
1034
    if not self.action_cb(self.up):
1035
      self.success = False
1036

    
1037
    if self.down:
1038
      raise utils.RetryAgain()
1039
    else:
1040
      return self.success
1041

    
1042
  def Wait(self, secs):
1043
    """Checks if a host is up or waits remaining seconds.
1044

1045
    @param secs: The secs remaining
1046

1047
    """
1048
    start = time.time()
1049
    for node in self.down:
1050
      if self._ping_fn(self.node2ip[node], self.port, timeout=_EPO_PING_TIMEOUT,
1051
                       live_port_needed=True):
1052
        self.feedback_fn("Node %s became available" % node)
1053
        self.up.add(node)
1054
        self.down -= self.up
1055
        # If we have a node available there is the possibility to run the
1056
        # action callback successfully, therefore we don't wait and return
1057
        return
1058

    
1059
    self._sleep_fn(max(0.0, start + secs - time.time()))
1060

    
1061

    
1062
def _RunWhenNodesReachable(node_list, action_cb, interval):
1063
  """Run action_cb when nodes become reachable.
1064

1065
  @param node_list: The list of nodes to be reachable
1066
  @param action_cb: Callback called when a new host is reachable
1067
  @param interval: The earliest time to retry
1068

1069
  """
1070
  client = GetClient()
1071
  cluster_info = client.QueryClusterInfo()
1072
  if cluster_info["primary_ip_version"] == constants.IP4_VERSION:
1073
    family = netutils.IPAddress.family
1074
  else:
1075
    family = netutils.IP6Address.family
1076

    
1077
  node2ip = dict((node, netutils.GetHostname(node, family=family).ip)
1078
                 for node in node_list)
1079

    
1080
  port = netutils.GetDaemonPort(constants.NODED)
1081
  helper = _RunWhenNodesReachableHelper(node_list, action_cb, node2ip, port,
1082
                                        ToStdout)
1083

    
1084
  try:
1085
    return utils.Retry(helper, interval, _EPO_REACHABLE_TIMEOUT,
1086
                       wait_fn=helper.Wait)
1087
  except utils.RetryTimeout:
1088
    ToStderr("Time exceeded while waiting for nodes to become reachable"
1089
             " again:\n  - %s", "  - ".join(helper.down))
1090
    return False
1091

    
1092

    
1093
def _MaybeInstanceStartup(opts, inst_map, nodes_online,
1094
                          _instance_start_fn=_InstanceStart):
1095
  """Start the instances conditional based on node_states.
1096

1097
  @param opts: The command line options selected by the user
1098
  @param inst_map: A dict of inst -> nodes mapping
1099
  @param nodes_online: A list of nodes online
1100
  @param _instance_start_fn: Callback to start instances (unittest use only)
1101
  @return: Success of the operation on all instances
1102

1103
  """
1104
  start_inst_list = []
1105
  for (inst, nodes) in inst_map.items():
1106
    if not (nodes - nodes_online):
1107
      # All nodes the instance lives on are back online
1108
      start_inst_list.append(inst)
1109

    
1110
  for inst in start_inst_list:
1111
    del inst_map[inst]
1112

    
1113
  if start_inst_list:
1114
    return _instance_start_fn(opts, start_inst_list, True)
1115

    
1116
  return True
1117

    
1118

    
1119
def _EpoOn(opts, full_node_list, node_list, inst_map):
1120
  """Does the actual power on.
1121

1122
  @param opts: The command line options selected by the user
1123
  @param full_node_list: All nodes to operate on (includes nodes not supporting
1124
                         OOB)
1125
  @param node_list: The list of nodes to operate on (all need to support OOB)
1126
  @param inst_map: A dict of inst -> nodes mapping
1127
  @return: The desired exit status
1128

1129
  """
1130
  if node_list and not _OobPower(opts, node_list, False):
1131
    ToStderr("Not all nodes seem to get back up, investigate and start"
1132
             " manually if needed")
1133

    
1134
  # Wait for the nodes to be back up
1135
  action_cb = compat.partial(_MaybeInstanceStartup, opts, dict(inst_map))
1136

    
1137
  ToStdout("Waiting until all nodes are available again")
1138
  if not _RunWhenNodesReachable(full_node_list, action_cb, _EPO_PING_INTERVAL):
1139
    ToStderr("Please investigate and start stopped instances manually")
1140
    return constants.EXIT_FAILURE
1141

    
1142
  return constants.EXIT_SUCCESS
1143

    
1144

    
1145
def _EpoOff(opts, node_list, inst_map):
1146
  """Does the actual power off.
1147

1148
  @param opts: The command line options selected by the user
1149
  @param node_list: The list of nodes to operate on (all need to support OOB)
1150
  @param inst_map: A dict of inst -> nodes mapping
1151
  @return: The desired exit status
1152

1153
  """
1154
  if not _InstanceStart(opts, inst_map.keys(), False):
1155
    ToStderr("Please investigate and stop instances manually before continuing")
1156
    return constants.EXIT_FAILURE
1157

    
1158
  if not node_list:
1159
    return constants.EXIT_SUCCESS
1160

    
1161
  if _OobPower(opts, node_list, False):
1162
    return constants.EXIT_SUCCESS
1163
  else:
1164
    return constants.EXIT_FAILURE
1165

    
1166

    
1167
def Epo(opts, args):
1168
  """EPO operations.
1169

1170
  @param opts: the command line options selected by the user
1171
  @type args: list
1172
  @param args: should contain only one element, the subcommand
1173
  @rtype: int
1174
  @return: the desired exit code
1175

1176
  """
1177
  if opts.groups and opts.show_all:
1178
    ToStderr("Only one of --groups or --all are allowed")
1179
    return constants.EXIT_FAILURE
1180
  elif args and opts.show_all:
1181
    ToStderr("Arguments in combination with --all are not allowed")
1182
    return constants.EXIT_FAILURE
1183

    
1184
  client = GetClient()
1185

    
1186
  if opts.groups:
1187
    node_query_list = itertools.chain(*client.QueryGroups(names=args,
1188
                                                          fields=["node_list"],
1189
                                                          use_locking=False))
1190
  else:
1191
    node_query_list = args
1192

    
1193
  result = client.QueryNodes(names=node_query_list,
1194
                             fields=["name", "master", "pinst_list",
1195
                                     "sinst_list", "powered", "offline"],
1196
                             use_locking=False)
1197
  node_list = []
1198
  inst_map = {}
1199
  for (idx, (node, master, pinsts, sinsts, powered,
1200
             offline)) in enumerate(result):
1201
    # Normalize the node_query_list as well
1202
    if not opts.show_all:
1203
      node_query_list[idx] = node
1204
    if not offline:
1205
      for inst in (pinsts + sinsts):
1206
        if inst in inst_map:
1207
          if not master:
1208
            inst_map[inst].add(node)
1209
        elif master:
1210
          inst_map[inst] = set()
1211
        else:
1212
          inst_map[inst] = set([node])
1213

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

    
1231
  if not opts.force and not ConfirmOperation(node_query_list, "nodes", "epo"):
1232
    return constants.EXIT_FAILURE
1233

    
1234
  if opts.on:
1235
    return _EpoOn(opts, node_query_list, node_list, inst_map)
1236
  else:
1237
    return _EpoOff(opts, node_list, inst_map)
1238

    
1239

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

    
1343

    
1344
#: dictionary with aliases for commands
1345
aliases = {
1346
  'masterfailover': 'master-failover',
1347
}
1348

    
1349

    
1350
def Main():
1351
  return GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER},
1352
                     aliases=aliases)