Statistics
| Branch: | Tag: | Revision:

root / lib / client / gnt_cluster.py @ c51ffffe

History | View | Annotate | Download (64.1 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2010, 2011, 2012, 2013 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=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
from cStringIO import StringIO
30
import os.path
31
import time
32
import OpenSSL
33
import itertools
34

    
35
from ganeti.cli import *
36
from ganeti import opcodes
37
from ganeti import constants
38
from ganeti import errors
39
from ganeti import utils
40
from ganeti import bootstrap
41
from ganeti import ssh
42
from ganeti import objects
43
from ganeti import uidpool
44
from ganeti import compat
45
from ganeti import netutils
46
from ganeti import ssconf
47
from ganeti import pathutils
48
from ganeti import qlang
49

    
50

    
51
ON_OPT = cli_option("--on", default=False,
52
                    action="store_true", dest="on",
53
                    help="Recover from an EPO")
54

    
55
GROUPS_OPT = cli_option("--groups", default=False,
56
                        action="store_true", dest="groups",
57
                        help="Arguments are node groups instead of nodes")
58

    
59
FORCE_FAILOVER = cli_option("--yes-do-it", dest="yes_do_it",
60
                            help="Override interactive check for --no-voting",
61
                            default=False, action="store_true")
62

    
63
FORCE_DISTRIBUTION = cli_option("--yes-do-it", dest="yes_do_it",
64
                                help="Unconditionally distribute the"
65
                                " configuration, even if the queue"
66
                                " is drained",
67
                                default=False, action="store_true")
68

    
69
TO_OPT = cli_option("--to", default=None, type="string",
70
                    help="The Ganeti version to upgrade to")
71

    
72
RESUME_OPT = cli_option("--resume", default=False, action="store_true",
73
                        help="Resume any pending Ganeti upgrades")
74

    
75
_EPO_PING_INTERVAL = 30 # 30 seconds between pings
76
_EPO_PING_TIMEOUT = 1 # 1 second
77
_EPO_REACHABLE_TIMEOUT = 15 * 60 # 15 minutes
78

    
79

    
80
def _CheckNoLvmStorageOptDeprecated(opts):
81
  """Checks if the legacy option '--no-lvm-storage' is used.
82

83
  """
84
  if not opts.lvm_storage:
85
    ToStderr("The option --no-lvm-storage is no longer supported. If you want"
86
             " to disable lvm-based storage cluster-wide, use the option"
87
             " --enabled-disk-templates to disable all of these lvm-base disk "
88
             "  templates: %s" %
89
             utils.CommaJoin(utils.GetLvmDiskTemplates()))
90
    return 1
91

    
92

    
93
def _InitEnabledDiskTemplates(opts):
94
  """Initialize the list of enabled disk templates.
95

96
  """
97
  if opts.enabled_disk_templates:
98
    return opts.enabled_disk_templates.split(",")
99
  else:
100
    return constants.DEFAULT_ENABLED_DISK_TEMPLATES
101

    
102

    
103
def _InitVgName(opts, enabled_disk_templates):
104
  """Initialize the volume group name.
105

106
  @type enabled_disk_templates: list of strings
107
  @param enabled_disk_templates: cluster-wide enabled disk templates
108

109
  """
110
  vg_name = None
111
  if opts.vg_name is not None:
112
    vg_name = opts.vg_name
113
    if vg_name:
114
      if not utils.IsLvmEnabled(enabled_disk_templates):
115
        ToStdout("You specified a volume group with --vg-name, but you did not"
116
                 " enable any disk template that uses lvm.")
117
    elif utils.IsLvmEnabled(enabled_disk_templates):
118
      raise errors.OpPrereqError(
119
          "LVM disk templates are enabled, but vg name not set.")
120
  elif utils.IsLvmEnabled(enabled_disk_templates):
121
    vg_name = constants.DEFAULT_VG
122
  return vg_name
123

    
124

    
125
def _InitDrbdHelper(opts, enabled_disk_templates):
126
  """Initialize the DRBD usermode helper.
127

128
  """
129
  drbd_enabled = constants.DT_DRBD8 in enabled_disk_templates
130

    
131
  if not drbd_enabled and opts.drbd_helper is not None:
132
    ToStdout("Note: You specified a DRBD usermode helper, while DRBD storage"
133
             " is not enabled.")
134

    
135
  if drbd_enabled:
136
    if opts.drbd_helper is None:
137
      return constants.DEFAULT_DRBD_HELPER
138
    if opts.drbd_helper == '':
139
      raise errors.OpPrereqError(
140
          "Unsetting the drbd usermode helper while enabling DRBD is not"
141
          " allowed.")
142

    
143
  return opts.drbd_helper
144

    
145

    
146
@UsesRPC
147
def InitCluster(opts, args):
148
  """Initialize the cluster.
149

150
  @param opts: the command line options selected by the user
151
  @type args: list
152
  @param args: should contain only one element, the desired
153
      cluster name
154
  @rtype: int
155
  @return: the desired exit code
156

157
  """
158
  if _CheckNoLvmStorageOptDeprecated(opts):
159
    return 1
160

    
161
  enabled_disk_templates = _InitEnabledDiskTemplates(opts)
162

    
163
  try:
164
    vg_name = _InitVgName(opts, enabled_disk_templates)
165
    drbd_helper = _InitDrbdHelper(opts, enabled_disk_templates)
166
  except errors.OpPrereqError, e:
167
    ToStderr(str(e))
168
    return 1
169

    
170
  master_netdev = opts.master_netdev
171
  if master_netdev is None:
172
    nic_mode = opts.nicparams.get(constants.NIC_MODE, None)
173
    if not nic_mode:
174
      # default case, use bridging
175
      master_netdev = constants.DEFAULT_BRIDGE
176
    elif nic_mode == constants.NIC_MODE_OVS:
177
      # default ovs is different from default bridge
178
      master_netdev = constants.DEFAULT_OVS
179
      opts.nicparams[constants.NIC_LINK] = constants.DEFAULT_OVS
180

    
181
  hvlist = opts.enabled_hypervisors
182
  if hvlist is None:
183
    hvlist = constants.DEFAULT_ENABLED_HYPERVISOR
184
  hvlist = hvlist.split(",")
185

    
186
  hvparams = dict(opts.hvparams)
187
  beparams = opts.beparams
188
  nicparams = opts.nicparams
189

    
190
  diskparams = dict(opts.diskparams)
191

    
192
  # check the disk template types here, as we cannot rely on the type check done
193
  # by the opcode parameter types
194
  diskparams_keys = set(diskparams.keys())
195
  if not (diskparams_keys <= constants.DISK_TEMPLATES):
196
    unknown = utils.NiceSort(diskparams_keys - constants.DISK_TEMPLATES)
197
    ToStderr("Disk templates unknown: %s" % utils.CommaJoin(unknown))
198
    return 1
199

    
200
  # prepare beparams dict
201
  beparams = objects.FillDict(constants.BEC_DEFAULTS, beparams)
202
  utils.ForceDictType(beparams, constants.BES_PARAMETER_COMPAT)
203

    
204
  # prepare nicparams dict
205
  nicparams = objects.FillDict(constants.NICC_DEFAULTS, nicparams)
206
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
207

    
208
  # prepare ndparams dict
209
  if opts.ndparams is None:
210
    ndparams = dict(constants.NDC_DEFAULTS)
211
  else:
212
    ndparams = objects.FillDict(constants.NDC_DEFAULTS, opts.ndparams)
213
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
214

    
215
  # prepare hvparams dict
216
  for hv in constants.HYPER_TYPES:
217
    if hv not in hvparams:
218
      hvparams[hv] = {}
219
    hvparams[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], hvparams[hv])
220
    utils.ForceDictType(hvparams[hv], constants.HVS_PARAMETER_TYPES)
221

    
222
  # prepare diskparams dict
223
  for templ in constants.DISK_TEMPLATES:
224
    if templ not in diskparams:
225
      diskparams[templ] = {}
226
    diskparams[templ] = objects.FillDict(constants.DISK_DT_DEFAULTS[templ],
227
                                         diskparams[templ])
228
    utils.ForceDictType(diskparams[templ], constants.DISK_DT_TYPES)
229

    
230
  # prepare ipolicy dict
231
  ipolicy = CreateIPolicyFromOpts(
232
    ispecs_mem_size=opts.ispecs_mem_size,
233
    ispecs_cpu_count=opts.ispecs_cpu_count,
234
    ispecs_disk_count=opts.ispecs_disk_count,
235
    ispecs_disk_size=opts.ispecs_disk_size,
236
    ispecs_nic_count=opts.ispecs_nic_count,
237
    minmax_ispecs=opts.ipolicy_bounds_specs,
238
    std_ispecs=opts.ipolicy_std_specs,
239
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
240
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
241
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
242
    fill_all=True)
243

    
244
  if opts.candidate_pool_size is None:
245
    opts.candidate_pool_size = constants.MASTER_POOL_SIZE_DEFAULT
246

    
247
  if opts.mac_prefix is None:
248
    opts.mac_prefix = constants.DEFAULT_MAC_PREFIX
249

    
250
  uid_pool = opts.uid_pool
251
  if uid_pool is not None:
252
    uid_pool = uidpool.ParseUidPool(uid_pool)
253

    
254
  if opts.prealloc_wipe_disks is None:
255
    opts.prealloc_wipe_disks = False
256

    
257
  external_ip_setup_script = opts.use_external_mip_script
258
  if external_ip_setup_script is None:
259
    external_ip_setup_script = False
260

    
261
  try:
262
    primary_ip_version = int(opts.primary_ip_version)
263
  except (ValueError, TypeError), err:
264
    ToStderr("Invalid primary ip version value: %s" % str(err))
265
    return 1
266

    
267
  master_netmask = opts.master_netmask
268
  try:
269
    if master_netmask is not None:
270
      master_netmask = int(master_netmask)
271
  except (ValueError, TypeError), err:
272
    ToStderr("Invalid master netmask value: %s" % str(err))
273
    return 1
274

    
275
  if opts.disk_state:
276
    disk_state = utils.FlatToDict(opts.disk_state)
277
  else:
278
    disk_state = {}
279

    
280
  hv_state = dict(opts.hv_state)
281

    
282
  bootstrap.InitCluster(cluster_name=args[0],
283
                        secondary_ip=opts.secondary_ip,
284
                        vg_name=vg_name,
285
                        mac_prefix=opts.mac_prefix,
286
                        master_netmask=master_netmask,
287
                        master_netdev=master_netdev,
288
                        file_storage_dir=opts.file_storage_dir,
289
                        shared_file_storage_dir=opts.shared_file_storage_dir,
290
                        enabled_hypervisors=hvlist,
291
                        hvparams=hvparams,
292
                        beparams=beparams,
293
                        nicparams=nicparams,
294
                        ndparams=ndparams,
295
                        diskparams=diskparams,
296
                        ipolicy=ipolicy,
297
                        candidate_pool_size=opts.candidate_pool_size,
298
                        modify_etc_hosts=opts.modify_etc_hosts,
299
                        modify_ssh_setup=opts.modify_ssh_setup,
300
                        maintain_node_health=opts.maintain_node_health,
301
                        drbd_helper=drbd_helper,
302
                        uid_pool=uid_pool,
303
                        default_iallocator=opts.default_iallocator,
304
                        primary_ip_version=primary_ip_version,
305
                        prealloc_wipe_disks=opts.prealloc_wipe_disks,
306
                        use_external_mip_script=external_ip_setup_script,
307
                        hv_state=hv_state,
308
                        disk_state=disk_state,
309
                        enabled_disk_templates=enabled_disk_templates,
310
                        )
311
  op = opcodes.OpClusterPostInit()
312
  SubmitOpCode(op, opts=opts)
313
  return 0
314

    
315

    
316
@UsesRPC
317
def DestroyCluster(opts, args):
318
  """Destroy the cluster.
319

320
  @param opts: the command line options selected by the user
321
  @type args: list
322
  @param args: should be an empty list
323
  @rtype: int
324
  @return: the desired exit code
325

326
  """
327
  if not opts.yes_do_it:
328
    ToStderr("Destroying a cluster is irreversible. If you really want"
329
             " destroy this cluster, supply the --yes-do-it option.")
330
    return 1
331

    
332
  op = opcodes.OpClusterDestroy()
333
  master_uuid = SubmitOpCode(op, opts=opts)
334
  # if we reached this, the opcode didn't fail; we can proceed to
335
  # shutdown all the daemons
336
  bootstrap.FinalizeClusterDestroy(master_uuid)
337
  return 0
338

    
339

    
340
def RenameCluster(opts, args):
341
  """Rename the cluster.
342

343
  @param opts: the command line options selected by the user
344
  @type args: list
345
  @param args: should contain only one element, the new cluster name
346
  @rtype: int
347
  @return: the desired exit code
348

349
  """
350
  cl = GetClient()
351

    
352
  (cluster_name, ) = cl.QueryConfigValues(["cluster_name"])
353

    
354
  new_name = args[0]
355
  if not opts.force:
356
    usertext = ("This will rename the cluster from '%s' to '%s'. If you are"
357
                " connected over the network to the cluster name, the"
358
                " operation is very dangerous as the IP address will be"
359
                " removed from the node and the change may not go through."
360
                " Continue?") % (cluster_name, new_name)
361
    if not AskUser(usertext):
362
      return 1
363

    
364
  op = opcodes.OpClusterRename(name=new_name)
365
  result = SubmitOpCode(op, opts=opts, cl=cl)
366

    
367
  if result:
368
    ToStdout("Cluster renamed from '%s' to '%s'", cluster_name, result)
369

    
370
  return 0
371

    
372

    
373
def ActivateMasterIp(opts, args):
374
  """Activates the master IP.
375

376
  """
377
  op = opcodes.OpClusterActivateMasterIp()
378
  SubmitOpCode(op)
379
  return 0
380

    
381

    
382
def DeactivateMasterIp(opts, args):
383
  """Deactivates the master IP.
384

385
  """
386
  if not opts.confirm:
387
    usertext = ("This will disable the master IP. All the open connections to"
388
                " the master IP will be closed. To reach the master you will"
389
                " need to use its node IP."
390
                " Continue?")
391
    if not AskUser(usertext):
392
      return 1
393

    
394
  op = opcodes.OpClusterDeactivateMasterIp()
395
  SubmitOpCode(op)
396
  return 0
397

    
398

    
399
def RedistributeConfig(opts, args):
400
  """Forces push of the cluster configuration.
401

402
  @param opts: the command line options selected by the user
403
  @type args: list
404
  @param args: empty list
405
  @rtype: int
406
  @return: the desired exit code
407

408
  """
409
  op = opcodes.OpClusterRedistConf()
410
  if opts.yes_do_it:
411
    SubmitOpCodeToDrainedQueue(op)
412
  else:
413
    SubmitOrSend(op, opts)
414
  return 0
415

    
416

    
417
def ShowClusterVersion(opts, args):
418
  """Write version of ganeti software to the standard output.
419

420
  @param opts: the command line options selected by the user
421
  @type args: list
422
  @param args: should be an empty list
423
  @rtype: int
424
  @return: the desired exit code
425

426
  """
427
  cl = GetClient(query=True)
428
  result = cl.QueryClusterInfo()
429
  ToStdout("Software version: %s", result["software_version"])
430
  ToStdout("Internode protocol: %s", result["protocol_version"])
431
  ToStdout("Configuration format: %s", result["config_version"])
432
  ToStdout("OS api version: %s", result["os_api_version"])
433
  ToStdout("Export interface: %s", result["export_version"])
434
  ToStdout("VCS version: %s", result["vcs_version"])
435
  return 0
436

    
437

    
438
def ShowClusterMaster(opts, args):
439
  """Write name of master node to the standard output.
440

441
  @param opts: the command line options selected by the user
442
  @type args: list
443
  @param args: should be an empty list
444
  @rtype: int
445
  @return: the desired exit code
446

447
  """
448
  master = bootstrap.GetMaster()
449
  ToStdout(master)
450
  return 0
451

    
452

    
453
def _FormatGroupedParams(paramsdict, roman=False):
454
  """Format Grouped parameters (be, nic, disk) by group.
455

456
  @type paramsdict: dict of dicts
457
  @param paramsdict: {group: {param: value, ...}, ...}
458
  @rtype: dict of dicts
459
  @return: copy of the input dictionaries with strings as values
460

461
  """
462
  ret = {}
463
  for (item, val) in paramsdict.items():
464
    if isinstance(val, dict):
465
      ret[item] = _FormatGroupedParams(val, roman=roman)
466
    elif roman and isinstance(val, int):
467
      ret[item] = compat.TryToRoman(val)
468
    else:
469
      ret[item] = str(val)
470
  return ret
471

    
472

    
473
def ShowClusterConfig(opts, args):
474
  """Shows cluster information.
475

476
  @param opts: the command line options selected by the user
477
  @type args: list
478
  @param args: should be an empty list
479
  @rtype: int
480
  @return: the desired exit code
481

482
  """
483
  cl = GetClient(query=True)
484
  result = cl.QueryClusterInfo()
485

    
486
  if result["tags"]:
487
    tags = utils.CommaJoin(utils.NiceSort(result["tags"]))
488
  else:
489
    tags = "(none)"
490
  if result["reserved_lvs"]:
491
    reserved_lvs = utils.CommaJoin(result["reserved_lvs"])
492
  else:
493
    reserved_lvs = "(none)"
494

    
495
  enabled_hv = result["enabled_hypervisors"]
496
  hvparams = dict((k, v) for k, v in result["hvparams"].iteritems()
497
                  if k in enabled_hv)
498

    
499
  info = [
500
    ("Cluster name", result["name"]),
501
    ("Cluster UUID", result["uuid"]),
502

    
503
    ("Creation time", utils.FormatTime(result["ctime"])),
504
    ("Modification time", utils.FormatTime(result["mtime"])),
505

    
506
    ("Master node", result["master"]),
507

    
508
    ("Architecture (this node)",
509
     "%s (%s)" % (result["architecture"][0], result["architecture"][1])),
510

    
511
    ("Tags", tags),
512

    
513
    ("Default hypervisor", result["default_hypervisor"]),
514
    ("Enabled hypervisors", utils.CommaJoin(enabled_hv)),
515

    
516
    ("Hypervisor parameters", _FormatGroupedParams(hvparams)),
517

    
518
    ("OS-specific hypervisor parameters",
519
     _FormatGroupedParams(result["os_hvp"])),
520

    
521
    ("OS parameters", _FormatGroupedParams(result["osparams"])),
522

    
523
    ("Hidden OSes", utils.CommaJoin(result["hidden_os"])),
524
    ("Blacklisted OSes", utils.CommaJoin(result["blacklisted_os"])),
525

    
526
    ("Cluster parameters", [
527
      ("candidate pool size",
528
       compat.TryToRoman(result["candidate_pool_size"],
529
                         convert=opts.roman_integers)),
530
      ("master netdev", result["master_netdev"]),
531
      ("master netmask", result["master_netmask"]),
532
      ("use external master IP address setup script",
533
       result["use_external_mip_script"]),
534
      ("lvm volume group", result["volume_group_name"]),
535
      ("lvm reserved volumes", reserved_lvs),
536
      ("drbd usermode helper", result["drbd_usermode_helper"]),
537
      ("file storage path", result["file_storage_dir"]),
538
      ("shared file storage path", result["shared_file_storage_dir"]),
539
      ("maintenance of node health", result["maintain_node_health"]),
540
      ("uid pool", uidpool.FormatUidPool(result["uid_pool"])),
541
      ("default instance allocator", result["default_iallocator"]),
542
      ("primary ip version", result["primary_ip_version"]),
543
      ("preallocation wipe disks", result["prealloc_wipe_disks"]),
544
      ("OS search path", utils.CommaJoin(pathutils.OS_SEARCH_PATH)),
545
      ("ExtStorage Providers search path",
546
       utils.CommaJoin(pathutils.ES_SEARCH_PATH)),
547
      ("enabled disk templates",
548
       utils.CommaJoin(result["enabled_disk_templates"])),
549
      ]),
550

    
551
    ("Default node parameters",
552
     _FormatGroupedParams(result["ndparams"], roman=opts.roman_integers)),
553

    
554
    ("Default instance parameters",
555
     _FormatGroupedParams(result["beparams"], roman=opts.roman_integers)),
556

    
557
    ("Default nic parameters",
558
     _FormatGroupedParams(result["nicparams"], roman=opts.roman_integers)),
559

    
560
    ("Default disk parameters",
561
     _FormatGroupedParams(result["diskparams"], roman=opts.roman_integers)),
562

    
563
    ("Instance policy - limits for instances",
564
     FormatPolicyInfo(result["ipolicy"], None, True)),
565
    ]
566

    
567
  PrintGenericInfo(info)
568
  return 0
569

    
570

    
571
def ClusterCopyFile(opts, args):
572
  """Copy a file from master to some nodes.
573

574
  @param opts: the command line options selected by the user
575
  @type args: list
576
  @param args: should contain only one element, the path of
577
      the file to be copied
578
  @rtype: int
579
  @return: the desired exit code
580

581
  """
582
  filename = args[0]
583
  if not os.path.exists(filename):
584
    raise errors.OpPrereqError("No such filename '%s'" % filename,
585
                               errors.ECODE_INVAL)
586

    
587
  cl = GetClient()
588

    
589
  cluster_name = cl.QueryConfigValues(["cluster_name"])[0]
590

    
591
  results = GetOnlineNodes(nodes=opts.nodes, cl=cl, filter_master=True,
592
                           secondary_ips=opts.use_replication_network,
593
                           nodegroup=opts.nodegroup)
594

    
595
  srun = ssh.SshRunner(cluster_name)
596
  for node in results:
597
    if not srun.CopyFileToNode(node, filename):
598
      ToStderr("Copy of file %s to node %s failed", filename, node)
599

    
600
  return 0
601

    
602

    
603
def RunClusterCommand(opts, args):
604
  """Run a command on some nodes.
605

606
  @param opts: the command line options selected by the user
607
  @type args: list
608
  @param args: should contain the command to be run and its arguments
609
  @rtype: int
610
  @return: the desired exit code
611

612
  """
613
  cl = GetClient()
614

    
615
  command = " ".join(args)
616

    
617
  nodes = GetOnlineNodes(nodes=opts.nodes, cl=cl, nodegroup=opts.nodegroup)
618

    
619
  cluster_name, master_node = cl.QueryConfigValues(["cluster_name",
620
                                                    "master_node"])
621

    
622
  srun = ssh.SshRunner(cluster_name=cluster_name)
623

    
624
  # Make sure master node is at list end
625
  if master_node in nodes:
626
    nodes.remove(master_node)
627
    nodes.append(master_node)
628

    
629
  for name in nodes:
630
    result = srun.Run(name, constants.SSH_LOGIN_USER, command)
631

    
632
    if opts.failure_only and result.exit_code == constants.EXIT_SUCCESS:
633
      # Do not output anything for successful commands
634
      continue
635

    
636
    ToStdout("------------------------------------------------")
637
    if opts.show_machine_names:
638
      for line in result.output.splitlines():
639
        ToStdout("%s: %s", name, line)
640
    else:
641
      ToStdout("node: %s", name)
642
      ToStdout("%s", result.output)
643
    ToStdout("return code = %s", result.exit_code)
644

    
645
  return 0
646

    
647

    
648
def VerifyCluster(opts, args):
649
  """Verify integrity of cluster, performing various test on nodes.
650

651
  @param opts: the command line options selected by the user
652
  @type args: list
653
  @param args: should be an empty list
654
  @rtype: int
655
  @return: the desired exit code
656

657
  """
658
  skip_checks = []
659

    
660
  if opts.skip_nplusone_mem:
661
    skip_checks.append(constants.VERIFY_NPLUSONE_MEM)
662

    
663
  cl = GetClient()
664

    
665
  op = opcodes.OpClusterVerify(verbose=opts.verbose,
666
                               error_codes=opts.error_codes,
667
                               debug_simulate_errors=opts.simulate_errors,
668
                               skip_checks=skip_checks,
669
                               ignore_errors=opts.ignore_errors,
670
                               group_name=opts.nodegroup)
671
  result = SubmitOpCode(op, cl=cl, opts=opts)
672

    
673
  # Keep track of submitted jobs
674
  jex = JobExecutor(cl=cl, opts=opts)
675

    
676
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
677
    jex.AddJobId(None, status, job_id)
678

    
679
  results = jex.GetResults()
680

    
681
  (bad_jobs, bad_results) = \
682
    map(len,
683
        # Convert iterators to lists
684
        map(list,
685
            # Count errors
686
            map(compat.partial(itertools.ifilterfalse, bool),
687
                # Convert result to booleans in a tuple
688
                zip(*((job_success, len(op_results) == 1 and op_results[0])
689
                      for (job_success, op_results) in results)))))
690

    
691
  if bad_jobs == 0 and bad_results == 0:
692
    rcode = constants.EXIT_SUCCESS
693
  else:
694
    rcode = constants.EXIT_FAILURE
695
    if bad_jobs > 0:
696
      ToStdout("%s job(s) failed while verifying the cluster.", bad_jobs)
697

    
698
  return rcode
699

    
700

    
701
def VerifyDisks(opts, args):
702
  """Verify integrity of cluster disks.
703

704
  @param opts: the command line options selected by the user
705
  @type args: list
706
  @param args: should be an empty list
707
  @rtype: int
708
  @return: the desired exit code
709

710
  """
711
  cl = GetClient()
712

    
713
  op = opcodes.OpClusterVerifyDisks()
714

    
715
  result = SubmitOpCode(op, cl=cl, opts=opts)
716

    
717
  # Keep track of submitted jobs
718
  jex = JobExecutor(cl=cl, opts=opts)
719

    
720
  for (status, job_id) in result[constants.JOB_IDS_KEY]:
721
    jex.AddJobId(None, status, job_id)
722

    
723
  retcode = constants.EXIT_SUCCESS
724

    
725
  for (status, result) in jex.GetResults():
726
    if not status:
727
      ToStdout("Job failed: %s", result)
728
      continue
729

    
730
    ((bad_nodes, instances, missing), ) = result
731

    
732
    for node, text in bad_nodes.items():
733
      ToStdout("Error gathering data on node %s: %s",
734
               node, utils.SafeEncode(text[-400:]))
735
      retcode = constants.EXIT_FAILURE
736
      ToStdout("You need to fix these nodes first before fixing instances")
737

    
738
    for iname in instances:
739
      if iname in missing:
740
        continue
741
      op = opcodes.OpInstanceActivateDisks(instance_name=iname)
742
      try:
743
        ToStdout("Activating disks for instance '%s'", iname)
744
        SubmitOpCode(op, opts=opts, cl=cl)
745
      except errors.GenericError, err:
746
        nret, msg = FormatError(err)
747
        retcode |= nret
748
        ToStderr("Error activating disks for instance %s: %s", iname, msg)
749

    
750
    if missing:
751
      for iname, ival in missing.iteritems():
752
        all_missing = compat.all(x[0] in bad_nodes for x in ival)
753
        if all_missing:
754
          ToStdout("Instance %s cannot be verified as it lives on"
755
                   " broken nodes", iname)
756
        else:
757
          ToStdout("Instance %s has missing logical volumes:", iname)
758
          ival.sort()
759
          for node, vol in ival:
760
            if node in bad_nodes:
761
              ToStdout("\tbroken node %s /dev/%s", node, vol)
762
            else:
763
              ToStdout("\t%s /dev/%s", node, vol)
764

    
765
      ToStdout("You need to replace or recreate disks for all the above"
766
               " instances if this message persists after fixing broken nodes.")
767
      retcode = constants.EXIT_FAILURE
768
    elif not instances:
769
      ToStdout("No disks need to be activated.")
770

    
771
  return retcode
772

    
773

    
774
def RepairDiskSizes(opts, args):
775
  """Verify sizes of cluster disks.
776

777
  @param opts: the command line options selected by the user
778
  @type args: list
779
  @param args: optional list of instances to restrict check to
780
  @rtype: int
781
  @return: the desired exit code
782

783
  """
784
  op = opcodes.OpClusterRepairDiskSizes(instances=args)
785
  SubmitOpCode(op, opts=opts)
786

    
787

    
788
@UsesRPC
789
def MasterFailover(opts, args):
790
  """Failover the master node.
791

792
  This command, when run on a non-master node, will cause the current
793
  master to cease being master, and the non-master to become new
794
  master.
795

796
  @param opts: the command line options selected by the user
797
  @type args: list
798
  @param args: should be an empty list
799
  @rtype: int
800
  @return: the desired exit code
801

802
  """
803
  if opts.no_voting and not opts.yes_do_it:
804
    usertext = ("This will perform the failover even if most other nodes"
805
                " are down, or if this node is outdated. This is dangerous"
806
                " as it can lead to a non-consistent cluster. Check the"
807
                " gnt-cluster(8) man page before proceeding. Continue?")
808
    if not AskUser(usertext):
809
      return 1
810

    
811
  return bootstrap.MasterFailover(no_voting=opts.no_voting)
812

    
813

    
814
def MasterPing(opts, args):
815
  """Checks if the master is alive.
816

817
  @param opts: the command line options selected by the user
818
  @type args: list
819
  @param args: should be an empty list
820
  @rtype: int
821
  @return: the desired exit code
822

823
  """
824
  try:
825
    cl = GetClient()
826
    cl.QueryClusterInfo()
827
    return 0
828
  except Exception: # pylint: disable=W0703
829
    return 1
830

    
831

    
832
def SearchTags(opts, args):
833
  """Searches the tags on all the cluster.
834

835
  @param opts: the command line options selected by the user
836
  @type args: list
837
  @param args: should contain only one element, the tag pattern
838
  @rtype: int
839
  @return: the desired exit code
840

841
  """
842
  op = opcodes.OpTagsSearch(pattern=args[0])
843
  result = SubmitOpCode(op, opts=opts)
844
  if not result:
845
    return 1
846
  result = list(result)
847
  result.sort()
848
  for path, tag in result:
849
    ToStdout("%s %s", path, tag)
850

    
851

    
852
def _ReadAndVerifyCert(cert_filename, verify_private_key=False):
853
  """Reads and verifies an X509 certificate.
854

855
  @type cert_filename: string
856
  @param cert_filename: the path of the file containing the certificate to
857
                        verify encoded in PEM format
858
  @type verify_private_key: bool
859
  @param verify_private_key: whether to verify the private key in addition to
860
                             the public certificate
861
  @rtype: string
862
  @return: a string containing the PEM-encoded certificate.
863

864
  """
865
  try:
866
    pem = utils.ReadFile(cert_filename)
867
  except IOError, err:
868
    raise errors.X509CertError(cert_filename,
869
                               "Unable to read certificate: %s" % str(err))
870

    
871
  try:
872
    OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, pem)
873
  except Exception, err:
874
    raise errors.X509CertError(cert_filename,
875
                               "Unable to load certificate: %s" % str(err))
876

    
877
  if verify_private_key:
878
    try:
879
      OpenSSL.crypto.load_privatekey(OpenSSL.crypto.FILETYPE_PEM, pem)
880
    except Exception, err:
881
      raise errors.X509CertError(cert_filename,
882
                                 "Unable to load private key: %s" % str(err))
883

    
884
  return pem
885

    
886

    
887
def _RenewCrypto(new_cluster_cert, new_rapi_cert, # pylint: disable=R0911
888
                 rapi_cert_filename, new_spice_cert, spice_cert_filename,
889
                 spice_cacert_filename, new_confd_hmac_key, new_cds,
890
                 cds_filename, force):
891
  """Renews cluster certificates, keys and secrets.
892

893
  @type new_cluster_cert: bool
894
  @param new_cluster_cert: Whether to generate a new cluster certificate
895
  @type new_rapi_cert: bool
896
  @param new_rapi_cert: Whether to generate a new RAPI certificate
897
  @type rapi_cert_filename: string
898
  @param rapi_cert_filename: Path to file containing new RAPI certificate
899
  @type new_spice_cert: bool
900
  @param new_spice_cert: Whether to generate a new SPICE certificate
901
  @type spice_cert_filename: string
902
  @param spice_cert_filename: Path to file containing new SPICE certificate
903
  @type spice_cacert_filename: string
904
  @param spice_cacert_filename: Path to file containing the certificate of the
905
                                CA that signed the SPICE certificate
906
  @type new_confd_hmac_key: bool
907
  @param new_confd_hmac_key: Whether to generate a new HMAC key
908
  @type new_cds: bool
909
  @param new_cds: Whether to generate a new cluster domain secret
910
  @type cds_filename: string
911
  @param cds_filename: Path to file containing new cluster domain secret
912
  @type force: bool
913
  @param force: Whether to ask user for confirmation
914

915
  """
916
  if new_rapi_cert and rapi_cert_filename:
917
    ToStderr("Only one of the --new-rapi-certificate and --rapi-certificate"
918
             " options can be specified at the same time.")
919
    return 1
920

    
921
  if new_cds and cds_filename:
922
    ToStderr("Only one of the --new-cluster-domain-secret and"
923
             " --cluster-domain-secret options can be specified at"
924
             " the same time.")
925
    return 1
926

    
927
  if new_spice_cert and (spice_cert_filename or spice_cacert_filename):
928
    ToStderr("When using --new-spice-certificate, the --spice-certificate"
929
             " and --spice-ca-certificate must not be used.")
930
    return 1
931

    
932
  if bool(spice_cacert_filename) ^ bool(spice_cert_filename):
933
    ToStderr("Both --spice-certificate and --spice-ca-certificate must be"
934
             " specified.")
935
    return 1
936

    
937
  rapi_cert_pem, spice_cert_pem, spice_cacert_pem = (None, None, None)
938
  try:
939
    if rapi_cert_filename:
940
      rapi_cert_pem = _ReadAndVerifyCert(rapi_cert_filename, True)
941
    if spice_cert_filename:
942
      spice_cert_pem = _ReadAndVerifyCert(spice_cert_filename, True)
943
      spice_cacert_pem = _ReadAndVerifyCert(spice_cacert_filename)
944
  except errors.X509CertError, err:
945
    ToStderr("Unable to load X509 certificate from %s: %s", err[0], err[1])
946
    return 1
947

    
948
  if cds_filename:
949
    try:
950
      cds = utils.ReadFile(cds_filename)
951
    except Exception, err: # pylint: disable=W0703
952
      ToStderr("Can't load new cluster domain secret from %s: %s" %
953
               (cds_filename, str(err)))
954
      return 1
955
  else:
956
    cds = None
957

    
958
  if not force:
959
    usertext = ("This requires all daemons on all nodes to be restarted and"
960
                " may take some time. Continue?")
961
    if not AskUser(usertext):
962
      return 1
963

    
964
  def _RenewCryptoInner(ctx):
965
    ctx.feedback_fn("Updating certificates and keys")
966
    bootstrap.GenerateClusterCrypto(new_cluster_cert,
967
                                    new_rapi_cert,
968
                                    new_spice_cert,
969
                                    new_confd_hmac_key,
970
                                    new_cds,
971
                                    rapi_cert_pem=rapi_cert_pem,
972
                                    spice_cert_pem=spice_cert_pem,
973
                                    spice_cacert_pem=spice_cacert_pem,
974
                                    cds=cds)
975

    
976
    files_to_copy = []
977

    
978
    if new_cluster_cert:
979
      files_to_copy.append(pathutils.NODED_CERT_FILE)
980

    
981
    if new_rapi_cert or rapi_cert_pem:
982
      files_to_copy.append(pathutils.RAPI_CERT_FILE)
983

    
984
    if new_spice_cert or spice_cert_pem:
985
      files_to_copy.append(pathutils.SPICE_CERT_FILE)
986
      files_to_copy.append(pathutils.SPICE_CACERT_FILE)
987

    
988
    if new_confd_hmac_key:
989
      files_to_copy.append(pathutils.CONFD_HMAC_KEY)
990

    
991
    if new_cds or cds:
992
      files_to_copy.append(pathutils.CLUSTER_DOMAIN_SECRET_FILE)
993

    
994
    if files_to_copy:
995
      for node_name in ctx.nonmaster_nodes:
996
        ctx.feedback_fn("Copying %s to %s" %
997
                        (", ".join(files_to_copy), node_name))
998
        for file_name in files_to_copy:
999
          ctx.ssh.CopyFileToNode(node_name, file_name)
1000

    
1001
  RunWhileClusterStopped(ToStdout, _RenewCryptoInner)
1002

    
1003
  ToStdout("All requested certificates and keys have been replaced."
1004
           " Running \"gnt-cluster verify\" now is recommended.")
1005

    
1006
  return 0
1007

    
1008

    
1009
def RenewCrypto(opts, args):
1010
  """Renews cluster certificates, keys and secrets.
1011

1012
  """
1013
  return _RenewCrypto(opts.new_cluster_cert,
1014
                      opts.new_rapi_cert,
1015
                      opts.rapi_cert,
1016
                      opts.new_spice_cert,
1017
                      opts.spice_cert,
1018
                      opts.spice_cacert,
1019
                      opts.new_confd_hmac_key,
1020
                      opts.new_cluster_domain_secret,
1021
                      opts.cluster_domain_secret,
1022
                      opts.force)
1023

    
1024

    
1025
def _GetEnabledDiskTemplates(opts):
1026
  """Determine the list of enabled disk templates.
1027

1028
  """
1029
  if opts.enabled_disk_templates:
1030
    return opts.enabled_disk_templates.split(",")
1031
  else:
1032
    return None
1033

    
1034

    
1035
def _GetVgName(opts, enabled_disk_templates):
1036
  """Determine the volume group name.
1037

1038
  @type enabled_disk_templates: list of strings
1039
  @param enabled_disk_templates: cluster-wide enabled disk-templates
1040

1041
  """
1042
  # consistency between vg name and enabled disk templates
1043
  vg_name = None
1044
  if opts.vg_name is not None:
1045
    vg_name = opts.vg_name
1046
  if enabled_disk_templates:
1047
    if vg_name and not utils.IsLvmEnabled(enabled_disk_templates):
1048
      ToStdout("You specified a volume group with --vg-name, but you did not"
1049
               " enable any of the following lvm-based disk templates: %s" %
1050
               utils.CommaJoin(utils.GetLvmDiskTemplates()))
1051
  return vg_name
1052

    
1053

    
1054
def _GetDrbdHelper(opts, enabled_disk_templates):
1055
  """Determine the DRBD usermode helper.
1056

1057
  """
1058
  drbd_helper = opts.drbd_helper
1059
  if enabled_disk_templates:
1060
    drbd_enabled = constants.DT_DRBD8 in enabled_disk_templates
1061
    if not drbd_enabled and opts.drbd_helper:
1062
      ToStdout("You specified a DRBD usermode helper with "
1063
               " --drbd-usermode-helper while DRBD is not enabled.")
1064
  return drbd_helper
1065

    
1066

    
1067
def SetClusterParams(opts, args):
1068
  """Modify the cluster.
1069

1070
  @param opts: the command line options selected by the user
1071
  @type args: list
1072
  @param args: should be an empty list
1073
  @rtype: int
1074
  @return: the desired exit code
1075

1076
  """
1077
  if not (opts.vg_name is not None or
1078
          opts.drbd_helper is not None or
1079
          opts.enabled_hypervisors or opts.hvparams or
1080
          opts.beparams or opts.nicparams or
1081
          opts.ndparams or opts.diskparams or
1082
          opts.candidate_pool_size is not None or
1083
          opts.uid_pool is not None or
1084
          opts.maintain_node_health is not None or
1085
          opts.add_uids is not None or
1086
          opts.remove_uids is not None or
1087
          opts.default_iallocator is not None or
1088
          opts.reserved_lvs is not None or
1089
          opts.master_netdev is not None or
1090
          opts.master_netmask is not None or
1091
          opts.use_external_mip_script is not None or
1092
          opts.prealloc_wipe_disks is not None or
1093
          opts.hv_state or
1094
          opts.enabled_disk_templates or
1095
          opts.disk_state or
1096
          opts.ipolicy_bounds_specs is not None or
1097
          opts.ipolicy_std_specs is not None or
1098
          opts.ipolicy_disk_templates is not None or
1099
          opts.ipolicy_vcpu_ratio is not None or
1100
          opts.ipolicy_spindle_ratio is not None or
1101
          opts.modify_etc_hosts is not None or
1102
          opts.file_storage_dir is not None):
1103
    ToStderr("Please give at least one of the parameters.")
1104
    return 1
1105

    
1106
  if _CheckNoLvmStorageOptDeprecated(opts):
1107
    return 1
1108

    
1109
  enabled_disk_templates = _GetEnabledDiskTemplates(opts)
1110
  vg_name = _GetVgName(opts, enabled_disk_templates)
1111

    
1112
  try:
1113
    drbd_helper = _GetDrbdHelper(opts, enabled_disk_templates)
1114
  except errors.OpPrereqError, e:
1115
    ToStderr(str(e))
1116
    return 1
1117

    
1118
  hvlist = opts.enabled_hypervisors
1119
  if hvlist is not None:
1120
    hvlist = hvlist.split(",")
1121

    
1122
  # a list of (name, dict) we can pass directly to dict() (or [])
1123
  hvparams = dict(opts.hvparams)
1124
  for hv_params in hvparams.values():
1125
    utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1126

    
1127
  diskparams = dict(opts.diskparams)
1128

    
1129
  for dt_params in diskparams.values():
1130
    utils.ForceDictType(dt_params, constants.DISK_DT_TYPES)
1131

    
1132
  beparams = opts.beparams
1133
  utils.ForceDictType(beparams, constants.BES_PARAMETER_COMPAT)
1134

    
1135
  nicparams = opts.nicparams
1136
  utils.ForceDictType(nicparams, constants.NICS_PARAMETER_TYPES)
1137

    
1138
  ndparams = opts.ndparams
1139
  if ndparams is not None:
1140
    utils.ForceDictType(ndparams, constants.NDS_PARAMETER_TYPES)
1141

    
1142
  ipolicy = CreateIPolicyFromOpts(
1143
    minmax_ispecs=opts.ipolicy_bounds_specs,
1144
    std_ispecs=opts.ipolicy_std_specs,
1145
    ipolicy_disk_templates=opts.ipolicy_disk_templates,
1146
    ipolicy_vcpu_ratio=opts.ipolicy_vcpu_ratio,
1147
    ipolicy_spindle_ratio=opts.ipolicy_spindle_ratio,
1148
    )
1149

    
1150
  mnh = opts.maintain_node_health
1151

    
1152
  uid_pool = opts.uid_pool
1153
  if uid_pool is not None:
1154
    uid_pool = uidpool.ParseUidPool(uid_pool)
1155

    
1156
  add_uids = opts.add_uids
1157
  if add_uids is not None:
1158
    add_uids = uidpool.ParseUidPool(add_uids)
1159

    
1160
  remove_uids = opts.remove_uids
1161
  if remove_uids is not None:
1162
    remove_uids = uidpool.ParseUidPool(remove_uids)
1163

    
1164
  if opts.reserved_lvs is not None:
1165
    if opts.reserved_lvs == "":
1166
      opts.reserved_lvs = []
1167
    else:
1168
      opts.reserved_lvs = utils.UnescapeAndSplit(opts.reserved_lvs, sep=",")
1169

    
1170
  if opts.master_netmask is not None:
1171
    try:
1172
      opts.master_netmask = int(opts.master_netmask)
1173
    except ValueError:
1174
      ToStderr("The --master-netmask option expects an int parameter.")
1175
      return 1
1176

    
1177
  ext_ip_script = opts.use_external_mip_script
1178

    
1179
  if opts.disk_state:
1180
    disk_state = utils.FlatToDict(opts.disk_state)
1181
  else:
1182
    disk_state = {}
1183

    
1184
  hv_state = dict(opts.hv_state)
1185

    
1186
  op = opcodes.OpClusterSetParams(
1187
    vg_name=vg_name,
1188
    drbd_helper=drbd_helper,
1189
    enabled_hypervisors=hvlist,
1190
    hvparams=hvparams,
1191
    os_hvp=None,
1192
    beparams=beparams,
1193
    nicparams=nicparams,
1194
    ndparams=ndparams,
1195
    diskparams=diskparams,
1196
    ipolicy=ipolicy,
1197
    candidate_pool_size=opts.candidate_pool_size,
1198
    maintain_node_health=mnh,
1199
    modify_etc_hosts=opts.modify_etc_hosts,
1200
    uid_pool=uid_pool,
1201
    add_uids=add_uids,
1202
    remove_uids=remove_uids,
1203
    default_iallocator=opts.default_iallocator,
1204
    prealloc_wipe_disks=opts.prealloc_wipe_disks,
1205
    master_netdev=opts.master_netdev,
1206
    master_netmask=opts.master_netmask,
1207
    reserved_lvs=opts.reserved_lvs,
1208
    use_external_mip_script=ext_ip_script,
1209
    hv_state=hv_state,
1210
    disk_state=disk_state,
1211
    enabled_disk_templates=enabled_disk_templates,
1212
    force=opts.force,
1213
    file_storage_dir=opts.file_storage_dir,
1214
    )
1215
  SubmitOrSend(op, opts)
1216
  return 0
1217

    
1218

    
1219
def QueueOps(opts, args):
1220
  """Queue operations.
1221

1222
  @param opts: the command line options selected by the user
1223
  @type args: list
1224
  @param args: should contain only one element, the subcommand
1225
  @rtype: int
1226
  @return: the desired exit code
1227

1228
  """
1229
  command = args[0]
1230
  client = GetClient()
1231
  if command in ("drain", "undrain"):
1232
    drain_flag = command == "drain"
1233
    client.SetQueueDrainFlag(drain_flag)
1234
  elif command == "info":
1235
    result = client.QueryConfigValues(["drain_flag"])
1236
    if result[0]:
1237
      val = "set"
1238
    else:
1239
      val = "unset"
1240
    ToStdout("The drain flag is %s" % val)
1241
  else:
1242
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
1243
                               errors.ECODE_INVAL)
1244

    
1245
  return 0
1246

    
1247

    
1248
def _ShowWatcherPause(until):
1249
  if until is None or until < time.time():
1250
    ToStdout("The watcher is not paused.")
1251
  else:
1252
    ToStdout("The watcher is paused until %s.", time.ctime(until))
1253

    
1254

    
1255
def WatcherOps(opts, args):
1256
  """Watcher operations.
1257

1258
  @param opts: the command line options selected by the user
1259
  @type args: list
1260
  @param args: should contain only one element, the subcommand
1261
  @rtype: int
1262
  @return: the desired exit code
1263

1264
  """
1265
  command = args[0]
1266
  client = GetClient()
1267

    
1268
  if command == "continue":
1269
    client.SetWatcherPause(None)
1270
    ToStdout("The watcher is no longer paused.")
1271

    
1272
  elif command == "pause":
1273
    if len(args) < 2:
1274
      raise errors.OpPrereqError("Missing pause duration", errors.ECODE_INVAL)
1275

    
1276
    result = client.SetWatcherPause(time.time() + ParseTimespec(args[1]))
1277
    _ShowWatcherPause(result)
1278

    
1279
  elif command == "info":
1280
    result = client.QueryConfigValues(["watcher_pause"])
1281
    _ShowWatcherPause(result[0])
1282

    
1283
  else:
1284
    raise errors.OpPrereqError("Command '%s' is not valid." % command,
1285
                               errors.ECODE_INVAL)
1286

    
1287
  return 0
1288

    
1289

    
1290
def _OobPower(opts, node_list, power):
1291
  """Puts the node in the list to desired power state.
1292

1293
  @param opts: The command line options selected by the user
1294
  @param node_list: The list of nodes to operate on
1295
  @param power: True if they should be powered on, False otherwise
1296
  @return: The success of the operation (none failed)
1297

1298
  """
1299
  if power:
1300
    command = constants.OOB_POWER_ON
1301
  else:
1302
    command = constants.OOB_POWER_OFF
1303

    
1304
  op = opcodes.OpOobCommand(node_names=node_list,
1305
                            command=command,
1306
                            ignore_status=True,
1307
                            timeout=opts.oob_timeout,
1308
                            power_delay=opts.power_delay)
1309
  result = SubmitOpCode(op, opts=opts)
1310
  errs = 0
1311
  for node_result in result:
1312
    (node_tuple, data_tuple) = node_result
1313
    (_, node_name) = node_tuple
1314
    (data_status, _) = data_tuple
1315
    if data_status != constants.RS_NORMAL:
1316
      assert data_status != constants.RS_UNAVAIL
1317
      errs += 1
1318
      ToStderr("There was a problem changing power for %s, please investigate",
1319
               node_name)
1320

    
1321
  if errs > 0:
1322
    return False
1323

    
1324
  return True
1325

    
1326

    
1327
def _InstanceStart(opts, inst_list, start, no_remember=False):
1328
  """Puts the instances in the list to desired state.
1329

1330
  @param opts: The command line options selected by the user
1331
  @param inst_list: The list of instances to operate on
1332
  @param start: True if they should be started, False for shutdown
1333
  @param no_remember: If the instance state should be remembered
1334
  @return: The success of the operation (none failed)
1335

1336
  """
1337
  if start:
1338
    opcls = opcodes.OpInstanceStartup
1339
    text_submit, text_success, text_failed = ("startup", "started", "starting")
1340
  else:
1341
    opcls = compat.partial(opcodes.OpInstanceShutdown,
1342
                           timeout=opts.shutdown_timeout,
1343
                           no_remember=no_remember)
1344
    text_submit, text_success, text_failed = ("shutdown", "stopped", "stopping")
1345

    
1346
  jex = JobExecutor(opts=opts)
1347

    
1348
  for inst in inst_list:
1349
    ToStdout("Submit %s of instance %s", text_submit, inst)
1350
    op = opcls(instance_name=inst)
1351
    jex.QueueJob(inst, op)
1352

    
1353
  results = jex.GetResults()
1354
  bad_cnt = len([1 for (success, _) in results if not success])
1355

    
1356
  if bad_cnt == 0:
1357
    ToStdout("All instances have been %s successfully", text_success)
1358
  else:
1359
    ToStderr("There were errors while %s instances:\n"
1360
             "%d error(s) out of %d instance(s)", text_failed, bad_cnt,
1361
             len(results))
1362
    return False
1363

    
1364
  return True
1365

    
1366

    
1367
class _RunWhenNodesReachableHelper:
1368
  """Helper class to make shared internal state sharing easier.
1369

1370
  @ivar success: Indicates if all action_cb calls were successful
1371

1372
  """
1373
  def __init__(self, node_list, action_cb, node2ip, port, feedback_fn,
1374
               _ping_fn=netutils.TcpPing, _sleep_fn=time.sleep):
1375
    """Init the object.
1376

1377
    @param node_list: The list of nodes to be reachable
1378
    @param action_cb: Callback called when a new host is reachable
1379
    @type node2ip: dict
1380
    @param node2ip: Node to ip mapping
1381
    @param port: The port to use for the TCP ping
1382
    @param feedback_fn: The function used for feedback
1383
    @param _ping_fn: Function to check reachabilty (for unittest use only)
1384
    @param _sleep_fn: Function to sleep (for unittest use only)
1385

1386
    """
1387
    self.down = set(node_list)
1388
    self.up = set()
1389
    self.node2ip = node2ip
1390
    self.success = True
1391
    self.action_cb = action_cb
1392
    self.port = port
1393
    self.feedback_fn = feedback_fn
1394
    self._ping_fn = _ping_fn
1395
    self._sleep_fn = _sleep_fn
1396

    
1397
  def __call__(self):
1398
    """When called we run action_cb.
1399

1400
    @raises utils.RetryAgain: When there are still down nodes
1401

1402
    """
1403
    if not self.action_cb(self.up):
1404
      self.success = False
1405

    
1406
    if self.down:
1407
      raise utils.RetryAgain()
1408
    else:
1409
      return self.success
1410

    
1411
  def Wait(self, secs):
1412
    """Checks if a host is up or waits remaining seconds.
1413

1414
    @param secs: The secs remaining
1415

1416
    """
1417
    start = time.time()
1418
    for node in self.down:
1419
      if self._ping_fn(self.node2ip[node], self.port, timeout=_EPO_PING_TIMEOUT,
1420
                       live_port_needed=True):
1421
        self.feedback_fn("Node %s became available" % node)
1422
        self.up.add(node)
1423
        self.down -= self.up
1424
        # If we have a node available there is the possibility to run the
1425
        # action callback successfully, therefore we don't wait and return
1426
        return
1427

    
1428
    self._sleep_fn(max(0.0, start + secs - time.time()))
1429

    
1430

    
1431
def _RunWhenNodesReachable(node_list, action_cb, interval):
1432
  """Run action_cb when nodes become reachable.
1433

1434
  @param node_list: The list of nodes to be reachable
1435
  @param action_cb: Callback called when a new host is reachable
1436
  @param interval: The earliest time to retry
1437

1438
  """
1439
  client = GetClient()
1440
  cluster_info = client.QueryClusterInfo()
1441
  if cluster_info["primary_ip_version"] == constants.IP4_VERSION:
1442
    family = netutils.IPAddress.family
1443
  else:
1444
    family = netutils.IP6Address.family
1445

    
1446
  node2ip = dict((node, netutils.GetHostname(node, family=family).ip)
1447
                 for node in node_list)
1448

    
1449
  port = netutils.GetDaemonPort(constants.NODED)
1450
  helper = _RunWhenNodesReachableHelper(node_list, action_cb, node2ip, port,
1451
                                        ToStdout)
1452

    
1453
  try:
1454
    return utils.Retry(helper, interval, _EPO_REACHABLE_TIMEOUT,
1455
                       wait_fn=helper.Wait)
1456
  except utils.RetryTimeout:
1457
    ToStderr("Time exceeded while waiting for nodes to become reachable"
1458
             " again:\n  - %s", "  - ".join(helper.down))
1459
    return False
1460

    
1461

    
1462
def _MaybeInstanceStartup(opts, inst_map, nodes_online,
1463
                          _instance_start_fn=_InstanceStart):
1464
  """Start the instances conditional based on node_states.
1465

1466
  @param opts: The command line options selected by the user
1467
  @param inst_map: A dict of inst -> nodes mapping
1468
  @param nodes_online: A list of nodes online
1469
  @param _instance_start_fn: Callback to start instances (unittest use only)
1470
  @return: Success of the operation on all instances
1471

1472
  """
1473
  start_inst_list = []
1474
  for (inst, nodes) in inst_map.items():
1475
    if not (nodes - nodes_online):
1476
      # All nodes the instance lives on are back online
1477
      start_inst_list.append(inst)
1478

    
1479
  for inst in start_inst_list:
1480
    del inst_map[inst]
1481

    
1482
  if start_inst_list:
1483
    return _instance_start_fn(opts, start_inst_list, True)
1484

    
1485
  return True
1486

    
1487

    
1488
def _EpoOn(opts, full_node_list, node_list, inst_map):
1489
  """Does the actual power on.
1490

1491
  @param opts: The command line options selected by the user
1492
  @param full_node_list: All nodes to operate on (includes nodes not supporting
1493
                         OOB)
1494
  @param node_list: The list of nodes to operate on (all need to support OOB)
1495
  @param inst_map: A dict of inst -> nodes mapping
1496
  @return: The desired exit status
1497

1498
  """
1499
  if node_list and not _OobPower(opts, node_list, False):
1500
    ToStderr("Not all nodes seem to get back up, investigate and start"
1501
             " manually if needed")
1502

    
1503
  # Wait for the nodes to be back up
1504
  action_cb = compat.partial(_MaybeInstanceStartup, opts, dict(inst_map))
1505

    
1506
  ToStdout("Waiting until all nodes are available again")
1507
  if not _RunWhenNodesReachable(full_node_list, action_cb, _EPO_PING_INTERVAL):
1508
    ToStderr("Please investigate and start stopped instances manually")
1509
    return constants.EXIT_FAILURE
1510

    
1511
  return constants.EXIT_SUCCESS
1512

    
1513

    
1514
def _EpoOff(opts, node_list, inst_map):
1515
  """Does the actual power off.
1516

1517
  @param opts: The command line options selected by the user
1518
  @param node_list: The list of nodes to operate on (all need to support OOB)
1519
  @param inst_map: A dict of inst -> nodes mapping
1520
  @return: The desired exit status
1521

1522
  """
1523
  if not _InstanceStart(opts, inst_map.keys(), False, no_remember=True):
1524
    ToStderr("Please investigate and stop instances manually before continuing")
1525
    return constants.EXIT_FAILURE
1526

    
1527
  if not node_list:
1528
    return constants.EXIT_SUCCESS
1529

    
1530
  if _OobPower(opts, node_list, False):
1531
    return constants.EXIT_SUCCESS
1532
  else:
1533
    return constants.EXIT_FAILURE
1534

    
1535

    
1536
def Epo(opts, args, cl=None, _on_fn=_EpoOn, _off_fn=_EpoOff,
1537
        _confirm_fn=ConfirmOperation,
1538
        _stdout_fn=ToStdout, _stderr_fn=ToStderr):
1539
  """EPO operations.
1540

1541
  @param opts: the command line options selected by the user
1542
  @type args: list
1543
  @param args: should contain only one element, the subcommand
1544
  @rtype: int
1545
  @return: the desired exit code
1546

1547
  """
1548
  if opts.groups and opts.show_all:
1549
    _stderr_fn("Only one of --groups or --all are allowed")
1550
    return constants.EXIT_FAILURE
1551
  elif args and opts.show_all:
1552
    _stderr_fn("Arguments in combination with --all are not allowed")
1553
    return constants.EXIT_FAILURE
1554

    
1555
  if cl is None:
1556
    cl = GetClient()
1557

    
1558
  if opts.groups:
1559
    node_query_list = \
1560
      itertools.chain(*cl.QueryGroups(args, ["node_list"], False))
1561
  else:
1562
    node_query_list = args
1563

    
1564
  result = cl.QueryNodes(node_query_list, ["name", "master", "pinst_list",
1565
                                           "sinst_list", "powered", "offline"],
1566
                         False)
1567

    
1568
  all_nodes = map(compat.fst, result)
1569
  node_list = []
1570
  inst_map = {}
1571
  for (node, master, pinsts, sinsts, powered, offline) in result:
1572
    if not offline:
1573
      for inst in (pinsts + sinsts):
1574
        if inst in inst_map:
1575
          if not master:
1576
            inst_map[inst].add(node)
1577
        elif master:
1578
          inst_map[inst] = set()
1579
        else:
1580
          inst_map[inst] = set([node])
1581

    
1582
    if master and opts.on:
1583
      # We ignore the master for turning on the machines, in fact we are
1584
      # already operating on the master at this point :)
1585
      continue
1586
    elif master and not opts.show_all:
1587
      _stderr_fn("%s is the master node, please do a master-failover to another"
1588
                 " node not affected by the EPO or use --all if you intend to"
1589
                 " shutdown the whole cluster", node)
1590
      return constants.EXIT_FAILURE
1591
    elif powered is None:
1592
      _stdout_fn("Node %s does not support out-of-band handling, it can not be"
1593
                 " handled in a fully automated manner", node)
1594
    elif powered == opts.on:
1595
      _stdout_fn("Node %s is already in desired power state, skipping", node)
1596
    elif not offline or (offline and powered):
1597
      node_list.append(node)
1598

    
1599
  if not (opts.force or _confirm_fn(all_nodes, "nodes", "epo")):
1600
    return constants.EXIT_FAILURE
1601

    
1602
  if opts.on:
1603
    return _on_fn(opts, all_nodes, node_list, inst_map)
1604
  else:
1605
    return _off_fn(opts, node_list, inst_map)
1606

    
1607

    
1608
def _GetCreateCommand(info):
1609
  buf = StringIO()
1610
  buf.write("gnt-cluster init")
1611
  PrintIPolicyCommand(buf, info["ipolicy"], False)
1612
  buf.write(" ")
1613
  buf.write(info["name"])
1614
  return buf.getvalue()
1615

    
1616

    
1617
def ShowCreateCommand(opts, args):
1618
  """Shows the command that can be used to re-create the cluster.
1619

1620
  Currently it works only for ipolicy specs.
1621

1622
  """
1623
  cl = GetClient(query=True)
1624
  result = cl.QueryClusterInfo()
1625
  ToStdout(_GetCreateCommand(result))
1626

    
1627

    
1628
def _RunCommandAndReport(cmd):
1629
  """Run a command and report its output, iff it failed.
1630

1631
  @param cmd: the command to execute
1632
  @type cmd: list
1633
  @rtype: bool
1634
  @return: False, if the execution failed.
1635

1636
  """
1637
  result = utils.RunCmd(cmd)
1638
  if result.failed:
1639
    ToStderr("Command %s failed: %s; Output %s" %
1640
             (cmd, result.fail_reason, result.output))
1641
    return False
1642
  return True
1643

    
1644

    
1645
def _VerifyCommand(cmd):
1646
  """Verify that a given command succeeds on all online nodes.
1647

1648
  As this function is intended to run during upgrades, it
1649
  is implemented in such a way that it still works, if all Ganeti
1650
  daemons are down.
1651

1652
  @param cmd: the command to execute
1653
  @type cmd: list
1654
  @rtype: list
1655
  @return: the list of node names that are online where
1656
      the command failed.
1657

1658
  """
1659
  command = utils.text.ShellQuoteArgs([str(val) for val in cmd])
1660

    
1661
  nodes = ssconf.SimpleStore().GetOnlineNodeList()
1662
  master_node = ssconf.SimpleStore().GetMasterNode()
1663
  cluster_name = ssconf.SimpleStore().GetClusterName()
1664

    
1665
  # If master node is in 'nodes', make sure master node is at list end
1666
  if master_node in nodes:
1667
    nodes.remove(master_node)
1668
    nodes.append(master_node)
1669

    
1670
  failed = []
1671

    
1672
  srun = ssh.SshRunner(cluster_name=cluster_name)
1673
  for name in nodes:
1674
    result = srun.Run(name, constants.SSH_LOGIN_USER, command)
1675
    if result.exit_code != 0:
1676
      failed.append(name)
1677

    
1678
  return failed
1679

    
1680

    
1681
def _VerifyVersionInstalled(versionstring):
1682
  """Verify that the given version of ganeti is installed on all online nodes.
1683

1684
  Do nothing, if this is the case, otherwise print an appropriate
1685
  message to stderr.
1686

1687
  @param versionstring: the version to check for
1688
  @type versionstring: string
1689
  @rtype: bool
1690
  @return: True, if the version is installed on all online nodes
1691

1692
  """
1693
  badnodes = _VerifyCommand(["test", "-d",
1694
                             os.path.join(pathutils.PKGLIBDIR, versionstring)])
1695
  if badnodes:
1696
    ToStderr("Ganeti version %s not installed on nodes %s"
1697
             % (versionstring, ", ".join(badnodes)))
1698
    return False
1699

    
1700
  return True
1701

    
1702

    
1703
def _GetRunning():
1704
  """Determine the list of running jobs.
1705

1706
  @rtype: list
1707
  @return: the number of jobs still running
1708

1709
  """
1710
  cl = GetClient()
1711
  qfilter = qlang.MakeSimpleFilter("status",
1712
                                   frozenset([constants.JOB_STATUS_RUNNING]))
1713
  return len(cl.Query(constants.QR_JOB, [], qfilter).data)
1714

    
1715

    
1716
def _SetGanetiVersion(versionstring):
1717
  """Set the active version of ganeti to the given versionstring
1718

1719
  @type versionstring: string
1720
  @rtype: list
1721
  @return: the list of nodes where the version change failed
1722

1723
  """
1724
  failed = []
1725
  failed.extend(_VerifyCommand(
1726
      ["rm", "-f", os.path.join(pathutils.SYSCONFDIR, "ganeti/lib")]))
1727
  failed.extend(_VerifyCommand(
1728
      ["ln", "-s", "-f", os.path.join(pathutils.PKGLIBDIR, versionstring),
1729
       os.path.join(pathutils.SYSCONFDIR, "ganeti/lib")]))
1730
  failed.extend(_VerifyCommand(
1731
      ["rm", "-f", os.path.join(pathutils.SYSCONFDIR, "ganeti/share")]))
1732
  failed.extend(_VerifyCommand(
1733
      ["ln", "-s", "-f", os.path.join(pathutils.SHAREDIR, versionstring),
1734
       os.path.join(pathutils.SYSCONFDIR, "ganeti/share")]))
1735
  return list(set(failed))
1736

    
1737

    
1738
def _ExecuteCommands(fns):
1739
  """Execute a list of functions, in reverse order.
1740

1741
  @type fns: list of functions.
1742
  @param fns: the functions to be executed.
1743

1744
  """
1745
  for fn in reversed(fns):
1746
    fn()
1747

    
1748

    
1749
# pylint: disable=R0911
1750
def UpgradeGanetiCommand(opts, args):
1751
  """Upgrade a cluster to a new ganeti version.
1752

1753
  @param opts: the command line options selected by the user
1754
  @type args: list
1755
  @param args: should be an empty list
1756
  @rtype: int
1757
  @return: the desired exit code
1758

1759
  """
1760
  if ((not opts.resume and opts.to is None)
1761
      or (opts.resume and opts.to is not None)):
1762
    ToStderr("Precisely one of the options --to and --resume"
1763
             " has to be given")
1764
    return 1
1765

    
1766
  if opts.resume:
1767
    # TODO: implement
1768
    ToStderr("The --resume mode is not yet implemented")
1769
    return 1
1770

    
1771
  rollback = []
1772

    
1773
  versionstring = opts.to
1774
  version = utils.version.ParseVersion(versionstring)
1775
  if version is None:
1776
    ToStderr("Could not parse version string %s" % versionstring)
1777
    return 1
1778

    
1779
  msg = utils.version.UpgradeRange(version)
1780
  if msg is not None:
1781
    ToStderr("Cannot upgrade to %s: %s" % (versionstring, msg))
1782
    return 1
1783

    
1784
  downgrade = utils.version.ShouldCfgdowngrade(version)
1785

    
1786
  if not _VerifyVersionInstalled(versionstring):
1787
    return 1
1788

    
1789
  # TODO: write intent-to-upgrade file
1790

    
1791
  ToStdout("Draining queue")
1792
  client = GetClient()
1793
  client.SetQueueDrainFlag(True)
1794

    
1795
  rollback.append(lambda: GetClient().SetQueueDrainFlag(False))
1796

    
1797
  if utils.SimpleRetry(0, _GetRunning,
1798
                       constants.UPGRADE_QUEUE_POLL_INTERVAL,
1799
                       constants.UPGRADE_QUEUE_DRAIN_TIMEOUT):
1800
    ToStderr("Failed to completely empty the queue.")
1801
    _ExecuteCommands(rollback)
1802
    return 1
1803

    
1804
  ToStdout("Stopping daemons on master node.")
1805
  if not _RunCommandAndReport([pathutils.DAEMON_UTIL, "stop-all"]):
1806
    _ExecuteCommands(rollback)
1807
    return 1
1808

    
1809
  if not _VerifyVersionInstalled(versionstring):
1810
    utils.RunCmd([pathutils.DAEMON_UTIL, "start-all"])
1811
    _ExecuteCommands(rollback)
1812
    return 1
1813

    
1814
  ToStdout("Stopping daemons everywhere.")
1815
  rollback.append(lambda: _VerifyCommand([pathutils.DAEMON_UTIL, "start-all"]))
1816
  badnodes = _VerifyCommand([pathutils.DAEMON_UTIL, "stop-all"])
1817
  if badnodes:
1818
    ToStderr("Failed to stop daemons on %s." % (", ".join(badnodes),))
1819
    _ExecuteCommands(rollback)
1820
    return 1
1821

    
1822
  backuptar = os.path.join(pathutils.LOCALSTATEDIR,
1823
                           "lib/ganeti%d.tar" % time.time())
1824
  ToStdout("Backing up configuration as %s" % backuptar)
1825
  if not _RunCommandAndReport(["tar", "cf", backuptar,
1826
                               pathutils.DATA_DIR]):
1827
    _ExecuteCommands(rollback)
1828
    return 1
1829

    
1830
  if downgrade:
1831
    ToStdout("Downgrading configuration")
1832
    if not _RunCommandAndReport([pathutils.CFGUPGRADE, "--downgrade", "-f"]):
1833
      _ExecuteCommands(rollback)
1834
      return 1
1835

    
1836
  # Configuration change is the point of no return. From then onwards, it is
1837
  # safer to push through the up/dowgrade than to try to roll it back.
1838

    
1839
  returnvalue = 0
1840

    
1841
  ToStdout("Switching to version %s on all nodes" % versionstring)
1842
  rollback.append(lambda: _SetGanetiVersion(constants.DIR_VERSION))
1843
  badnodes = _SetGanetiVersion(versionstring)
1844
  if badnodes:
1845
    ToStderr("Failed to switch to Ganeti version %s on nodes %s"
1846
             % (versionstring, ", ".join(badnodes)))
1847
    if not downgrade:
1848
      _ExecuteCommands(rollback)
1849
      return 1
1850

    
1851
  # Now that we have changed to the new version of Ganeti we should
1852
  # not communicate over luxi any more, as luxi might have changed in
1853
  # incompatible ways. Therefore, manually call the corresponding ganeti
1854
  # commands using their canonical (version independent) path.
1855

    
1856
  if not downgrade:
1857
    ToStdout("Upgrading configuration")
1858
    if not _RunCommandAndReport([pathutils.CFGUPGRADE, "-f"]):
1859
      _ExecuteCommands(rollback)
1860
      return 1
1861

    
1862
  ToStdout("Starting daemons everywhere.")
1863
  badnodes = _VerifyCommand([pathutils.DAEMON_UTIL, "start-all"])
1864
  if badnodes:
1865
    ToStderr("Warning: failed to start daemons on %s." % (", ".join(badnodes),))
1866
    returnvalue = 1
1867

    
1868
  ToStdout("Ensuring directories everywhere.")
1869
  badnodes = _VerifyCommand([pathutils.ENSURE_DIRS])
1870
  if badnodes:
1871
    ToStderr("Warning: failed to ensure directories on %s." %
1872
             (", ".join(badnodes)))
1873
    returnvalue = 1
1874

    
1875
  ToStdout("Redistributing the configuration.")
1876
  if not _RunCommandAndReport(["gnt-cluster", "redist-conf", "--yes-do-it"]):
1877
    returnvalue = 1
1878

    
1879
  ToStdout("Restarting daemons everywhere.")
1880
  badnodes = _VerifyCommand([pathutils.DAEMON_UTIL, "stop-all"])
1881
  badnodes.extend(_VerifyCommand([pathutils.DAEMON_UTIL, "start-all"]))
1882
  if badnodes:
1883
    ToStderr("Warning: failed to start daemons on %s." %
1884
             (", ".join(list(set(badnodes))),))
1885
    returnvalue = 1
1886

    
1887
  ToStdout("Undraining the queue.")
1888
  if not _RunCommandAndReport(["gnt-cluster", "queue", "undrain"]):
1889
    returnvalue = 1
1890

    
1891
  # TODO: write intent-to-upgrade file
1892

    
1893
  ToStdout("Verifying cluster.")
1894
  if not _RunCommandAndReport(["gnt-cluster", "verify"]):
1895
    returnvalue = 1
1896

    
1897
  return returnvalue
1898

    
1899

    
1900
commands = {
1901
  "init": (
1902
    InitCluster, [ArgHost(min=1, max=1)],
1903
    [BACKEND_OPT, CP_SIZE_OPT, ENABLED_HV_OPT, GLOBAL_FILEDIR_OPT,
1904
     HVLIST_OPT, MAC_PREFIX_OPT, MASTER_NETDEV_OPT, MASTER_NETMASK_OPT,
1905
     NIC_PARAMS_OPT, NOLVM_STORAGE_OPT, NOMODIFY_ETCHOSTS_OPT,
1906
     NOMODIFY_SSH_SETUP_OPT, SECONDARY_IP_OPT, VG_NAME_OPT,
1907
     MAINTAIN_NODE_HEALTH_OPT, UIDPOOL_OPT, DRBD_HELPER_OPT,
1908
     DEFAULT_IALLOCATOR_OPT, PRIMARY_IP_VERSION_OPT, PREALLOC_WIPE_DISKS_OPT,
1909
     NODE_PARAMS_OPT, GLOBAL_SHARED_FILEDIR_OPT, USE_EXTERNAL_MIP_SCRIPT,
1910
     DISK_PARAMS_OPT, HV_STATE_OPT, DISK_STATE_OPT, ENABLED_DISK_TEMPLATES_OPT,
1911
     IPOLICY_STD_SPECS_OPT] + INSTANCE_POLICY_OPTS + SPLIT_ISPECS_OPTS,
1912
    "[opts...] <cluster_name>", "Initialises a new cluster configuration"),
1913
  "destroy": (
1914
    DestroyCluster, ARGS_NONE, [YES_DOIT_OPT],
1915
    "", "Destroy cluster"),
1916
  "rename": (
1917
    RenameCluster, [ArgHost(min=1, max=1)],
1918
    [FORCE_OPT, DRY_RUN_OPT],
1919
    "<new_name>",
1920
    "Renames the cluster"),
1921
  "redist-conf": (
1922
    RedistributeConfig, ARGS_NONE, SUBMIT_OPTS +
1923
    [DRY_RUN_OPT, PRIORITY_OPT, FORCE_DISTRIBUTION],
1924
    "", "Forces a push of the configuration file and ssconf files"
1925
    " to the nodes in the cluster"),
1926
  "verify": (
1927
    VerifyCluster, ARGS_NONE,
1928
    [VERBOSE_OPT, DEBUG_SIMERR_OPT, ERROR_CODES_OPT, NONPLUS1_OPT,
1929
     DRY_RUN_OPT, PRIORITY_OPT, NODEGROUP_OPT, IGNORE_ERRORS_OPT],
1930
    "", "Does a check on the cluster configuration"),
1931
  "verify-disks": (
1932
    VerifyDisks, ARGS_NONE, [PRIORITY_OPT],
1933
    "", "Does a check on the cluster disk status"),
1934
  "repair-disk-sizes": (
1935
    RepairDiskSizes, ARGS_MANY_INSTANCES, [DRY_RUN_OPT, PRIORITY_OPT],
1936
    "[instance...]", "Updates mismatches in recorded disk sizes"),
1937
  "master-failover": (
1938
    MasterFailover, ARGS_NONE, [NOVOTING_OPT, FORCE_FAILOVER],
1939
    "", "Makes the current node the master"),
1940
  "master-ping": (
1941
    MasterPing, ARGS_NONE, [],
1942
    "", "Checks if the master is alive"),
1943
  "version": (
1944
    ShowClusterVersion, ARGS_NONE, [],
1945
    "", "Shows the cluster version"),
1946
  "getmaster": (
1947
    ShowClusterMaster, ARGS_NONE, [],
1948
    "", "Shows the cluster master"),
1949
  "copyfile": (
1950
    ClusterCopyFile, [ArgFile(min=1, max=1)],
1951
    [NODE_LIST_OPT, USE_REPL_NET_OPT, NODEGROUP_OPT],
1952
    "[-n node...] <filename>", "Copies a file to all (or only some) nodes"),
1953
  "command": (
1954
    RunClusterCommand, [ArgCommand(min=1)],
1955
    [NODE_LIST_OPT, NODEGROUP_OPT, SHOW_MACHINE_OPT, FAILURE_ONLY_OPT],
1956
    "[-n node...] <command>", "Runs a command on all (or only some) nodes"),
1957
  "info": (
1958
    ShowClusterConfig, ARGS_NONE, [ROMAN_OPT],
1959
    "[--roman]", "Show cluster configuration"),
1960
  "list-tags": (
1961
    ListTags, ARGS_NONE, [], "", "List the tags of the cluster"),
1962
  "add-tags": (
1963
    AddTags, [ArgUnknown()], [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
1964
    "tag...", "Add tags to the cluster"),
1965
  "remove-tags": (
1966
    RemoveTags, [ArgUnknown()], [TAG_SRC_OPT, PRIORITY_OPT] + SUBMIT_OPTS,
1967
    "tag...", "Remove tags from the cluster"),
1968
  "search-tags": (
1969
    SearchTags, [ArgUnknown(min=1, max=1)], [PRIORITY_OPT], "",
1970
    "Searches the tags on all objects on"
1971
    " the cluster for a given pattern (regex)"),
1972
  "queue": (
1973
    QueueOps,
1974
    [ArgChoice(min=1, max=1, choices=["drain", "undrain", "info"])],
1975
    [], "drain|undrain|info", "Change queue properties"),
1976
  "watcher": (
1977
    WatcherOps,
1978
    [ArgChoice(min=1, max=1, choices=["pause", "continue", "info"]),
1979
     ArgSuggest(min=0, max=1, choices=["30m", "1h", "4h"])],
1980
    [],
1981
    "{pause <timespec>|continue|info}", "Change watcher properties"),
1982
  "modify": (
1983
    SetClusterParams, ARGS_NONE,
1984
    [FORCE_OPT,
1985
     BACKEND_OPT, CP_SIZE_OPT, ENABLED_HV_OPT, HVLIST_OPT, MASTER_NETDEV_OPT,
1986
     MASTER_NETMASK_OPT, NIC_PARAMS_OPT, NOLVM_STORAGE_OPT, VG_NAME_OPT,
1987
     MAINTAIN_NODE_HEALTH_OPT, UIDPOOL_OPT, ADD_UIDS_OPT, REMOVE_UIDS_OPT,
1988
     DRBD_HELPER_OPT, DEFAULT_IALLOCATOR_OPT,
1989
     RESERVED_LVS_OPT, DRY_RUN_OPT, PRIORITY_OPT, PREALLOC_WIPE_DISKS_OPT,
1990
     NODE_PARAMS_OPT, USE_EXTERNAL_MIP_SCRIPT, DISK_PARAMS_OPT, HV_STATE_OPT,
1991
     DISK_STATE_OPT] + SUBMIT_OPTS +
1992
     [ENABLED_DISK_TEMPLATES_OPT, IPOLICY_STD_SPECS_OPT, MODIFY_ETCHOSTS_OPT] +
1993
     INSTANCE_POLICY_OPTS + [GLOBAL_FILEDIR_OPT],
1994
    "[opts...]",
1995
    "Alters the parameters of the cluster"),
1996
  "renew-crypto": (
1997
    RenewCrypto, ARGS_NONE,
1998
    [NEW_CLUSTER_CERT_OPT, NEW_RAPI_CERT_OPT, RAPI_CERT_OPT,
1999
     NEW_CONFD_HMAC_KEY_OPT, FORCE_OPT,
2000
     NEW_CLUSTER_DOMAIN_SECRET_OPT, CLUSTER_DOMAIN_SECRET_OPT,
2001
     NEW_SPICE_CERT_OPT, SPICE_CERT_OPT, SPICE_CACERT_OPT],
2002
    "[opts...]",
2003
    "Renews cluster certificates, keys and secrets"),
2004
  "epo": (
2005
    Epo, [ArgUnknown()],
2006
    [FORCE_OPT, ON_OPT, GROUPS_OPT, ALL_OPT, OOB_TIMEOUT_OPT,
2007
     SHUTDOWN_TIMEOUT_OPT, POWER_DELAY_OPT],
2008
    "[opts...] [args]",
2009
    "Performs an emergency power-off on given args"),
2010
  "activate-master-ip": (
2011
    ActivateMasterIp, ARGS_NONE, [], "", "Activates the master IP"),
2012
  "deactivate-master-ip": (
2013
    DeactivateMasterIp, ARGS_NONE, [CONFIRM_OPT], "",
2014
    "Deactivates the master IP"),
2015
  "show-ispecs-cmd": (
2016
    ShowCreateCommand, ARGS_NONE, [], "",
2017
    "Show the command line to re-create the cluster"),
2018
  "upgrade": (
2019
    UpgradeGanetiCommand, ARGS_NONE, [TO_OPT, RESUME_OPT], "",
2020
    "Upgrade (or downgrade) to a new Ganeti version"),
2021
  }
2022

    
2023

    
2024
#: dictionary with aliases for commands
2025
aliases = {
2026
  "masterfailover": "master-failover",
2027
  "show": "info",
2028
}
2029

    
2030

    
2031
def Main():
2032
  return GenericMain(commands, override={"tag_type": constants.TAG_CLUSTER},
2033
                     aliases=aliases)