Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_cluster.py @ 66d1f035

History | View | Annotate | Download (41.5 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
                        enabled_hypervisors=hvlist,
149
                        hvparams=hvparams,
150
                        beparams=beparams,
151
                        nicparams=nicparams,
152
                        ndparams=ndparams,
153
                        candidate_pool_size=opts.candidate_pool_size,
154
                        modify_etc_hosts=opts.modify_etc_hosts,
155
                        modify_ssh_setup=opts.modify_ssh_setup,
156
                        maintain_node_health=opts.maintain_node_health,
157
                        drbd_helper=drbd_helper,
158
                        uid_pool=uid_pool,
159
                        default_iallocator=opts.default_iallocator,
160
                        primary_ip_version=primary_ip_version,
161
                        prealloc_wipe_disks=opts.prealloc_wipe_disks,
162
                        )
163
  op = opcodes.OpClusterPostInit()
164
  SubmitOpCode(op, opts=opts)
165
  return 0
166

    
167

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

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

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

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

    
191

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

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

201
  """
202
  cl = GetClient()
203

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

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

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

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

    
222
  return 0
223

    
224

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

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

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

    
239

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

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

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

    
259

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

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

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

    
274

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

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

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

    
294

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
364
  ToStdout("Default node parameters:")
365
  _PrintGroupedParams(result["ndparams"], roman=opts.roman_integers)
366

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

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

    
373
  return 0
374

    
375

    
376
def ClusterCopyFile(opts, args):
377
  """Copy a file from master to some nodes.
378

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

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

    
392
  cl = GetClient()
393

    
394
  cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
395

    
396
  results = GetOnlineNodes(nodes=opts.nodes, cl=cl, filter_master=True,
397
                           secondary_ips=opts.use_replication_network)
398

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

    
404
  return 0
405

    
406

    
407
def RunClusterCommand(opts, args):
408
  """Run a command on some nodes.
409

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

416
  """
417
  cl = GetClient()
418

    
419
  command = " ".join(args)
420

    
421
  nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl)
422

    
423
  cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
424
                                                    "master_node"])
425

    
426
  srun = ssh.SshRunner(cluster_name=cluster_name)
427

    
428
  # Make sure master node is at list end
429
  if master_node in nodes:
430
    nodes.remove(master_node)
431
    nodes.append(master_node)
432

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

    
440
  return 0
441

    
442

    
443
def VerifyCluster(opts, args):
444
  """Verify integrity of cluster, performing various test on nodes.
445

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

452
  """
453
  skip_checks = []
454
  if opts.skip_nplusone_mem:
455
    skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
456
  op = opcodes.OpClusterVerify(skip_checks=skip_checks,
457
                               verbose=opts.verbose,
458
                               error_codes=opts.error_codes,
459
                               debug_simulate_errors=opts.simulate_errors)
460
  if SubmitOpCode(op, opts=opts):
461
    return 0
462
  else:
463
    return 1
464

    
465

    
466
def VerifyDisks(opts, args):
467
  """Verify integrity of cluster disks.
468

469
  @param opts: the command line options selected by the user
470
  @type args: list
471
  @param args: should be an empty list
472
  @rtype: int
473
  @return: the desired exit code
474

475
  """
476
  cl = GetClient()
477

    
478
  op = opcodes.OpClusterVerifyDisks()
479
  result = SubmitOpCode(op, opts=opts, cl=cl)
480
  if not isinstance(result, (list, tuple)) or len(result) != 3:
481
    raise errors.ProgrammerError("Unknown result type for OpClusterVerifyDisks")
482

    
483
  bad_nodes, instances, missing = result
484

    
485
  retcode = constants.EXIT_SUCCESS
486

    
487
  if bad_nodes:
488
    for node, text in bad_nodes.items():
489
      ToStdout("Error gathering data on node %s: %s",
490
               node, utils.SafeEncode(text[-400:]))
491
      retcode |= 1
492
      ToStdout("You need to fix these nodes first before fixing instances")
493

    
494
  if instances:
495
    for iname in instances:
496
      if iname in missing:
497
        continue
498
      op = opcodes.OpInstanceActivateDisks(instance_name=iname)
499
      try:
500
        ToStdout("Activating disks for instance '%s'", iname)
501
        SubmitOpCode(op, opts=opts, cl=cl)
502
      except errors.GenericError, err:
503
        nret, msg = FormatError(err)
504
        retcode |= nret
505
        ToStderr("Error activating disks for instance %s: %s", iname, msg)
506

    
507
  if missing:
508
    for iname, ival in missing.iteritems():
509
      all_missing = compat.all(x[0] in bad_nodes for x in ival)
510
      if all_missing:
511
        ToStdout("Instance %s cannot be verified as it lives on"
512
                 " broken nodes", iname)
513
      else:
514
        ToStdout("Instance %s has missing logical volumes:", iname)
515
        ival.sort()
516
        for node, vol in ival:
517
          if node in bad_nodes:
518
            ToStdout("\tbroken node %s /dev/%s", node, vol)
519
          else:
520
            ToStdout("\t%s /dev/%s", node, vol)
521

    
522
    ToStdout("You need to run replace or recreate disks for all the above"
523
             " instances, if this message persist after fixing nodes.")
524
    retcode |= 1
525

    
526
  return retcode
527

    
528

    
529
def RepairDiskSizes(opts, args):
530
  """Verify sizes of cluster disks.
531

532
  @param opts: the command line options selected by the user
533
  @type args: list
534
  @param args: optional list of instances to restrict check to
535
  @rtype: int
536
  @return: the desired exit code
537

538
  """
539
  op = opcodes.OpClusterRepairDiskSizes(instances=args)
540
  SubmitOpCode(op, opts=opts)
541

    
542

    
543
@UsesRPC
544
def MasterFailover(opts, args):
545
  """Failover the master node.
546

547
  This command, when run on a non-master node, will cause the current
548
  master to cease being master, and the non-master to become new
549
  master.
550

551
  @param opts: the command line options selected by the user
552
  @type args: list
553
  @param args: should be an empty list
554
  @rtype: int
555
  @return: the desired exit code
556

557
  """
558
  if opts.no_voting:
559
    usertext = ("This will perform the failover even if most other nodes"
560
                " are down, or if this node is outdated. This is dangerous"
561
                " as it can lead to a non-consistent cluster. Check the"
562
                " gnt-cluster(8) man page before proceeding. Continue?")
563
    if not AskUser(usertext):
564
      return 1
565

    
566
  return bootstrap.MasterFailover(no_voting=opts.no_voting)
567

    
568

    
569
def MasterPing(opts, args):
570
  """Checks if the master is alive.
571

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

578
  """
579
  try:
580
    cl = GetClient()
581
    cl.QueryClusterInfo()
582
    return 0
583
  except Exception: # pylint: disable-msg=W0703
584
    return 1
585

    
586

    
587
def SearchTags(opts, args):
588
  """Searches the tags on all the cluster.
589

590
  @param opts: the command line options selected by the user
591
  @type args: list
592
  @param args: should contain only one element, the tag pattern
593
  @rtype: int
594
  @return: the desired exit code
595

596
  """
597
  op = opcodes.OpTagsSearch(pattern=args[0])
598
  result = SubmitOpCode(op, opts=opts)
599
  if not result:
600
    return 1
601
  result = list(result)
602
  result.sort()
603
  for path, tag in result:
604
    ToStdout("%s %s", path, tag)
605

    
606

    
607
def _RenewCrypto(new_cluster_cert, new_rapi_cert, rapi_cert_filename,
608
                 new_confd_hmac_key, new_cds, cds_filename,
609
                 force):
610
  """Renews cluster certificates, keys and secrets.
611

612
  @type new_cluster_cert: bool
613
  @param new_cluster_cert: Whether to generate a new cluster certificate
614
  @type new_rapi_cert: bool
615
  @param new_rapi_cert: Whether to generate a new RAPI certificate
616
  @type rapi_cert_filename: string
617
  @param rapi_cert_filename: Path to file containing new RAPI certificate
618
  @type new_confd_hmac_key: bool
619
  @param new_confd_hmac_key: Whether to generate a new HMAC key
620
  @type new_cds: bool
621
  @param new_cds: Whether to generate a new cluster domain secret
622
  @type cds_filename: string
623
  @param cds_filename: Path to file containing new cluster domain secret
624
  @type force: bool
625
  @param force: Whether to ask user for confirmation
626

627
  """
628
  if new_rapi_cert and rapi_cert_filename:
629
    ToStderr("Only one of the --new-rapi-certficate and --rapi-certificate"
630
             " options can be specified at the same time.")
631
    return 1
632

    
633
  if new_cds and cds_filename:
634
    ToStderr("Only one of the --new-cluster-domain-secret and"
635
             " --cluster-domain-secret options can be specified at"
636
             " the same time.")
637
    return 1
638

    
639
  if rapi_cert_filename:
640
    # Read and verify new certificate
641
    try:
642
      rapi_cert_pem = utils.ReadFile(rapi_cert_filename)
643

    
644
      OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
645
                                      rapi_cert_pem)
646
    except Exception, err: # pylint: disable-msg=W0703
647
      ToStderr("Can't load new RAPI certificate from %s: %s" %
648
               (rapi_cert_filename, str(err)))
649
      return 1
650

    
651
    try:
652
      OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, rapi_cert_pem)
653
    except Exception, err: # pylint: disable-msg=W0703
654
      ToStderr("Can't load new RAPI private key from %s: %s" %
655
               (rapi_cert_filename, str(err)))
656
      return 1
657

    
658
  else:
659
    rapi_cert_pem = None
660

    
661
  if cds_filename:
662
    try:
663
      cds = utils.ReadFile(cds_filename)
664
    except Exception, err: # pylint: disable-msg=W0703
665
      ToStderr("Can't load new cluster domain secret from %s: %s" %
666
               (cds_filename, str(err)))
667
      return 1
668
  else:
669
    cds = None
670

    
671
  if not force:
672
    usertext = ("This requires all daemons on all nodes to be restarted and"
673
                " may take some time. Continue?")
674
    if not AskUser(usertext):
675
      return 1
676

    
677
  def _RenewCryptoInner(ctx):
678
    ctx.feedback_fn("Updating certificates and keys")
679
    bootstrap.GenerateClusterCrypto(new_cluster_cert, new_rapi_cert,
680
                                    new_confd_hmac_key,
681
                                    new_cds,
682
                                    rapi_cert_pem=rapi_cert_pem,
683
                                    cds=cds)
684

    
685
    files_to_copy = []
686

    
687
    if new_cluster_cert:
688
      files_to_copy.append(constants.NODED_CERT_FILE)
689

    
690
    if new_rapi_cert or rapi_cert_pem:
691
      files_to_copy.append(constants.RAPI_CERT_FILE)
692

    
693
    if new_confd_hmac_key:
694
      files_to_copy.append(constants.CONFD_HMAC_KEY)
695

    
696
    if new_cds or cds:
697
      files_to_copy.append(constants.CLUSTER_DOMAIN_SECRET_FILE)
698

    
699
    if files_to_copy:
700
      for node_name in ctx.nonmaster_nodes:
701
        ctx.feedback_fn("Copying %s to %s" %
702
                        (", ".join(files_to_copy), node_name))
703
        for file_name in files_to_copy:
704
          ctx.ssh.CopyFileToNode(node_name, file_name)
705

    
706
  RunWhileClusterStopped(ToStdout, _RenewCryptoInner)
707

    
708
  ToStdout("All requested certificates and keys have been replaced."
709
           " Running \"gnt-cluster verify\" now is recommended.")
710

    
711
  return 0
712

    
713

    
714
def RenewCrypto(opts, args):
715
  """Renews cluster certificates, keys and secrets.
716

717
  """
718
  return _RenewCrypto(opts.new_cluster_cert,
719
                      opts.new_rapi_cert,
720
                      opts.rapi_cert,
721
                      opts.new_confd_hmac_key,
722
                      opts.new_cluster_domain_secret,
723
                      opts.cluster_domain_secret,
724
                      opts.force)
725

    
726

    
727
def SetClusterParams(opts, args):
728
  """Modify the cluster.
729

730
  @param opts: the command line options selected by the user
731
  @type args: list
732
  @param args: should be an empty list
733
  @rtype: int
734
  @return: the desired exit code
735

736
  """
737
  if not (not opts.lvm_storage or opts.vg_name or
738
          not opts.drbd_storage or opts.drbd_helper or
739
          opts.enabled_hypervisors or opts.hvparams or
740
          opts.beparams or opts.nicparams or opts.ndparams or
741
          opts.candidate_pool_size is not None or
742
          opts.uid_pool is not None or
743
          opts.maintain_node_health is not None or
744
          opts.add_uids is not None or
745
          opts.remove_uids is not None or
746
          opts.default_iallocator is not None or
747
          opts.reserved_lvs is not None or
748
          opts.master_netdev is not None or
749
          opts.prealloc_wipe_disks is not None):
750
    ToStderr("Please give at least one of the parameters.")
751
    return 1
752

    
753
  vg_name = opts.vg_name
754
  if not opts.lvm_storage and opts.vg_name:
755
    ToStderr("Options --no-lvm-storage and --vg-name conflict.")
756
    return 1
757

    
758
  if not opts.lvm_storage:
759
    vg_name = ""
760

    
761
  drbd_helper = opts.drbd_helper
762
  if not opts.drbd_storage and opts.drbd_helper:
763
    ToStderr("Options --no-drbd-storage and --drbd-usermode-helper conflict.")
764
    return 1
765

    
766
  if not opts.drbd_storage:
767
    drbd_helper = ""
768

    
769
  hvlist = opts.enabled_hypervisors
770
  if hvlist is not None:
771
    hvlist = hvlist.split(",")
772

    
773
  # a list of (name, dict) we can pass directly to dict() (or [])
774
  hvparams = dict(opts.hvparams)
775
  for hv_params in hvparams.values():
776
    utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
777

    
778
  beparams = opts.beparams
779
  utils.ForceDictType(beparams, constants.BES_PARAMETER_TYPES)
780

    
781
  nicparams = opts.nicparams
782
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
783

    
784
  ndparams = opts.ndparams
785
  if ndparams is not None:
786
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
787

    
788
  mnh = opts.maintain_node_health
789

    
790
  uid_pool = opts.uid_pool
791
  if uid_pool is not None:
792
    uid_pool = uidpool.ParseUidPool(uid_pool)
793

    
794
  add_uids = opts.add_uids
795
  if add_uids is not None:
796
    add_uids = uidpool.ParseUidPool(add_uids)
797

    
798
  remove_uids = opts.remove_uids
799
  if remove_uids is not None:
800
    remove_uids = uidpool.ParseUidPool(remove_uids)
801

    
802
  if opts.reserved_lvs is not None:
803
    if opts.reserved_lvs == "":
804
      opts.reserved_lvs = []
805
    else:
806
      opts.reserved_lvs = utils.UnescapeAndSplit(opts.reserved_lvs, sep=",")
807

    
808
  op = opcodes.OpClusterSetParams(vg_name=vg_name,
809
                                  drbd_helper=drbd_helper,
810
                                  enabled_hypervisors=hvlist,
811
                                  hvparams=hvparams,
812
                                  os_hvp=None,
813
                                  beparams=beparams,
814
                                  nicparams=nicparams,
815
                                  ndparams=ndparams,
816
                                  candidate_pool_size=opts.candidate_pool_size,
817
                                  maintain_node_health=mnh,
818
                                  uid_pool=uid_pool,
819
                                  add_uids=add_uids,
820
                                  remove_uids=remove_uids,
821
                                  default_iallocator=opts.default_iallocator,
822
                                  prealloc_wipe_disks=opts.prealloc_wipe_disks,
823
                                  master_netdev=opts.master_netdev,
824
                                  reserved_lvs=opts.reserved_lvs)
825
  SubmitOpCode(op, opts=opts)
826
  return 0
827

    
828

    
829
def QueueOps(opts, args):
830
  """Queue operations.
831

832
  @param opts: the command line options selected by the user
833
  @type args: list
834
  @param args: should contain only one element, the subcommand
835
  @rtype: int
836
  @return: the desired exit code
837

838
  """
839
  command = args[0]
840
  client = GetClient()
841
  if command in ("drain", "undrain"):
842
    drain_flag = command == "drain"
843
    client.SetQueueDrainFlag(drain_flag)
844
  elif command == "info":
845
    result = client.QueryConfigValues(["drain_flag"])
846
    if result[0]:
847
      val = "set"
848
    else:
849
      val = "unset"
850
    ToStdout("The drain flag is %s" % val)
851
  else:
852
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
853
                               errors.ECODE_INVAL)
854

    
855
  return 0
856

    
857

    
858
def _ShowWatcherPause(until):
859
  if until is None or until < time.time():
860
    ToStdout("The watcher is not paused.")
861
  else:
862
    ToStdout("The watcher is paused until %s.", time.ctime(until))
863

    
864

    
865
def WatcherOps(opts, args):
866
  """Watcher operations.
867

868
  @param opts: the command line options selected by the user
869
  @type args: list
870
  @param args: should contain only one element, the subcommand
871
  @rtype: int
872
  @return: the desired exit code
873

874
  """
875
  command = args[0]
876
  client = GetClient()
877

    
878
  if command == "continue":
879
    client.SetWatcherPause(None)
880
    ToStdout("The watcher is no longer paused.")
881

    
882
  elif command == "pause":
883
    if len(args) < 2:
884
      raise errors.OpPrereqError("Missing pause duration", errors.ECODE_INVAL)
885

    
886
    result = client.SetWatcherPause(time.time() + ParseTimespec(args[1]))
887
    _ShowWatcherPause(result)
888

    
889
  elif command == "info":
890
    result = client.QueryConfigValues(["watcher_pause"])
891
    _ShowWatcherPause(result[0])
892

    
893
  else:
894
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
895
                               errors.ECODE_INVAL)
896

    
897
  return 0
898

    
899

    
900
def _OobPower(opts, node_list, power):
901
  """Puts the node in the list to desired power state.
902

903
  @param opts: The command line options selected by the user
904
  @param node_list: The list of nodes to operate on
905
  @param power: True if they should be powered on, False otherwise
906
  @return: The success of the operation (none failed)
907

908
  """
909
  if power:
910
    command = constants.OOB_POWER_ON
911
  else:
912
    command = constants.OOB_POWER_OFF
913

    
914
  op = opcodes.OpOobCommand(node_names=node_list,
915
                            command=command,
916
                            ignore_status=True,
917
                            timeout=opts.oob_timeout)
918
  result = SubmitOpCode(op, opts=opts)
919
  errs = 0
920
  for node_result in result:
921
    (node_tuple, data_tuple) = node_result
922
    (_, node_name) = node_tuple
923
    (data_status, _) = data_tuple
924
    if data_status != constants.RS_NORMAL:
925
      assert data_status != constants.RS_UNAVAIL
926
      errs += 1
927
      ToStderr("There was a problem changing power for %s, please investigate",
928
               node_name)
929

    
930
  if errs > 0:
931
    return False
932

    
933
  return True
934

    
935

    
936
def _InstanceStart(opts, inst_list, start):
937
  """Puts the instances in the list to desired state.
938

939
  @param opts: The command line options selected by the user
940
  @param inst_list: The list of instances to operate on
941
  @param start: True if they should be started, False for shutdown
942
  @return: The success of the operation (none failed)
943

944
  """
945
  if start:
946
    opcls = opcodes.OpInstanceStartup
947
    text_submit, text_success, text_failed = ("startup", "started", "starting")
948
  else:
949
    opcls = opcodes.OpInstanceShutdown
950
    text_submit, text_success, text_failed = ("shutdown", "stopped", "stopping")
951

    
952
  jex = JobExecutor(opts=opts)
953

    
954
  for inst in inst_list:
955
    ToStdout("Submit %s of instance %s", text_submit, inst)
956
    op = opcls(instance_name=inst)
957
    jex.QueueJob(inst, op)
958

    
959
  results = jex.GetResults()
960
  bad_cnt = len([1 for (success, _) in results if not success])
961

    
962
  if bad_cnt == 0:
963
    ToStdout("All instances have been %s successfully", text_success)
964
  else:
965
    ToStderr("There were errors while %s instances:\n"
966
             "%d error(s) out of %d instance(s)", text_failed, bad_cnt,
967
             len(results))
968
    return False
969

    
970
  return True
971

    
972

    
973
class _RunWhenNodesReachableHelper:
974
  """Helper class to make shared internal state sharing easier.
975

976
  @ivar success: Indicates if all action_cb calls were successful
977

978
  """
979
  def __init__(self, node_list, action_cb, node2ip, port,
980
               _ping_fn=netutils.TcpPing, _sleep_fn=time.sleep):
981
    """Init the object.
982

983
    @param node_list: The list of nodes to be reachable
984
    @param action_cb: Callback called when a new host is reachable
985
    @type node2ip: dict
986
    @param node2ip: Node to ip mapping
987
    @param port: The port to use for the TCP ping
988
    @param _ping_fn: Function to check reachabilty (for unittest use only)
989
    @param _sleep_fn: Function to sleep (for unittest use only)
990

991
    """
992
    self.down = set(node_list)
993
    self.up = set()
994
    self.node2ip = node2ip
995
    self.success = True
996
    self.action_cb = action_cb
997
    self.port = port
998
    self._ping_fn = _ping_fn
999
    self._sleep_fn = _sleep_fn
1000

    
1001
  def __call__(self):
1002
    """When called we run action_cb.
1003

1004
    @raises utils.RetryAgain: When there are still down nodes
1005

1006
    """
1007
    if not self.action_cb(self.up):
1008
      self.success = False
1009

    
1010
    if self.down:
1011
      raise utils.RetryAgain()
1012
    else:
1013
      return self.success
1014

    
1015
  def Wait(self, secs):
1016
    """Checks if a host is up or waits remaining seconds.
1017

1018
    @param secs: The secs remaining
1019

1020
    """
1021
    start = time.time()
1022
    for node in self.down:
1023
      if self._ping_fn(self.node2ip[node], self.port, timeout=_EPO_PING_TIMEOUT,
1024
                       live_port_needed=True):
1025
        ToStdout("Node %s became available", node)
1026
        self.up.add(node)
1027
        self.down -= self.up
1028
        # If we have a node available there is the possibility to run the
1029
        # action callback successfully, therefore we don't wait and return
1030
        return
1031

    
1032
    self._sleep_fn(max(0.0, start + secs - time.time()))
1033

    
1034

    
1035
def _RunWhenNodesReachable(node_list, action_cb, interval):
1036
  """Run action_cb when nodes become reachable.
1037

1038
  @param node_list: The list of nodes to be reachable
1039
  @param action_cb: Callback called when a new host is reachable
1040
  @param interval: The earliest time to retry
1041

1042
  """
1043
  client = GetClient()
1044
  cluster_info = client.QueryClusterInfo()
1045
  if cluster_info["primary_ip_version"] == constants.IP4_VERSION:
1046
    family = netutils.IPAddress.family
1047
  else:
1048
    family = netutils.IP6Address.family
1049

    
1050
  node2ip = dict((node, netutils.GetHostname(node, family=family).ip)
1051
                 for node in node_list)
1052

    
1053
  port = netutils.GetDaemonPort(constants.NODED)
1054
  helper = _RunWhenNodesReachableHelper(node_list, action_cb, node2ip, port)
1055

    
1056
  try:
1057
    return utils.Retry(helper, interval, _EPO_REACHABLE_TIMEOUT,
1058
                       wait_fn=helper.Wait)
1059
  except utils.RetryTimeout:
1060
    ToStderr("Time exceeded while waiting for nodes to become reachable"
1061
             " again:\n  - %s", "  - ".join(helper.down))
1062
    return False
1063

    
1064

    
1065
def _MaybeInstanceStartup(opts, inst_map, nodes_online,
1066
                          _instance_start_fn=_InstanceStart):
1067
  """Start the instances conditional based on node_states.
1068

1069
  @param opts: The command line options selected by the user
1070
  @param inst_map: A dict of inst -> nodes mapping
1071
  @param nodes_online: A list of nodes online
1072
  @param _instance_start_fn: Callback to start instances (unittest use only)
1073
  @return: Success of the operation on all instances
1074

1075
  """
1076
  start_inst_list = []
1077
  for (inst, nodes) in inst_map.items():
1078
    if not (nodes - nodes_online):
1079
      # All nodes the instance lives on are back online
1080
      start_inst_list.append(inst)
1081

    
1082
  for inst in start_inst_list:
1083
    del inst_map[inst]
1084

    
1085
  if start_inst_list:
1086
    return _instance_start_fn(opts, start_inst_list, True)
1087

    
1088
  return True
1089

    
1090

    
1091
def _EpoOn(opts, full_node_list, node_list, inst_map):
1092
  """Does the actual power on.
1093

1094
  @param opts: The command line options selected by the user
1095
  @param full_node_list: All nodes to operate on (includes nodes not supporting
1096
                         OOB)
1097
  @param node_list: The list of nodes to operate on (all need to support OOB)
1098
  @param inst_map: A dict of inst -> nodes mapping
1099
  @return: The desired exit status
1100

1101
  """
1102
  if node_list and not _OobPower(opts, node_list, False):
1103
    ToStderr("Not all nodes seem to get back up, investigate and start"
1104
             " manually if needed")
1105

    
1106
  # Wait for the nodes to be back up
1107
  action_cb = compat.partial(_MaybeInstanceStartup, opts, dict(inst_map))
1108

    
1109
  ToStdout("Waiting until all nodes are available again")
1110
  if not _RunWhenNodesReachable(full_node_list, action_cb, _EPO_PING_INTERVAL):
1111
    ToStderr("Please investigate and start stopped instances manually")
1112
    return constants.EXIT_FAILURE
1113

    
1114
  return constants.EXIT_SUCCESS
1115

    
1116

    
1117
def _EpoOff(opts, node_list, inst_map):
1118
  """Does the actual power off.
1119

1120
  @param opts: The command line options selected by the user
1121
  @param node_list: The list of nodes to operate on (all need to support OOB)
1122
  @param inst_map: A dict of inst -> nodes mapping
1123
  @return: The desired exit status
1124

1125
  """
1126
  if not _InstanceStart(opts, inst_map.keys(), False):
1127
    ToStderr("Please investigate and stop instances manually before continuing")
1128
    return constants.EXIT_FAILURE
1129

    
1130
  if not node_list:
1131
    return constants.EXIT_SUCCESS
1132

    
1133
  if _OobPower(opts, node_list, False):
1134
    return constants.EXIT_SUCCESS
1135
  else:
1136
    return constants.EXIT_FAILURE
1137

    
1138

    
1139
def Epo(opts, args):
1140
  """EPO operations.
1141

1142
  @param opts: the command line options selected by the user
1143
  @type args: list
1144
  @param args: should contain only one element, the subcommand
1145
  @rtype: int
1146
  @return: the desired exit code
1147

1148
  """
1149
  if opts.groups and opts.show_all:
1150
    ToStderr("Only one of --groups or --all are allowed")
1151
    return constants.EXIT_FAILURE
1152
  elif args and opts.show_all:
1153
    ToStderr("Arguments in combination with --all are not allowed")
1154
    return constants.EXIT_FAILURE
1155

    
1156
  client = GetClient()
1157

    
1158
  if opts.groups:
1159
    node_query_list = itertools.chain(*client.QueryGroups(names=args,
1160
                                                          fields=["node_list"],
1161
                                                          use_locking=False))
1162
  else:
1163
    node_query_list = args
1164

    
1165
  result = client.QueryNodes(names=node_query_list,
1166
                             fields=["name", "master", "pinst_list",
1167
                                     "sinst_list", "powered", "offline"],
1168
                             use_locking=False)
1169
  node_list = []
1170
  inst_map = {}
1171
  for (idx, (node, master, pinsts, sinsts, powered,
1172
             offline)) in enumerate(result):
1173
    # Normalize the node_query_list as well
1174
    if not opts.show_all:
1175
      node_query_list[idx] = node
1176
    if not offline:
1177
      for inst in (pinsts + sinsts):
1178
        if inst in inst_map:
1179
          if not master:
1180
            inst_map[inst].add(node)
1181
        elif master:
1182
          inst_map[inst] = set()
1183
        else:
1184
          inst_map[inst] = set([node])
1185

    
1186
    if master and opts.on:
1187
      # We ignore the master for turning on the machines, in fact we are
1188
      # already operating on the master at this point :)
1189
      continue
1190
    elif master and not opts.show_all:
1191
      ToStderr("%s is the master node, please do a master-failover to another"
1192
               " node not affected by the EPO or use --all if you intend to"
1193
               " shutdown the whole cluster", node)
1194
      return constants.EXIT_FAILURE
1195
    elif powered is None:
1196
      ToStdout("Node %s does not support out-of-band handling, it can not be"
1197
               " handled in a fully automated manner", node)
1198
    elif powered == opts.on:
1199
      ToStdout("Node %s is already in desired power state, skipping", node)
1200
    elif not offline or (offline and powered):
1201
      node_list.append(node)
1202

    
1203
  if not opts.force and not ConfirmOperation(node_query_list, "nodes", "epo"):
1204
    return constants.EXIT_FAILURE
1205

    
1206
  if opts.on:
1207
    return _EpoOn(opts, node_query_list, node_list, inst_map)
1208
  else:
1209
    return _EpoOff(opts, node_list, inst_map)
1210

    
1211

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

    
1314

    
1315
#: dictionary with aliases for commands
1316
aliases = {
1317
  'masterfailover': 'master-failover',
1318
}
1319

    
1320

    
1321
def Main():
1322
  return GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER},
1323
                     aliases=aliases)