Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 3b01286e

History | View | Annotate | Download (379.7 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008, 2009, 2010 Google Inc.
5
#
6
# This program is free software; you can redistribute it and/or modify
7
# it under the terms of the GNU General Public License as published by
8
# the Free Software Foundation; either version 2 of the License, or
9
# (at your option) any later version.
10
#
11
# This program is distributed in the hope that it will be useful, but
12
# WITHOUT ANY WARRANTY; without even the implied warranty of
13
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14
# General Public License for more details.
15
#
16
# You should have received a copy of the GNU General Public License
17
# along with this program; if not, write to the Free Software
18
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19
# 02110-1301, USA.
20

    
21

    
22
"""Module implementing the master-side code."""
23

    
24
# pylint: disable-msg=W0201,C0302
25

    
26
# W0201 since most LU attributes are defined in CheckPrereq or similar
27
# functions
28

    
29
# C0302: since we have waaaay to many lines in this module
30

    
31
import os
32
import os.path
33
import time
34
import re
35
import platform
36
import logging
37
import copy
38
import OpenSSL
39
import socket
40
import tempfile
41
import shutil
42

    
43
from ganeti import ssh
44
from ganeti import utils
45
from ganeti import errors
46
from ganeti import hypervisor
47
from ganeti import locking
48
from ganeti import constants
49
from ganeti import objects
50
from ganeti import serializer
51
from ganeti import ssconf
52
from ganeti import uidpool
53
from ganeti import compat
54
from ganeti import masterd
55
from ganeti import netutils
56
from ganeti import ht
57

    
58
import ganeti.masterd.instance # pylint: disable-msg=W0611
59

    
60
# Common opcode attributes
61

    
62
#: output fields for a query operation
63
_POutputFields = ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString))
64

    
65

    
66
#: the shutdown timeout
67
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
68
                     ht.TPositiveInt)
69

    
70
#: the force parameter
71
_PForce = ("force", False, ht.TBool)
72

    
73
#: a required instance name (for single-instance LUs)
74
_PInstanceName = ("instance_name", ht.NoDefault, ht.TNonEmptyString)
75

    
76
#: Whether to ignore offline nodes
77
_PIgnoreOfflineNodes = ("ignore_offline_nodes", False, ht.TBool)
78

    
79
#: a required node name (for single-node LUs)
80
_PNodeName = ("node_name", ht.NoDefault, ht.TNonEmptyString)
81

    
82
#: the migration type (live/non-live)
83
_PMigrationMode = ("mode", None,
84
                   ht.TOr(ht.TNone, ht.TElemOf(constants.HT_MIGRATION_MODES)))
85

    
86
#: the obsolete 'live' mode (boolean)
87
_PMigrationLive = ("live", None, ht.TMaybeBool)
88

    
89

    
90
# End types
91
class LogicalUnit(object):
92
  """Logical Unit base class.
93

94
  Subclasses must follow these rules:
95
    - implement ExpandNames
96
    - implement CheckPrereq (except when tasklets are used)
97
    - implement Exec (except when tasklets are used)
98
    - implement BuildHooksEnv
99
    - redefine HPATH and HTYPE
100
    - optionally redefine their run requirements:
101
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
102

103
  Note that all commands require root permissions.
104

105
  @ivar dry_run_result: the value (if any) that will be returned to the caller
106
      in dry-run mode (signalled by opcode dry_run parameter)
107
  @cvar _OP_PARAMS: a list of opcode attributes, their defaults values
108
      they should get if not already defined, and types they must match
109

110
  """
111
  HPATH = None
112
  HTYPE = None
113
  _OP_PARAMS = []
114
  REQ_BGL = True
115

    
116
  def __init__(self, processor, op, context, rpc):
117
    """Constructor for LogicalUnit.
118

119
    This needs to be overridden in derived classes in order to check op
120
    validity.
121

122
    """
123
    self.proc = processor
124
    self.op = op
125
    self.cfg = context.cfg
126
    self.context = context
127
    self.rpc = rpc
128
    # Dicts used to declare locking needs to mcpu
129
    self.needed_locks = None
130
    self.acquired_locks = {}
131
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
132
    self.add_locks = {}
133
    self.remove_locks = {}
134
    # Used to force good behavior when calling helper functions
135
    self.recalculate_locks = {}
136
    self.__ssh = None
137
    # logging
138
    self.Log = processor.Log # pylint: disable-msg=C0103
139
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
140
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
141
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
142
    # support for dry-run
143
    self.dry_run_result = None
144
    # support for generic debug attribute
145
    if (not hasattr(self.op, "debug_level") or
146
        not isinstance(self.op.debug_level, int)):
147
      self.op.debug_level = 0
148

    
149
    # Tasklets
150
    self.tasklets = None
151

    
152
    # The new kind-of-type-system
153
    op_id = self.op.OP_ID
154
    for attr_name, aval, test in self._OP_PARAMS:
155
      if not hasattr(op, attr_name):
156
        if aval == ht.NoDefault:
157
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
158
                                     (op_id, attr_name), errors.ECODE_INVAL)
159
        else:
160
          if callable(aval):
161
            dval = aval()
162
          else:
163
            dval = aval
164
          setattr(self.op, attr_name, dval)
165
      attr_val = getattr(op, attr_name)
166
      if test == ht.NoType:
167
        # no tests here
168
        continue
169
      if not callable(test):
170
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
171
                                     " given type is not a proper type (%s)" %
172
                                     (op_id, attr_name, test))
173
      if not test(attr_val):
174
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
175
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
176
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
177
                                   (op_id, attr_name), errors.ECODE_INVAL)
178

    
179
    self.CheckArguments()
180

    
181
  def __GetSSH(self):
182
    """Returns the SshRunner object
183

184
    """
185
    if not self.__ssh:
186
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
187
    return self.__ssh
188

    
189
  ssh = property(fget=__GetSSH)
190

    
191
  def CheckArguments(self):
192
    """Check syntactic validity for the opcode arguments.
193

194
    This method is for doing a simple syntactic check and ensure
195
    validity of opcode parameters, without any cluster-related
196
    checks. While the same can be accomplished in ExpandNames and/or
197
    CheckPrereq, doing these separate is better because:
198

199
      - ExpandNames is left as as purely a lock-related function
200
      - CheckPrereq is run after we have acquired locks (and possible
201
        waited for them)
202

203
    The function is allowed to change the self.op attribute so that
204
    later methods can no longer worry about missing parameters.
205

206
    """
207
    pass
208

    
209
  def ExpandNames(self):
210
    """Expand names for this LU.
211

212
    This method is called before starting to execute the opcode, and it should
213
    update all the parameters of the opcode to their canonical form (e.g. a
214
    short node name must be fully expanded after this method has successfully
215
    completed). This way locking, hooks, logging, ecc. can work correctly.
216

217
    LUs which implement this method must also populate the self.needed_locks
218
    member, as a dict with lock levels as keys, and a list of needed lock names
219
    as values. Rules:
220

221
      - use an empty dict if you don't need any lock
222
      - if you don't need any lock at a particular level omit that level
223
      - don't put anything for the BGL level
224
      - if you want all locks at a level use locking.ALL_SET as a value
225

226
    If you need to share locks (rather than acquire them exclusively) at one
227
    level you can modify self.share_locks, setting a true value (usually 1) for
228
    that level. By default locks are not shared.
229

230
    This function can also define a list of tasklets, which then will be
231
    executed in order instead of the usual LU-level CheckPrereq and Exec
232
    functions, if those are not defined by the LU.
233

234
    Examples::
235

236
      # Acquire all nodes and one instance
237
      self.needed_locks = {
238
        locking.LEVEL_NODE: locking.ALL_SET,
239
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
240
      }
241
      # Acquire just two nodes
242
      self.needed_locks = {
243
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
244
      }
245
      # Acquire no locks
246
      self.needed_locks = {} # No, you can't leave it to the default value None
247

248
    """
249
    # The implementation of this method is mandatory only if the new LU is
250
    # concurrent, so that old LUs don't need to be changed all at the same
251
    # time.
252
    if self.REQ_BGL:
253
      self.needed_locks = {} # Exclusive LUs don't need locks.
254
    else:
255
      raise NotImplementedError
256

    
257
  def DeclareLocks(self, level):
258
    """Declare LU locking needs for a level
259

260
    While most LUs can just declare their locking needs at ExpandNames time,
261
    sometimes there's the need to calculate some locks after having acquired
262
    the ones before. This function is called just before acquiring locks at a
263
    particular level, but after acquiring the ones at lower levels, and permits
264
    such calculations. It can be used to modify self.needed_locks, and by
265
    default it does nothing.
266

267
    This function is only called if you have something already set in
268
    self.needed_locks for the level.
269

270
    @param level: Locking level which is going to be locked
271
    @type level: member of ganeti.locking.LEVELS
272

273
    """
274

    
275
  def CheckPrereq(self):
276
    """Check prerequisites for this LU.
277

278
    This method should check that the prerequisites for the execution
279
    of this LU are fulfilled. It can do internode communication, but
280
    it should be idempotent - no cluster or system changes are
281
    allowed.
282

283
    The method should raise errors.OpPrereqError in case something is
284
    not fulfilled. Its return value is ignored.
285

286
    This method should also update all the parameters of the opcode to
287
    their canonical form if it hasn't been done by ExpandNames before.
288

289
    """
290
    if self.tasklets is not None:
291
      for (idx, tl) in enumerate(self.tasklets):
292
        logging.debug("Checking prerequisites for tasklet %s/%s",
293
                      idx + 1, len(self.tasklets))
294
        tl.CheckPrereq()
295
    else:
296
      pass
297

    
298
  def Exec(self, feedback_fn):
299
    """Execute the LU.
300

301
    This method should implement the actual work. It should raise
302
    errors.OpExecError for failures that are somewhat dealt with in
303
    code, or expected.
304

305
    """
306
    if self.tasklets is not None:
307
      for (idx, tl) in enumerate(self.tasklets):
308
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
309
        tl.Exec(feedback_fn)
310
    else:
311
      raise NotImplementedError
312

    
313
  def BuildHooksEnv(self):
314
    """Build hooks environment for this LU.
315

316
    This method should return a three-node tuple consisting of: a dict
317
    containing the environment that will be used for running the
318
    specific hook for this LU, a list of node names on which the hook
319
    should run before the execution, and a list of node names on which
320
    the hook should run after the execution.
321

322
    The keys of the dict must not have 'GANETI_' prefixed as this will
323
    be handled in the hooks runner. Also note additional keys will be
324
    added by the hooks runner. If the LU doesn't define any
325
    environment, an empty dict (and not None) should be returned.
326

327
    No nodes should be returned as an empty list (and not None).
328

329
    Note that if the HPATH for a LU class is None, this function will
330
    not be called.
331

332
    """
333
    raise NotImplementedError
334

    
335
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
336
    """Notify the LU about the results of its hooks.
337

338
    This method is called every time a hooks phase is executed, and notifies
339
    the Logical Unit about the hooks' result. The LU can then use it to alter
340
    its result based on the hooks.  By default the method does nothing and the
341
    previous result is passed back unchanged but any LU can define it if it
342
    wants to use the local cluster hook-scripts somehow.
343

344
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
345
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
346
    @param hook_results: the results of the multi-node hooks rpc call
347
    @param feedback_fn: function used send feedback back to the caller
348
    @param lu_result: the previous Exec result this LU had, or None
349
        in the PRE phase
350
    @return: the new Exec result, based on the previous result
351
        and hook results
352

353
    """
354
    # API must be kept, thus we ignore the unused argument and could
355
    # be a function warnings
356
    # pylint: disable-msg=W0613,R0201
357
    return lu_result
358

    
359
  def _ExpandAndLockInstance(self):
360
    """Helper function to expand and lock an instance.
361

362
    Many LUs that work on an instance take its name in self.op.instance_name
363
    and need to expand it and then declare the expanded name for locking. This
364
    function does it, and then updates self.op.instance_name to the expanded
365
    name. It also initializes needed_locks as a dict, if this hasn't been done
366
    before.
367

368
    """
369
    if self.needed_locks is None:
370
      self.needed_locks = {}
371
    else:
372
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
373
        "_ExpandAndLockInstance called with instance-level locks set"
374
    self.op.instance_name = _ExpandInstanceName(self.cfg,
375
                                                self.op.instance_name)
376
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
377

    
378
  def _LockInstancesNodes(self, primary_only=False):
379
    """Helper function to declare instances' nodes for locking.
380

381
    This function should be called after locking one or more instances to lock
382
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
383
    with all primary or secondary nodes for instances already locked and
384
    present in self.needed_locks[locking.LEVEL_INSTANCE].
385

386
    It should be called from DeclareLocks, and for safety only works if
387
    self.recalculate_locks[locking.LEVEL_NODE] is set.
388

389
    In the future it may grow parameters to just lock some instance's nodes, or
390
    to just lock primaries or secondary nodes, if needed.
391

392
    If should be called in DeclareLocks in a way similar to::
393

394
      if level == locking.LEVEL_NODE:
395
        self._LockInstancesNodes()
396

397
    @type primary_only: boolean
398
    @param primary_only: only lock primary nodes of locked instances
399

400
    """
401
    assert locking.LEVEL_NODE in self.recalculate_locks, \
402
      "_LockInstancesNodes helper function called with no nodes to recalculate"
403

    
404
    # TODO: check if we're really been called with the instance locks held
405

    
406
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
407
    # future we might want to have different behaviors depending on the value
408
    # of self.recalculate_locks[locking.LEVEL_NODE]
409
    wanted_nodes = []
410
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
411
      instance = self.context.cfg.GetInstanceInfo(instance_name)
412
      wanted_nodes.append(instance.primary_node)
413
      if not primary_only:
414
        wanted_nodes.extend(instance.secondary_nodes)
415

    
416
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
417
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
418
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
419
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
420

    
421
    del self.recalculate_locks[locking.LEVEL_NODE]
422

    
423

    
424
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
425
  """Simple LU which runs no hooks.
426

427
  This LU is intended as a parent for other LogicalUnits which will
428
  run no hooks, in order to reduce duplicate code.
429

430
  """
431
  HPATH = None
432
  HTYPE = None
433

    
434
  def BuildHooksEnv(self):
435
    """Empty BuildHooksEnv for NoHooksLu.
436

437
    This just raises an error.
438

439
    """
440
    assert False, "BuildHooksEnv called for NoHooksLUs"
441

    
442

    
443
class Tasklet:
444
  """Tasklet base class.
445

446
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
447
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
448
  tasklets know nothing about locks.
449

450
  Subclasses must follow these rules:
451
    - Implement CheckPrereq
452
    - Implement Exec
453

454
  """
455
  def __init__(self, lu):
456
    self.lu = lu
457

    
458
    # Shortcuts
459
    self.cfg = lu.cfg
460
    self.rpc = lu.rpc
461

    
462
  def CheckPrereq(self):
463
    """Check prerequisites for this tasklets.
464

465
    This method should check whether the prerequisites for the execution of
466
    this tasklet are fulfilled. It can do internode communication, but it
467
    should be idempotent - no cluster or system changes are allowed.
468

469
    The method should raise errors.OpPrereqError in case something is not
470
    fulfilled. Its return value is ignored.
471

472
    This method should also update all parameters to their canonical form if it
473
    hasn't been done before.
474

475
    """
476
    pass
477

    
478
  def Exec(self, feedback_fn):
479
    """Execute the tasklet.
480

481
    This method should implement the actual work. It should raise
482
    errors.OpExecError for failures that are somewhat dealt with in code, or
483
    expected.
484

485
    """
486
    raise NotImplementedError
487

    
488

    
489
def _GetWantedNodes(lu, nodes):
490
  """Returns list of checked and expanded node names.
491

492
  @type lu: L{LogicalUnit}
493
  @param lu: the logical unit on whose behalf we execute
494
  @type nodes: list
495
  @param nodes: list of node names or None for all nodes
496
  @rtype: list
497
  @return: the list of nodes, sorted
498
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
499

500
  """
501
  if not nodes:
502
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
503
      " non-empty list of nodes whose name is to be expanded.")
504

    
505
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
506
  return utils.NiceSort(wanted)
507

    
508

    
509
def _GetWantedInstances(lu, instances):
510
  """Returns list of checked and expanded instance names.
511

512
  @type lu: L{LogicalUnit}
513
  @param lu: the logical unit on whose behalf we execute
514
  @type instances: list
515
  @param instances: list of instance names or None for all instances
516
  @rtype: list
517
  @return: the list of instances, sorted
518
  @raise errors.OpPrereqError: if the instances parameter is wrong type
519
  @raise errors.OpPrereqError: if any of the passed instances is not found
520

521
  """
522
  if instances:
523
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
524
  else:
525
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
526
  return wanted
527

    
528

    
529
def _GetUpdatedParams(old_params, update_dict,
530
                      use_default=True, use_none=False):
531
  """Return the new version of a parameter dictionary.
532

533
  @type old_params: dict
534
  @param old_params: old parameters
535
  @type update_dict: dict
536
  @param update_dict: dict containing new parameter values, or
537
      constants.VALUE_DEFAULT to reset the parameter to its default
538
      value
539
  @param use_default: boolean
540
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
541
      values as 'to be deleted' values
542
  @param use_none: boolean
543
  @type use_none: whether to recognise C{None} values as 'to be
544
      deleted' values
545
  @rtype: dict
546
  @return: the new parameter dictionary
547

548
  """
549
  params_copy = copy.deepcopy(old_params)
550
  for key, val in update_dict.iteritems():
551
    if ((use_default and val == constants.VALUE_DEFAULT) or
552
        (use_none and val is None)):
553
      try:
554
        del params_copy[key]
555
      except KeyError:
556
        pass
557
    else:
558
      params_copy[key] = val
559
  return params_copy
560

    
561

    
562
def _CheckOutputFields(static, dynamic, selected):
563
  """Checks whether all selected fields are valid.
564

565
  @type static: L{utils.FieldSet}
566
  @param static: static fields set
567
  @type dynamic: L{utils.FieldSet}
568
  @param dynamic: dynamic fields set
569

570
  """
571
  f = utils.FieldSet()
572
  f.Extend(static)
573
  f.Extend(dynamic)
574

    
575
  delta = f.NonMatching(selected)
576
  if delta:
577
    raise errors.OpPrereqError("Unknown output fields selected: %s"
578
                               % ",".join(delta), errors.ECODE_INVAL)
579

    
580

    
581
def _CheckGlobalHvParams(params):
582
  """Validates that given hypervisor params are not global ones.
583

584
  This will ensure that instances don't get customised versions of
585
  global params.
586

587
  """
588
  used_globals = constants.HVC_GLOBALS.intersection(params)
589
  if used_globals:
590
    msg = ("The following hypervisor parameters are global and cannot"
591
           " be customized at instance level, please modify them at"
592
           " cluster level: %s" % utils.CommaJoin(used_globals))
593
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
594

    
595

    
596
def _CheckNodeOnline(lu, node):
597
  """Ensure that a given node is online.
598

599
  @param lu: the LU on behalf of which we make the check
600
  @param node: the node to check
601
  @raise errors.OpPrereqError: if the node is offline
602

603
  """
604
  if lu.cfg.GetNodeInfo(node).offline:
605
    raise errors.OpPrereqError("Can't use offline node %s" % node,
606
                               errors.ECODE_STATE)
607

    
608

    
609
def _CheckNodeNotDrained(lu, node):
610
  """Ensure that a given node is not drained.
611

612
  @param lu: the LU on behalf of which we make the check
613
  @param node: the node to check
614
  @raise errors.OpPrereqError: if the node is drained
615

616
  """
617
  if lu.cfg.GetNodeInfo(node).drained:
618
    raise errors.OpPrereqError("Can't use drained node %s" % node,
619
                               errors.ECODE_STATE)
620

    
621

    
622
def _CheckNodeVmCapable(lu, node):
623
  """Ensure that a given node is vm capable.
624

625
  @param lu: the LU on behalf of which we make the check
626
  @param node: the node to check
627
  @raise errors.OpPrereqError: if the node is not vm capable
628

629
  """
630
  if not lu.cfg.GetNodeInfo(node).vm_capable:
631
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
632
                               errors.ECODE_STATE)
633

    
634

    
635
def _CheckNodeHasOS(lu, node, os_name, force_variant):
636
  """Ensure that a node supports a given OS.
637

638
  @param lu: the LU on behalf of which we make the check
639
  @param node: the node to check
640
  @param os_name: the OS to query about
641
  @param force_variant: whether to ignore variant errors
642
  @raise errors.OpPrereqError: if the node is not supporting the OS
643

644
  """
645
  result = lu.rpc.call_os_get(node, os_name)
646
  result.Raise("OS '%s' not in supported OS list for node %s" %
647
               (os_name, node),
648
               prereq=True, ecode=errors.ECODE_INVAL)
649
  if not force_variant:
650
    _CheckOSVariant(result.payload, os_name)
651

    
652

    
653
def _RequireFileStorage():
654
  """Checks that file storage is enabled.
655

656
  @raise errors.OpPrereqError: when file storage is disabled
657

658
  """
659
  if not constants.ENABLE_FILE_STORAGE:
660
    raise errors.OpPrereqError("File storage disabled at configure time",
661
                               errors.ECODE_INVAL)
662

    
663

    
664
def _CheckDiskTemplate(template):
665
  """Ensure a given disk template is valid.
666

667
  """
668
  if template not in constants.DISK_TEMPLATES:
669
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
670
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
671
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
672
  if template == constants.DT_FILE:
673
    _RequireFileStorage()
674
  return True
675

    
676

    
677
def _CheckStorageType(storage_type):
678
  """Ensure a given storage type is valid.
679

680
  """
681
  if storage_type not in constants.VALID_STORAGE_TYPES:
682
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
683
                               errors.ECODE_INVAL)
684
  if storage_type == constants.ST_FILE:
685
    _RequireFileStorage()
686
  return True
687

    
688

    
689
def _GetClusterDomainSecret():
690
  """Reads the cluster domain secret.
691

692
  """
693
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
694
                               strict=True)
695

    
696

    
697
def _CheckInstanceDown(lu, instance, reason):
698
  """Ensure that an instance is not running."""
699
  if instance.admin_up:
700
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
701
                               (instance.name, reason), errors.ECODE_STATE)
702

    
703
  pnode = instance.primary_node
704
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
705
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
706
              prereq=True, ecode=errors.ECODE_ENVIRON)
707

    
708
  if instance.name in ins_l.payload:
709
    raise errors.OpPrereqError("Instance %s is running, %s" %
710
                               (instance.name, reason), errors.ECODE_STATE)
711

    
712

    
713
def _ExpandItemName(fn, name, kind):
714
  """Expand an item name.
715

716
  @param fn: the function to use for expansion
717
  @param name: requested item name
718
  @param kind: text description ('Node' or 'Instance')
719
  @return: the resolved (full) name
720
  @raise errors.OpPrereqError: if the item is not found
721

722
  """
723
  full_name = fn(name)
724
  if full_name is None:
725
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
726
                               errors.ECODE_NOENT)
727
  return full_name
728

    
729

    
730
def _ExpandNodeName(cfg, name):
731
  """Wrapper over L{_ExpandItemName} for nodes."""
732
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
733

    
734

    
735
def _ExpandInstanceName(cfg, name):
736
  """Wrapper over L{_ExpandItemName} for instance."""
737
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
738

    
739

    
740
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
741
                          memory, vcpus, nics, disk_template, disks,
742
                          bep, hvp, hypervisor_name):
743
  """Builds instance related env variables for hooks
744

745
  This builds the hook environment from individual variables.
746

747
  @type name: string
748
  @param name: the name of the instance
749
  @type primary_node: string
750
  @param primary_node: the name of the instance's primary node
751
  @type secondary_nodes: list
752
  @param secondary_nodes: list of secondary nodes as strings
753
  @type os_type: string
754
  @param os_type: the name of the instance's OS
755
  @type status: boolean
756
  @param status: the should_run status of the instance
757
  @type memory: string
758
  @param memory: the memory size of the instance
759
  @type vcpus: string
760
  @param vcpus: the count of VCPUs the instance has
761
  @type nics: list
762
  @param nics: list of tuples (ip, mac, mode, link) representing
763
      the NICs the instance has
764
  @type disk_template: string
765
  @param disk_template: the disk template of the instance
766
  @type disks: list
767
  @param disks: the list of (size, mode) pairs
768
  @type bep: dict
769
  @param bep: the backend parameters for the instance
770
  @type hvp: dict
771
  @param hvp: the hypervisor parameters for the instance
772
  @type hypervisor_name: string
773
  @param hypervisor_name: the hypervisor for the instance
774
  @rtype: dict
775
  @return: the hook environment for this instance
776

777
  """
778
  if status:
779
    str_status = "up"
780
  else:
781
    str_status = "down"
782
  env = {
783
    "OP_TARGET": name,
784
    "INSTANCE_NAME": name,
785
    "INSTANCE_PRIMARY": primary_node,
786
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
787
    "INSTANCE_OS_TYPE": os_type,
788
    "INSTANCE_STATUS": str_status,
789
    "INSTANCE_MEMORY": memory,
790
    "INSTANCE_VCPUS": vcpus,
791
    "INSTANCE_DISK_TEMPLATE": disk_template,
792
    "INSTANCE_HYPERVISOR": hypervisor_name,
793
  }
794

    
795
  if nics:
796
    nic_count = len(nics)
797
    for idx, (ip, mac, mode, link) in enumerate(nics):
798
      if ip is None:
799
        ip = ""
800
      env["INSTANCE_NIC%d_IP" % idx] = ip
801
      env["INSTANCE_NIC%d_MAC" % idx] = mac
802
      env["INSTANCE_NIC%d_MODE" % idx] = mode
803
      env["INSTANCE_NIC%d_LINK" % idx] = link
804
      if mode == constants.NIC_MODE_BRIDGED:
805
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
806
  else:
807
    nic_count = 0
808

    
809
  env["INSTANCE_NIC_COUNT"] = nic_count
810

    
811
  if disks:
812
    disk_count = len(disks)
813
    for idx, (size, mode) in enumerate(disks):
814
      env["INSTANCE_DISK%d_SIZE" % idx] = size
815
      env["INSTANCE_DISK%d_MODE" % idx] = mode
816
  else:
817
    disk_count = 0
818

    
819
  env["INSTANCE_DISK_COUNT"] = disk_count
820

    
821
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
822
    for key, value in source.items():
823
      env["INSTANCE_%s_%s" % (kind, key)] = value
824

    
825
  return env
826

    
827

    
828
def _NICListToTuple(lu, nics):
829
  """Build a list of nic information tuples.
830

831
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
832
  value in LUQueryInstanceData.
833

834
  @type lu:  L{LogicalUnit}
835
  @param lu: the logical unit on whose behalf we execute
836
  @type nics: list of L{objects.NIC}
837
  @param nics: list of nics to convert to hooks tuples
838

839
  """
840
  hooks_nics = []
841
  cluster = lu.cfg.GetClusterInfo()
842
  for nic in nics:
843
    ip = nic.ip
844
    mac = nic.mac
845
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
846
    mode = filled_params[constants.NIC_MODE]
847
    link = filled_params[constants.NIC_LINK]
848
    hooks_nics.append((ip, mac, mode, link))
849
  return hooks_nics
850

    
851

    
852
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
853
  """Builds instance related env variables for hooks from an object.
854

855
  @type lu: L{LogicalUnit}
856
  @param lu: the logical unit on whose behalf we execute
857
  @type instance: L{objects.Instance}
858
  @param instance: the instance for which we should build the
859
      environment
860
  @type override: dict
861
  @param override: dictionary with key/values that will override
862
      our values
863
  @rtype: dict
864
  @return: the hook environment dictionary
865

866
  """
867
  cluster = lu.cfg.GetClusterInfo()
868
  bep = cluster.FillBE(instance)
869
  hvp = cluster.FillHV(instance)
870
  args = {
871
    'name': instance.name,
872
    'primary_node': instance.primary_node,
873
    'secondary_nodes': instance.secondary_nodes,
874
    'os_type': instance.os,
875
    'status': instance.admin_up,
876
    'memory': bep[constants.BE_MEMORY],
877
    'vcpus': bep[constants.BE_VCPUS],
878
    'nics': _NICListToTuple(lu, instance.nics),
879
    'disk_template': instance.disk_template,
880
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
881
    'bep': bep,
882
    'hvp': hvp,
883
    'hypervisor_name': instance.hypervisor,
884
  }
885
  if override:
886
    args.update(override)
887
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
888

    
889

    
890
def _AdjustCandidatePool(lu, exceptions):
891
  """Adjust the candidate pool after node operations.
892

893
  """
894
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
895
  if mod_list:
896
    lu.LogInfo("Promoted nodes to master candidate role: %s",
897
               utils.CommaJoin(node.name for node in mod_list))
898
    for name in mod_list:
899
      lu.context.ReaddNode(name)
900
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
901
  if mc_now > mc_max:
902
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
903
               (mc_now, mc_max))
904

    
905

    
906
def _DecideSelfPromotion(lu, exceptions=None):
907
  """Decide whether I should promote myself as a master candidate.
908

909
  """
910
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
911
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
912
  # the new node will increase mc_max with one, so:
913
  mc_should = min(mc_should + 1, cp_size)
914
  return mc_now < mc_should
915

    
916

    
917
def _CheckNicsBridgesExist(lu, target_nics, target_node):
918
  """Check that the brigdes needed by a list of nics exist.
919

920
  """
921
  cluster = lu.cfg.GetClusterInfo()
922
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
923
  brlist = [params[constants.NIC_LINK] for params in paramslist
924
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
925
  if brlist:
926
    result = lu.rpc.call_bridges_exist(target_node, brlist)
927
    result.Raise("Error checking bridges on destination node '%s'" %
928
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
929

    
930

    
931
def _CheckInstanceBridgesExist(lu, instance, node=None):
932
  """Check that the brigdes needed by an instance exist.
933

934
  """
935
  if node is None:
936
    node = instance.primary_node
937
  _CheckNicsBridgesExist(lu, instance.nics, node)
938

    
939

    
940
def _CheckOSVariant(os_obj, name):
941
  """Check whether an OS name conforms to the os variants specification.
942

943
  @type os_obj: L{objects.OS}
944
  @param os_obj: OS object to check
945
  @type name: string
946
  @param name: OS name passed by the user, to check for validity
947

948
  """
949
  if not os_obj.supported_variants:
950
    return
951
  variant = objects.OS.GetVariant(name)
952
  if not variant:
953
    raise errors.OpPrereqError("OS name must include a variant",
954
                               errors.ECODE_INVAL)
955

    
956
  if variant not in os_obj.supported_variants:
957
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
958

    
959

    
960
def _GetNodeInstancesInner(cfg, fn):
961
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
962

    
963

    
964
def _GetNodeInstances(cfg, node_name):
965
  """Returns a list of all primary and secondary instances on a node.
966

967
  """
968

    
969
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
970

    
971

    
972
def _GetNodePrimaryInstances(cfg, node_name):
973
  """Returns primary instances on a node.
974

975
  """
976
  return _GetNodeInstancesInner(cfg,
977
                                lambda inst: node_name == inst.primary_node)
978

    
979

    
980
def _GetNodeSecondaryInstances(cfg, node_name):
981
  """Returns secondary instances on a node.
982

983
  """
984
  return _GetNodeInstancesInner(cfg,
985
                                lambda inst: node_name in inst.secondary_nodes)
986

    
987

    
988
def _GetStorageTypeArgs(cfg, storage_type):
989
  """Returns the arguments for a storage type.
990

991
  """
992
  # Special case for file storage
993
  if storage_type == constants.ST_FILE:
994
    # storage.FileStorage wants a list of storage directories
995
    return [[cfg.GetFileStorageDir()]]
996

    
997
  return []
998

    
999

    
1000
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1001
  faulty = []
1002

    
1003
  for dev in instance.disks:
1004
    cfg.SetDiskID(dev, node_name)
1005

    
1006
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1007
  result.Raise("Failed to get disk status from node %s" % node_name,
1008
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1009

    
1010
  for idx, bdev_status in enumerate(result.payload):
1011
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1012
      faulty.append(idx)
1013

    
1014
  return faulty
1015

    
1016

    
1017
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1018
  """Check the sanity of iallocator and node arguments and use the
1019
  cluster-wide iallocator if appropriate.
1020

1021
  Check that at most one of (iallocator, node) is specified. If none is
1022
  specified, then the LU's opcode's iallocator slot is filled with the
1023
  cluster-wide default iallocator.
1024

1025
  @type iallocator_slot: string
1026
  @param iallocator_slot: the name of the opcode iallocator slot
1027
  @type node_slot: string
1028
  @param node_slot: the name of the opcode target node slot
1029

1030
  """
1031
  node = getattr(lu.op, node_slot, None)
1032
  iallocator = getattr(lu.op, iallocator_slot, None)
1033

    
1034
  if node is not None and iallocator is not None:
1035
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1036
                               errors.ECODE_INVAL)
1037
  elif node is None and iallocator is None:
1038
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1039
    if default_iallocator:
1040
      setattr(lu.op, iallocator_slot, default_iallocator)
1041
    else:
1042
      raise errors.OpPrereqError("No iallocator or node given and no"
1043
                                 " cluster-wide default iallocator found."
1044
                                 " Please specify either an iallocator or a"
1045
                                 " node, or set a cluster-wide default"
1046
                                 " iallocator.")
1047

    
1048

    
1049
class LUPostInitCluster(LogicalUnit):
1050
  """Logical unit for running hooks after cluster initialization.
1051

1052
  """
1053
  HPATH = "cluster-init"
1054
  HTYPE = constants.HTYPE_CLUSTER
1055

    
1056
  def BuildHooksEnv(self):
1057
    """Build hooks env.
1058

1059
    """
1060
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1061
    mn = self.cfg.GetMasterNode()
1062
    return env, [], [mn]
1063

    
1064
  def Exec(self, feedback_fn):
1065
    """Nothing to do.
1066

1067
    """
1068
    return True
1069

    
1070

    
1071
class LUDestroyCluster(LogicalUnit):
1072
  """Logical unit for destroying the cluster.
1073

1074
  """
1075
  HPATH = "cluster-destroy"
1076
  HTYPE = constants.HTYPE_CLUSTER
1077

    
1078
  def BuildHooksEnv(self):
1079
    """Build hooks env.
1080

1081
    """
1082
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1083
    return env, [], []
1084

    
1085
  def CheckPrereq(self):
1086
    """Check prerequisites.
1087

1088
    This checks whether the cluster is empty.
1089

1090
    Any errors are signaled by raising errors.OpPrereqError.
1091

1092
    """
1093
    master = self.cfg.GetMasterNode()
1094

    
1095
    nodelist = self.cfg.GetNodeList()
1096
    if len(nodelist) != 1 or nodelist[0] != master:
1097
      raise errors.OpPrereqError("There are still %d node(s) in"
1098
                                 " this cluster." % (len(nodelist) - 1),
1099
                                 errors.ECODE_INVAL)
1100
    instancelist = self.cfg.GetInstanceList()
1101
    if instancelist:
1102
      raise errors.OpPrereqError("There are still %d instance(s) in"
1103
                                 " this cluster." % len(instancelist),
1104
                                 errors.ECODE_INVAL)
1105

    
1106
  def Exec(self, feedback_fn):
1107
    """Destroys the cluster.
1108

1109
    """
1110
    master = self.cfg.GetMasterNode()
1111

    
1112
    # Run post hooks on master node before it's removed
1113
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1114
    try:
1115
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1116
    except:
1117
      # pylint: disable-msg=W0702
1118
      self.LogWarning("Errors occurred running hooks on %s" % master)
1119

    
1120
    result = self.rpc.call_node_stop_master(master, False)
1121
    result.Raise("Could not disable the master role")
1122

    
1123
    return master
1124

    
1125

    
1126
def _VerifyCertificate(filename):
1127
  """Verifies a certificate for LUVerifyCluster.
1128

1129
  @type filename: string
1130
  @param filename: Path to PEM file
1131

1132
  """
1133
  try:
1134
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1135
                                           utils.ReadFile(filename))
1136
  except Exception, err: # pylint: disable-msg=W0703
1137
    return (LUVerifyCluster.ETYPE_ERROR,
1138
            "Failed to load X509 certificate %s: %s" % (filename, err))
1139

    
1140
  (errcode, msg) = \
1141
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1142
                                constants.SSL_CERT_EXPIRATION_ERROR)
1143

    
1144
  if msg:
1145
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1146
  else:
1147
    fnamemsg = None
1148

    
1149
  if errcode is None:
1150
    return (None, fnamemsg)
1151
  elif errcode == utils.CERT_WARNING:
1152
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1153
  elif errcode == utils.CERT_ERROR:
1154
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1155

    
1156
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1157

    
1158

    
1159
class LUVerifyCluster(LogicalUnit):
1160
  """Verifies the cluster status.
1161

1162
  """
1163
  HPATH = "cluster-verify"
1164
  HTYPE = constants.HTYPE_CLUSTER
1165
  _OP_PARAMS = [
1166
    ("skip_checks", ht.EmptyList,
1167
     ht.TListOf(ht.TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1168
    ("verbose", False, ht.TBool),
1169
    ("error_codes", False, ht.TBool),
1170
    ("debug_simulate_errors", False, ht.TBool),
1171
    ]
1172
  REQ_BGL = False
1173

    
1174
  TCLUSTER = "cluster"
1175
  TNODE = "node"
1176
  TINSTANCE = "instance"
1177

    
1178
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1179
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1180
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1181
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1182
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1183
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1184
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1185
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1186
  ENODEDRBD = (TNODE, "ENODEDRBD")
1187
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1188
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1189
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1190
  ENODEHV = (TNODE, "ENODEHV")
1191
  ENODELVM = (TNODE, "ENODELVM")
1192
  ENODEN1 = (TNODE, "ENODEN1")
1193
  ENODENET = (TNODE, "ENODENET")
1194
  ENODEOS = (TNODE, "ENODEOS")
1195
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1196
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1197
  ENODERPC = (TNODE, "ENODERPC")
1198
  ENODESSH = (TNODE, "ENODESSH")
1199
  ENODEVERSION = (TNODE, "ENODEVERSION")
1200
  ENODESETUP = (TNODE, "ENODESETUP")
1201
  ENODETIME = (TNODE, "ENODETIME")
1202

    
1203
  ETYPE_FIELD = "code"
1204
  ETYPE_ERROR = "ERROR"
1205
  ETYPE_WARNING = "WARNING"
1206

    
1207
  class NodeImage(object):
1208
    """A class representing the logical and physical status of a node.
1209

1210
    @type name: string
1211
    @ivar name: the node name to which this object refers
1212
    @ivar volumes: a structure as returned from
1213
        L{ganeti.backend.GetVolumeList} (runtime)
1214
    @ivar instances: a list of running instances (runtime)
1215
    @ivar pinst: list of configured primary instances (config)
1216
    @ivar sinst: list of configured secondary instances (config)
1217
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1218
        of this node (config)
1219
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1220
    @ivar dfree: free disk, as reported by the node (runtime)
1221
    @ivar offline: the offline status (config)
1222
    @type rpc_fail: boolean
1223
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1224
        not whether the individual keys were correct) (runtime)
1225
    @type lvm_fail: boolean
1226
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1227
    @type hyp_fail: boolean
1228
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1229
    @type ghost: boolean
1230
    @ivar ghost: whether this is a known node or not (config)
1231
    @type os_fail: boolean
1232
    @ivar os_fail: whether the RPC call didn't return valid OS data
1233
    @type oslist: list
1234
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1235
    @type vm_capable: boolean
1236
    @ivar vm_capable: whether the node can host instances
1237

1238
    """
1239
    def __init__(self, offline=False, name=None, vm_capable=True):
1240
      self.name = name
1241
      self.volumes = {}
1242
      self.instances = []
1243
      self.pinst = []
1244
      self.sinst = []
1245
      self.sbp = {}
1246
      self.mfree = 0
1247
      self.dfree = 0
1248
      self.offline = offline
1249
      self.vm_capable = vm_capable
1250
      self.rpc_fail = False
1251
      self.lvm_fail = False
1252
      self.hyp_fail = False
1253
      self.ghost = False
1254
      self.os_fail = False
1255
      self.oslist = {}
1256

    
1257
  def ExpandNames(self):
1258
    self.needed_locks = {
1259
      locking.LEVEL_NODE: locking.ALL_SET,
1260
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1261
    }
1262
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1263

    
1264
  def _Error(self, ecode, item, msg, *args, **kwargs):
1265
    """Format an error message.
1266

1267
    Based on the opcode's error_codes parameter, either format a
1268
    parseable error code, or a simpler error string.
1269

1270
    This must be called only from Exec and functions called from Exec.
1271

1272
    """
1273
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1274
    itype, etxt = ecode
1275
    # first complete the msg
1276
    if args:
1277
      msg = msg % args
1278
    # then format the whole message
1279
    if self.op.error_codes:
1280
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1281
    else:
1282
      if item:
1283
        item = " " + item
1284
      else:
1285
        item = ""
1286
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1287
    # and finally report it via the feedback_fn
1288
    self._feedback_fn("  - %s" % msg)
1289

    
1290
  def _ErrorIf(self, cond, *args, **kwargs):
1291
    """Log an error message if the passed condition is True.
1292

1293
    """
1294
    cond = bool(cond) or self.op.debug_simulate_errors
1295
    if cond:
1296
      self._Error(*args, **kwargs)
1297
    # do not mark the operation as failed for WARN cases only
1298
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1299
      self.bad = self.bad or cond
1300

    
1301
  def _VerifyNode(self, ninfo, nresult):
1302
    """Perform some basic validation on data returned from a node.
1303

1304
      - check the result data structure is well formed and has all the
1305
        mandatory fields
1306
      - check ganeti version
1307

1308
    @type ninfo: L{objects.Node}
1309
    @param ninfo: the node to check
1310
    @param nresult: the results from the node
1311
    @rtype: boolean
1312
    @return: whether overall this call was successful (and we can expect
1313
         reasonable values in the respose)
1314

1315
    """
1316
    node = ninfo.name
1317
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1318

    
1319
    # main result, nresult should be a non-empty dict
1320
    test = not nresult or not isinstance(nresult, dict)
1321
    _ErrorIf(test, self.ENODERPC, node,
1322
                  "unable to verify node: no data returned")
1323
    if test:
1324
      return False
1325

    
1326
    # compares ganeti version
1327
    local_version = constants.PROTOCOL_VERSION
1328
    remote_version = nresult.get("version", None)
1329
    test = not (remote_version and
1330
                isinstance(remote_version, (list, tuple)) and
1331
                len(remote_version) == 2)
1332
    _ErrorIf(test, self.ENODERPC, node,
1333
             "connection to node returned invalid data")
1334
    if test:
1335
      return False
1336

    
1337
    test = local_version != remote_version[0]
1338
    _ErrorIf(test, self.ENODEVERSION, node,
1339
             "incompatible protocol versions: master %s,"
1340
             " node %s", local_version, remote_version[0])
1341
    if test:
1342
      return False
1343

    
1344
    # node seems compatible, we can actually try to look into its results
1345

    
1346
    # full package version
1347
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1348
                  self.ENODEVERSION, node,
1349
                  "software version mismatch: master %s, node %s",
1350
                  constants.RELEASE_VERSION, remote_version[1],
1351
                  code=self.ETYPE_WARNING)
1352

    
1353
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1354
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1355
      for hv_name, hv_result in hyp_result.iteritems():
1356
        test = hv_result is not None
1357
        _ErrorIf(test, self.ENODEHV, node,
1358
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1359

    
1360
    test = nresult.get(constants.NV_NODESETUP,
1361
                           ["Missing NODESETUP results"])
1362
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1363
             "; ".join(test))
1364

    
1365
    return True
1366

    
1367
  def _VerifyNodeTime(self, ninfo, nresult,
1368
                      nvinfo_starttime, nvinfo_endtime):
1369
    """Check the node time.
1370

1371
    @type ninfo: L{objects.Node}
1372
    @param ninfo: the node to check
1373
    @param nresult: the remote results for the node
1374
    @param nvinfo_starttime: the start time of the RPC call
1375
    @param nvinfo_endtime: the end time of the RPC call
1376

1377
    """
1378
    node = ninfo.name
1379
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1380

    
1381
    ntime = nresult.get(constants.NV_TIME, None)
1382
    try:
1383
      ntime_merged = utils.MergeTime(ntime)
1384
    except (ValueError, TypeError):
1385
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1386
      return
1387

    
1388
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1389
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1390
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1391
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1392
    else:
1393
      ntime_diff = None
1394

    
1395
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1396
             "Node time diverges by at least %s from master node time",
1397
             ntime_diff)
1398

    
1399
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1400
    """Check the node time.
1401

1402
    @type ninfo: L{objects.Node}
1403
    @param ninfo: the node to check
1404
    @param nresult: the remote results for the node
1405
    @param vg_name: the configured VG name
1406

1407
    """
1408
    if vg_name is None:
1409
      return
1410

    
1411
    node = ninfo.name
1412
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1413

    
1414
    # checks vg existence and size > 20G
1415
    vglist = nresult.get(constants.NV_VGLIST, None)
1416
    test = not vglist
1417
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1418
    if not test:
1419
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1420
                                            constants.MIN_VG_SIZE)
1421
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1422

    
1423
    # check pv names
1424
    pvlist = nresult.get(constants.NV_PVLIST, None)
1425
    test = pvlist is None
1426
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1427
    if not test:
1428
      # check that ':' is not present in PV names, since it's a
1429
      # special character for lvcreate (denotes the range of PEs to
1430
      # use on the PV)
1431
      for _, pvname, owner_vg in pvlist:
1432
        test = ":" in pvname
1433
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1434
                 " '%s' of VG '%s'", pvname, owner_vg)
1435

    
1436
  def _VerifyNodeNetwork(self, ninfo, nresult):
1437
    """Check the node time.
1438

1439
    @type ninfo: L{objects.Node}
1440
    @param ninfo: the node to check
1441
    @param nresult: the remote results for the node
1442

1443
    """
1444
    node = ninfo.name
1445
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1446

    
1447
    test = constants.NV_NODELIST not in nresult
1448
    _ErrorIf(test, self.ENODESSH, node,
1449
             "node hasn't returned node ssh connectivity data")
1450
    if not test:
1451
      if nresult[constants.NV_NODELIST]:
1452
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1453
          _ErrorIf(True, self.ENODESSH, node,
1454
                   "ssh communication with node '%s': %s", a_node, a_msg)
1455

    
1456
    test = constants.NV_NODENETTEST not in nresult
1457
    _ErrorIf(test, self.ENODENET, node,
1458
             "node hasn't returned node tcp connectivity data")
1459
    if not test:
1460
      if nresult[constants.NV_NODENETTEST]:
1461
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1462
        for anode in nlist:
1463
          _ErrorIf(True, self.ENODENET, node,
1464
                   "tcp communication with node '%s': %s",
1465
                   anode, nresult[constants.NV_NODENETTEST][anode])
1466

    
1467
    test = constants.NV_MASTERIP not in nresult
1468
    _ErrorIf(test, self.ENODENET, node,
1469
             "node hasn't returned node master IP reachability data")
1470
    if not test:
1471
      if not nresult[constants.NV_MASTERIP]:
1472
        if node == self.master_node:
1473
          msg = "the master node cannot reach the master IP (not configured?)"
1474
        else:
1475
          msg = "cannot reach the master IP"
1476
        _ErrorIf(True, self.ENODENET, node, msg)
1477

    
1478
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1479
                      diskstatus):
1480
    """Verify an instance.
1481

1482
    This function checks to see if the required block devices are
1483
    available on the instance's node.
1484

1485
    """
1486
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1487
    node_current = instanceconfig.primary_node
1488

    
1489
    node_vol_should = {}
1490
    instanceconfig.MapLVsByNode(node_vol_should)
1491

    
1492
    for node in node_vol_should:
1493
      n_img = node_image[node]
1494
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1495
        # ignore missing volumes on offline or broken nodes
1496
        continue
1497
      for volume in node_vol_should[node]:
1498
        test = volume not in n_img.volumes
1499
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1500
                 "volume %s missing on node %s", volume, node)
1501

    
1502
    if instanceconfig.admin_up:
1503
      pri_img = node_image[node_current]
1504
      test = instance not in pri_img.instances and not pri_img.offline
1505
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1506
               "instance not running on its primary node %s",
1507
               node_current)
1508

    
1509
    for node, n_img in node_image.items():
1510
      if (not node == node_current):
1511
        test = instance in n_img.instances
1512
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1513
                 "instance should not run on node %s", node)
1514

    
1515
    diskdata = [(nname, disk, idx)
1516
                for (nname, disks) in diskstatus.items()
1517
                for idx, disk in enumerate(disks)]
1518

    
1519
    for nname, bdev_status, idx in diskdata:
1520
      _ErrorIf(not bdev_status,
1521
               self.EINSTANCEFAULTYDISK, instance,
1522
               "couldn't retrieve status for disk/%s on %s", idx, nname)
1523
      _ErrorIf(bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY,
1524
               self.EINSTANCEFAULTYDISK, instance,
1525
               "disk/%s on %s is faulty", idx, nname)
1526

    
1527
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1528
    """Verify if there are any unknown volumes in the cluster.
1529

1530
    The .os, .swap and backup volumes are ignored. All other volumes are
1531
    reported as unknown.
1532

1533
    @type reserved: L{ganeti.utils.FieldSet}
1534
    @param reserved: a FieldSet of reserved volume names
1535

1536
    """
1537
    for node, n_img in node_image.items():
1538
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1539
        # skip non-healthy nodes
1540
        continue
1541
      for volume in n_img.volumes:
1542
        test = ((node not in node_vol_should or
1543
                volume not in node_vol_should[node]) and
1544
                not reserved.Matches(volume))
1545
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1546
                      "volume %s is unknown", volume)
1547

    
1548
  def _VerifyOrphanInstances(self, instancelist, node_image):
1549
    """Verify the list of running instances.
1550

1551
    This checks what instances are running but unknown to the cluster.
1552

1553
    """
1554
    for node, n_img in node_image.items():
1555
      for o_inst in n_img.instances:
1556
        test = o_inst not in instancelist
1557
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1558
                      "instance %s on node %s should not exist", o_inst, node)
1559

    
1560
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1561
    """Verify N+1 Memory Resilience.
1562

1563
    Check that if one single node dies we can still start all the
1564
    instances it was primary for.
1565

1566
    """
1567
    for node, n_img in node_image.items():
1568
      # This code checks that every node which is now listed as
1569
      # secondary has enough memory to host all instances it is
1570
      # supposed to should a single other node in the cluster fail.
1571
      # FIXME: not ready for failover to an arbitrary node
1572
      # FIXME: does not support file-backed instances
1573
      # WARNING: we currently take into account down instances as well
1574
      # as up ones, considering that even if they're down someone
1575
      # might want to start them even in the event of a node failure.
1576
      for prinode, instances in n_img.sbp.items():
1577
        needed_mem = 0
1578
        for instance in instances:
1579
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1580
          if bep[constants.BE_AUTO_BALANCE]:
1581
            needed_mem += bep[constants.BE_MEMORY]
1582
        test = n_img.mfree < needed_mem
1583
        self._ErrorIf(test, self.ENODEN1, node,
1584
                      "not enough memory on to accommodate"
1585
                      " failovers should peer node %s fail", prinode)
1586

    
1587
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1588
                       master_files):
1589
    """Verifies and computes the node required file checksums.
1590

1591
    @type ninfo: L{objects.Node}
1592
    @param ninfo: the node to check
1593
    @param nresult: the remote results for the node
1594
    @param file_list: required list of files
1595
    @param local_cksum: dictionary of local files and their checksums
1596
    @param master_files: list of files that only masters should have
1597

1598
    """
1599
    node = ninfo.name
1600
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1601

    
1602
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1603
    test = not isinstance(remote_cksum, dict)
1604
    _ErrorIf(test, self.ENODEFILECHECK, node,
1605
             "node hasn't returned file checksum data")
1606
    if test:
1607
      return
1608

    
1609
    for file_name in file_list:
1610
      node_is_mc = ninfo.master_candidate
1611
      must_have = (file_name not in master_files) or node_is_mc
1612
      # missing
1613
      test1 = file_name not in remote_cksum
1614
      # invalid checksum
1615
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1616
      # existing and good
1617
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1618
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1619
               "file '%s' missing", file_name)
1620
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1621
               "file '%s' has wrong checksum", file_name)
1622
      # not candidate and this is not a must-have file
1623
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1624
               "file '%s' should not exist on non master"
1625
               " candidates (and the file is outdated)", file_name)
1626
      # all good, except non-master/non-must have combination
1627
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1628
               "file '%s' should not exist"
1629
               " on non master candidates", file_name)
1630

    
1631
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1632
                      drbd_map):
1633
    """Verifies and the node DRBD status.
1634

1635
    @type ninfo: L{objects.Node}
1636
    @param ninfo: the node to check
1637
    @param nresult: the remote results for the node
1638
    @param instanceinfo: the dict of instances
1639
    @param drbd_helper: the configured DRBD usermode helper
1640
    @param drbd_map: the DRBD map as returned by
1641
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1642

1643
    """
1644
    node = ninfo.name
1645
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1646

    
1647
    if drbd_helper:
1648
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1649
      test = (helper_result == None)
1650
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1651
               "no drbd usermode helper returned")
1652
      if helper_result:
1653
        status, payload = helper_result
1654
        test = not status
1655
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1656
                 "drbd usermode helper check unsuccessful: %s", payload)
1657
        test = status and (payload != drbd_helper)
1658
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1659
                 "wrong drbd usermode helper: %s", payload)
1660

    
1661
    # compute the DRBD minors
1662
    node_drbd = {}
1663
    for minor, instance in drbd_map[node].items():
1664
      test = instance not in instanceinfo
1665
      _ErrorIf(test, self.ECLUSTERCFG, None,
1666
               "ghost instance '%s' in temporary DRBD map", instance)
1667
        # ghost instance should not be running, but otherwise we
1668
        # don't give double warnings (both ghost instance and
1669
        # unallocated minor in use)
1670
      if test:
1671
        node_drbd[minor] = (instance, False)
1672
      else:
1673
        instance = instanceinfo[instance]
1674
        node_drbd[minor] = (instance.name, instance.admin_up)
1675

    
1676
    # and now check them
1677
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1678
    test = not isinstance(used_minors, (tuple, list))
1679
    _ErrorIf(test, self.ENODEDRBD, node,
1680
             "cannot parse drbd status file: %s", str(used_minors))
1681
    if test:
1682
      # we cannot check drbd status
1683
      return
1684

    
1685
    for minor, (iname, must_exist) in node_drbd.items():
1686
      test = minor not in used_minors and must_exist
1687
      _ErrorIf(test, self.ENODEDRBD, node,
1688
               "drbd minor %d of instance %s is not active", minor, iname)
1689
    for minor in used_minors:
1690
      test = minor not in node_drbd
1691
      _ErrorIf(test, self.ENODEDRBD, node,
1692
               "unallocated drbd minor %d is in use", minor)
1693

    
1694
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1695
    """Builds the node OS structures.
1696

1697
    @type ninfo: L{objects.Node}
1698
    @param ninfo: the node to check
1699
    @param nresult: the remote results for the node
1700
    @param nimg: the node image object
1701

1702
    """
1703
    node = ninfo.name
1704
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1705

    
1706
    remote_os = nresult.get(constants.NV_OSLIST, None)
1707
    test = (not isinstance(remote_os, list) or
1708
            not compat.all(isinstance(v, list) and len(v) == 7
1709
                           for v in remote_os))
1710

    
1711
    _ErrorIf(test, self.ENODEOS, node,
1712
             "node hasn't returned valid OS data")
1713

    
1714
    nimg.os_fail = test
1715

    
1716
    if test:
1717
      return
1718

    
1719
    os_dict = {}
1720

    
1721
    for (name, os_path, status, diagnose,
1722
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1723

    
1724
      if name not in os_dict:
1725
        os_dict[name] = []
1726

    
1727
      # parameters is a list of lists instead of list of tuples due to
1728
      # JSON lacking a real tuple type, fix it:
1729
      parameters = [tuple(v) for v in parameters]
1730
      os_dict[name].append((os_path, status, diagnose,
1731
                            set(variants), set(parameters), set(api_ver)))
1732

    
1733
    nimg.oslist = os_dict
1734

    
1735
  def _VerifyNodeOS(self, ninfo, nimg, base):
1736
    """Verifies the node OS list.
1737

1738
    @type ninfo: L{objects.Node}
1739
    @param ninfo: the node to check
1740
    @param nimg: the node image object
1741
    @param base: the 'template' node we match against (e.g. from the master)
1742

1743
    """
1744
    node = ninfo.name
1745
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1746

    
1747
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1748

    
1749
    for os_name, os_data in nimg.oslist.items():
1750
      assert os_data, "Empty OS status for OS %s?!" % os_name
1751
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1752
      _ErrorIf(not f_status, self.ENODEOS, node,
1753
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1754
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1755
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1756
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1757
      # this will catched in backend too
1758
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1759
               and not f_var, self.ENODEOS, node,
1760
               "OS %s with API at least %d does not declare any variant",
1761
               os_name, constants.OS_API_V15)
1762
      # comparisons with the 'base' image
1763
      test = os_name not in base.oslist
1764
      _ErrorIf(test, self.ENODEOS, node,
1765
               "Extra OS %s not present on reference node (%s)",
1766
               os_name, base.name)
1767
      if test:
1768
        continue
1769
      assert base.oslist[os_name], "Base node has empty OS status?"
1770
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1771
      if not b_status:
1772
        # base OS is invalid, skipping
1773
        continue
1774
      for kind, a, b in [("API version", f_api, b_api),
1775
                         ("variants list", f_var, b_var),
1776
                         ("parameters", f_param, b_param)]:
1777
        _ErrorIf(a != b, self.ENODEOS, node,
1778
                 "OS %s %s differs from reference node %s: %s vs. %s",
1779
                 kind, os_name, base.name,
1780
                 utils.CommaJoin(a), utils.CommaJoin(b))
1781

    
1782
    # check any missing OSes
1783
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1784
    _ErrorIf(missing, self.ENODEOS, node,
1785
             "OSes present on reference node %s but missing on this node: %s",
1786
             base.name, utils.CommaJoin(missing))
1787

    
1788
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1789
    """Verifies and updates the node volume data.
1790

1791
    This function will update a L{NodeImage}'s internal structures
1792
    with data from the remote call.
1793

1794
    @type ninfo: L{objects.Node}
1795
    @param ninfo: the node to check
1796
    @param nresult: the remote results for the node
1797
    @param nimg: the node image object
1798
    @param vg_name: the configured VG name
1799

1800
    """
1801
    node = ninfo.name
1802
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1803

    
1804
    nimg.lvm_fail = True
1805
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1806
    if vg_name is None:
1807
      pass
1808
    elif isinstance(lvdata, basestring):
1809
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1810
               utils.SafeEncode(lvdata))
1811
    elif not isinstance(lvdata, dict):
1812
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1813
    else:
1814
      nimg.volumes = lvdata
1815
      nimg.lvm_fail = False
1816

    
1817
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1818
    """Verifies and updates the node instance list.
1819

1820
    If the listing was successful, then updates this node's instance
1821
    list. Otherwise, it marks the RPC call as failed for the instance
1822
    list key.
1823

1824
    @type ninfo: L{objects.Node}
1825
    @param ninfo: the node to check
1826
    @param nresult: the remote results for the node
1827
    @param nimg: the node image object
1828

1829
    """
1830
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1831
    test = not isinstance(idata, list)
1832
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1833
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1834
    if test:
1835
      nimg.hyp_fail = True
1836
    else:
1837
      nimg.instances = idata
1838

    
1839
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1840
    """Verifies and computes a node information map
1841

1842
    @type ninfo: L{objects.Node}
1843
    @param ninfo: the node to check
1844
    @param nresult: the remote results for the node
1845
    @param nimg: the node image object
1846
    @param vg_name: the configured VG name
1847

1848
    """
1849
    node = ninfo.name
1850
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1851

    
1852
    # try to read free memory (from the hypervisor)
1853
    hv_info = nresult.get(constants.NV_HVINFO, None)
1854
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1855
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1856
    if not test:
1857
      try:
1858
        nimg.mfree = int(hv_info["memory_free"])
1859
      except (ValueError, TypeError):
1860
        _ErrorIf(True, self.ENODERPC, node,
1861
                 "node returned invalid nodeinfo, check hypervisor")
1862

    
1863
    # FIXME: devise a free space model for file based instances as well
1864
    if vg_name is not None:
1865
      test = (constants.NV_VGLIST not in nresult or
1866
              vg_name not in nresult[constants.NV_VGLIST])
1867
      _ErrorIf(test, self.ENODELVM, node,
1868
               "node didn't return data for the volume group '%s'"
1869
               " - it is either missing or broken", vg_name)
1870
      if not test:
1871
        try:
1872
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1873
        except (ValueError, TypeError):
1874
          _ErrorIf(True, self.ENODERPC, node,
1875
                   "node returned invalid LVM info, check LVM status")
1876

    
1877
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
1878
    """Gets per-disk status information for all instances.
1879

1880
    @type nodelist: list of strings
1881
    @param nodelist: Node names
1882
    @type node_image: dict of (name, L{objects.Node})
1883
    @param node_image: Node objects
1884
    @type instanceinfo: dict of (name, L{objects.Instance})
1885
    @param instanceinfo: Instance objects
1886

1887
    """
1888
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1889

    
1890
    node_disks = {}
1891
    node_disks_devonly = {}
1892

    
1893
    for nname in nodelist:
1894
      disks = [(inst, disk)
1895
               for instlist in [node_image[nname].pinst,
1896
                                node_image[nname].sinst]
1897
               for inst in instlist
1898
               for disk in instanceinfo[inst].disks]
1899

    
1900
      if not disks:
1901
        # No need to collect data
1902
        continue
1903

    
1904
      node_disks[nname] = disks
1905

    
1906
      # Creating copies as SetDiskID below will modify the objects and that can
1907
      # lead to incorrect data returned from nodes
1908
      devonly = [dev.Copy() for (_, dev) in disks]
1909

    
1910
      for dev in devonly:
1911
        self.cfg.SetDiskID(dev, nname)
1912

    
1913
      node_disks_devonly[nname] = devonly
1914

    
1915
    assert len(node_disks) == len(node_disks_devonly)
1916

    
1917
    # Collect data from all nodes with disks
1918
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
1919
                                                          node_disks_devonly)
1920

    
1921
    assert len(result) == len(node_disks)
1922

    
1923
    instdisk = {}
1924

    
1925
    for (nname, nres) in result.items():
1926
      if nres.offline:
1927
        # Ignore offline node
1928
        continue
1929

    
1930
      disks = node_disks[nname]
1931

    
1932
      msg = nres.fail_msg
1933
      _ErrorIf(msg, self.ENODERPC, nname,
1934
               "while getting disk information: %s", nres.fail_msg)
1935
      if msg:
1936
        # No data from this node
1937
        data = len(disks) * [None]
1938
      else:
1939
        data = nres.payload
1940

    
1941
      for ((inst, _), status) in zip(disks, data):
1942
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
1943

    
1944
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
1945
                      len(nnames) <= len(instanceinfo[inst].all_nodes)
1946
                      for inst, nnames in instdisk.items()
1947
                      for nname, statuses in nnames.items())
1948

    
1949
    return instdisk
1950

    
1951
  def BuildHooksEnv(self):
1952
    """Build hooks env.
1953

1954
    Cluster-Verify hooks just ran in the post phase and their failure makes
1955
    the output be logged in the verify output and the verification to fail.
1956

1957
    """
1958
    all_nodes = self.cfg.GetNodeList()
1959
    env = {
1960
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1961
      }
1962
    for node in self.cfg.GetAllNodesInfo().values():
1963
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1964

    
1965
    return env, [], all_nodes
1966

    
1967
  def Exec(self, feedback_fn):
1968
    """Verify integrity of cluster, performing various test on nodes.
1969

1970
    """
1971
    self.bad = False
1972
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1973
    verbose = self.op.verbose
1974
    self._feedback_fn = feedback_fn
1975
    feedback_fn("* Verifying global settings")
1976
    for msg in self.cfg.VerifyConfig():
1977
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1978

    
1979
    # Check the cluster certificates
1980
    for cert_filename in constants.ALL_CERT_FILES:
1981
      (errcode, msg) = _VerifyCertificate(cert_filename)
1982
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1983

    
1984
    vg_name = self.cfg.GetVGName()
1985
    drbd_helper = self.cfg.GetDRBDHelper()
1986
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1987
    cluster = self.cfg.GetClusterInfo()
1988
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1989
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1990
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1991
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1992
                        for iname in instancelist)
1993
    i_non_redundant = [] # Non redundant instances
1994
    i_non_a_balanced = [] # Non auto-balanced instances
1995
    n_offline = 0 # Count of offline nodes
1996
    n_drained = 0 # Count of nodes being drained
1997
    node_vol_should = {}
1998

    
1999
    # FIXME: verify OS list
2000
    # do local checksums
2001
    master_files = [constants.CLUSTER_CONF_FILE]
2002
    master_node = self.master_node = self.cfg.GetMasterNode()
2003
    master_ip = self.cfg.GetMasterIP()
2004

    
2005
    file_names = ssconf.SimpleStore().GetFileList()
2006
    file_names.extend(constants.ALL_CERT_FILES)
2007
    file_names.extend(master_files)
2008
    if cluster.modify_etc_hosts:
2009
      file_names.append(constants.ETC_HOSTS)
2010

    
2011
    local_checksums = utils.FingerprintFiles(file_names)
2012

    
2013
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2014
    node_verify_param = {
2015
      constants.NV_FILELIST: file_names,
2016
      constants.NV_NODELIST: [node.name for node in nodeinfo
2017
                              if not node.offline],
2018
      constants.NV_HYPERVISOR: hypervisors,
2019
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2020
                                  node.secondary_ip) for node in nodeinfo
2021
                                 if not node.offline],
2022
      constants.NV_INSTANCELIST: hypervisors,
2023
      constants.NV_VERSION: None,
2024
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2025
      constants.NV_NODESETUP: None,
2026
      constants.NV_TIME: None,
2027
      constants.NV_MASTERIP: (master_node, master_ip),
2028
      constants.NV_OSLIST: None,
2029
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2030
      }
2031

    
2032
    if vg_name is not None:
2033
      node_verify_param[constants.NV_VGLIST] = None
2034
      node_verify_param[constants.NV_LVLIST] = vg_name
2035
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2036
      node_verify_param[constants.NV_DRBDLIST] = None
2037

    
2038
    if drbd_helper:
2039
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2040

    
2041
    # Build our expected cluster state
2042
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2043
                                                 name=node.name,
2044
                                                 vm_capable=node.vm_capable))
2045
                      for node in nodeinfo)
2046

    
2047
    for instance in instancelist:
2048
      inst_config = instanceinfo[instance]
2049

    
2050
      for nname in inst_config.all_nodes:
2051
        if nname not in node_image:
2052
          # ghost node
2053
          gnode = self.NodeImage(name=nname)
2054
          gnode.ghost = True
2055
          node_image[nname] = gnode
2056

    
2057
      inst_config.MapLVsByNode(node_vol_should)
2058

    
2059
      pnode = inst_config.primary_node
2060
      node_image[pnode].pinst.append(instance)
2061

    
2062
      for snode in inst_config.secondary_nodes:
2063
        nimg = node_image[snode]
2064
        nimg.sinst.append(instance)
2065
        if pnode not in nimg.sbp:
2066
          nimg.sbp[pnode] = []
2067
        nimg.sbp[pnode].append(instance)
2068

    
2069
    # At this point, we have the in-memory data structures complete,
2070
    # except for the runtime information, which we'll gather next
2071

    
2072
    # Due to the way our RPC system works, exact response times cannot be
2073
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2074
    # time before and after executing the request, we can at least have a time
2075
    # window.
2076
    nvinfo_starttime = time.time()
2077
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2078
                                           self.cfg.GetClusterName())
2079
    nvinfo_endtime = time.time()
2080

    
2081
    all_drbd_map = self.cfg.ComputeDRBDMap()
2082

    
2083
    feedback_fn("* Gathering disk information (%s nodes)" % len(nodelist))
2084
    instdisk = self._CollectDiskInfo(nodelist, node_image, instanceinfo)
2085

    
2086
    feedback_fn("* Verifying node status")
2087

    
2088
    refos_img = None
2089

    
2090
    for node_i in nodeinfo:
2091
      node = node_i.name
2092
      nimg = node_image[node]
2093

    
2094
      if node_i.offline:
2095
        if verbose:
2096
          feedback_fn("* Skipping offline node %s" % (node,))
2097
        n_offline += 1
2098
        continue
2099

    
2100
      if node == master_node:
2101
        ntype = "master"
2102
      elif node_i.master_candidate:
2103
        ntype = "master candidate"
2104
      elif node_i.drained:
2105
        ntype = "drained"
2106
        n_drained += 1
2107
      else:
2108
        ntype = "regular"
2109
      if verbose:
2110
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2111

    
2112
      msg = all_nvinfo[node].fail_msg
2113
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2114
      if msg:
2115
        nimg.rpc_fail = True
2116
        continue
2117

    
2118
      nresult = all_nvinfo[node].payload
2119

    
2120
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2121
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2122
      self._VerifyNodeNetwork(node_i, nresult)
2123
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2124
                            master_files)
2125

    
2126
      if nimg.vm_capable:
2127
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2128
        self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2129
                             all_drbd_map)
2130

    
2131
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2132
        self._UpdateNodeInstances(node_i, nresult, nimg)
2133
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2134
        self._UpdateNodeOS(node_i, nresult, nimg)
2135
        if not nimg.os_fail:
2136
          if refos_img is None:
2137
            refos_img = nimg
2138
          self._VerifyNodeOS(node_i, nimg, refos_img)
2139

    
2140
    feedback_fn("* Verifying instance status")
2141
    for instance in instancelist:
2142
      if verbose:
2143
        feedback_fn("* Verifying instance %s" % instance)
2144
      inst_config = instanceinfo[instance]
2145
      self._VerifyInstance(instance, inst_config, node_image,
2146
                           instdisk[instance])
2147
      inst_nodes_offline = []
2148

    
2149
      pnode = inst_config.primary_node
2150
      pnode_img = node_image[pnode]
2151
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2152
               self.ENODERPC, pnode, "instance %s, connection to"
2153
               " primary node failed", instance)
2154

    
2155
      if pnode_img.offline:
2156
        inst_nodes_offline.append(pnode)
2157

    
2158
      # If the instance is non-redundant we cannot survive losing its primary
2159
      # node, so we are not N+1 compliant. On the other hand we have no disk
2160
      # templates with more than one secondary so that situation is not well
2161
      # supported either.
2162
      # FIXME: does not support file-backed instances
2163
      if not inst_config.secondary_nodes:
2164
        i_non_redundant.append(instance)
2165
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2166
               instance, "instance has multiple secondary nodes: %s",
2167
               utils.CommaJoin(inst_config.secondary_nodes),
2168
               code=self.ETYPE_WARNING)
2169

    
2170
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2171
        i_non_a_balanced.append(instance)
2172

    
2173
      for snode in inst_config.secondary_nodes:
2174
        s_img = node_image[snode]
2175
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2176
                 "instance %s, connection to secondary node failed", instance)
2177

    
2178
        if s_img.offline:
2179
          inst_nodes_offline.append(snode)
2180

    
2181
      # warn that the instance lives on offline nodes
2182
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2183
               "instance lives on offline node(s) %s",
2184
               utils.CommaJoin(inst_nodes_offline))
2185
      # ... or ghost/non-vm_capable nodes
2186
      for node in inst_config.all_nodes:
2187
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2188
                 "instance lives on ghost node %s", node)
2189
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2190
                 instance, "instance lives on non-vm_capable node %s", node)
2191

    
2192
    feedback_fn("* Verifying orphan volumes")
2193
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2194
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2195

    
2196
    feedback_fn("* Verifying orphan instances")
2197
    self._VerifyOrphanInstances(instancelist, node_image)
2198

    
2199
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2200
      feedback_fn("* Verifying N+1 Memory redundancy")
2201
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2202

    
2203
    feedback_fn("* Other Notes")
2204
    if i_non_redundant:
2205
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2206
                  % len(i_non_redundant))
2207

    
2208
    if i_non_a_balanced:
2209
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2210
                  % len(i_non_a_balanced))
2211

    
2212
    if n_offline:
2213
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2214

    
2215
    if n_drained:
2216
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2217

    
2218
    return not self.bad
2219

    
2220
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2221
    """Analyze the post-hooks' result
2222

2223
    This method analyses the hook result, handles it, and sends some
2224
    nicely-formatted feedback back to the user.
2225

2226
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2227
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2228
    @param hooks_results: the results of the multi-node hooks rpc call
2229
    @param feedback_fn: function used send feedback back to the caller
2230
    @param lu_result: previous Exec result
2231
    @return: the new Exec result, based on the previous result
2232
        and hook results
2233

2234
    """
2235
    # We only really run POST phase hooks, and are only interested in
2236
    # their results
2237
    if phase == constants.HOOKS_PHASE_POST:
2238
      # Used to change hooks' output to proper indentation
2239
      indent_re = re.compile('^', re.M)
2240
      feedback_fn("* Hooks Results")
2241
      assert hooks_results, "invalid result from hooks"
2242

    
2243
      for node_name in hooks_results:
2244
        res = hooks_results[node_name]
2245
        msg = res.fail_msg
2246
        test = msg and not res.offline
2247
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2248
                      "Communication failure in hooks execution: %s", msg)
2249
        if res.offline or msg:
2250
          # No need to investigate payload if node is offline or gave an error.
2251
          # override manually lu_result here as _ErrorIf only
2252
          # overrides self.bad
2253
          lu_result = 1
2254
          continue
2255
        for script, hkr, output in res.payload:
2256
          test = hkr == constants.HKR_FAIL
2257
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2258
                        "Script %s failed, output:", script)
2259
          if test:
2260
            output = indent_re.sub('      ', output)
2261
            feedback_fn("%s" % output)
2262
            lu_result = 0
2263

    
2264
      return lu_result
2265

    
2266

    
2267
class LUVerifyDisks(NoHooksLU):
2268
  """Verifies the cluster disks status.
2269

2270
  """
2271
  REQ_BGL = False
2272

    
2273
  def ExpandNames(self):
2274
    self.needed_locks = {
2275
      locking.LEVEL_NODE: locking.ALL_SET,
2276
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2277
    }
2278
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2279

    
2280
  def Exec(self, feedback_fn):
2281
    """Verify integrity of cluster disks.
2282

2283
    @rtype: tuple of three items
2284
    @return: a tuple of (dict of node-to-node_error, list of instances
2285
        which need activate-disks, dict of instance: (node, volume) for
2286
        missing volumes
2287

2288
    """
2289
    result = res_nodes, res_instances, res_missing = {}, [], {}
2290

    
2291
    vg_name = self.cfg.GetVGName()
2292
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2293
    instances = [self.cfg.GetInstanceInfo(name)
2294
                 for name in self.cfg.GetInstanceList()]
2295

    
2296
    nv_dict = {}
2297
    for inst in instances:
2298
      inst_lvs = {}
2299
      if (not inst.admin_up or
2300
          inst.disk_template not in constants.DTS_NET_MIRROR):
2301
        continue
2302
      inst.MapLVsByNode(inst_lvs)
2303
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2304
      for node, vol_list in inst_lvs.iteritems():
2305
        for vol in vol_list:
2306
          nv_dict[(node, vol)] = inst
2307

    
2308
    if not nv_dict:
2309
      return result
2310

    
2311
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2312

    
2313
    for node in nodes:
2314
      # node_volume
2315
      node_res = node_lvs[node]
2316
      if node_res.offline:
2317
        continue
2318
      msg = node_res.fail_msg
2319
      if msg:
2320
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2321
        res_nodes[node] = msg
2322
        continue
2323

    
2324
      lvs = node_res.payload
2325
      for lv_name, (_, _, lv_online) in lvs.items():
2326
        inst = nv_dict.pop((node, lv_name), None)
2327
        if (not lv_online and inst is not None
2328
            and inst.name not in res_instances):
2329
          res_instances.append(inst.name)
2330

    
2331
    # any leftover items in nv_dict are missing LVs, let's arrange the
2332
    # data better
2333
    for key, inst in nv_dict.iteritems():
2334
      if inst.name not in res_missing:
2335
        res_missing[inst.name] = []
2336
      res_missing[inst.name].append(key)
2337

    
2338
    return result
2339

    
2340

    
2341
class LURepairDiskSizes(NoHooksLU):
2342
  """Verifies the cluster disks sizes.
2343

2344
  """
2345
  _OP_PARAMS = [("instances", ht.EmptyList, ht.TListOf(ht.TNonEmptyString))]
2346
  REQ_BGL = False
2347

    
2348
  def ExpandNames(self):
2349
    if self.op.instances:
2350
      self.wanted_names = []
2351
      for name in self.op.instances:
2352
        full_name = _ExpandInstanceName(self.cfg, name)
2353
        self.wanted_names.append(full_name)
2354
      self.needed_locks = {
2355
        locking.LEVEL_NODE: [],
2356
        locking.LEVEL_INSTANCE: self.wanted_names,
2357
        }
2358
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2359
    else:
2360
      self.wanted_names = None
2361
      self.needed_locks = {
2362
        locking.LEVEL_NODE: locking.ALL_SET,
2363
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2364
        }
2365
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2366

    
2367
  def DeclareLocks(self, level):
2368
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2369
      self._LockInstancesNodes(primary_only=True)
2370

    
2371
  def CheckPrereq(self):
2372
    """Check prerequisites.
2373

2374
    This only checks the optional instance list against the existing names.
2375

2376
    """
2377
    if self.wanted_names is None:
2378
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2379

    
2380
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2381
                             in self.wanted_names]
2382

    
2383
  def _EnsureChildSizes(self, disk):
2384
    """Ensure children of the disk have the needed disk size.
2385

2386
    This is valid mainly for DRBD8 and fixes an issue where the
2387
    children have smaller disk size.
2388

2389
    @param disk: an L{ganeti.objects.Disk} object
2390

2391
    """
2392
    if disk.dev_type == constants.LD_DRBD8:
2393
      assert disk.children, "Empty children for DRBD8?"
2394
      fchild = disk.children[0]
2395
      mismatch = fchild.size < disk.size
2396
      if mismatch:
2397
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2398
                     fchild.size, disk.size)
2399
        fchild.size = disk.size
2400

    
2401
      # and we recurse on this child only, not on the metadev
2402
      return self._EnsureChildSizes(fchild) or mismatch
2403
    else:
2404
      return False
2405

    
2406
  def Exec(self, feedback_fn):
2407
    """Verify the size of cluster disks.
2408

2409
    """
2410
    # TODO: check child disks too
2411
    # TODO: check differences in size between primary/secondary nodes
2412
    per_node_disks = {}
2413
    for instance in self.wanted_instances:
2414
      pnode = instance.primary_node
2415
      if pnode not in per_node_disks:
2416
        per_node_disks[pnode] = []
2417
      for idx, disk in enumerate(instance.disks):
2418
        per_node_disks[pnode].append((instance, idx, disk))
2419

    
2420
    changed = []
2421
    for node, dskl in per_node_disks.items():
2422
      newl = [v[2].Copy() for v in dskl]
2423
      for dsk in newl:
2424
        self.cfg.SetDiskID(dsk, node)
2425
      result = self.rpc.call_blockdev_getsizes(node, newl)
2426
      if result.fail_msg:
2427
        self.LogWarning("Failure in blockdev_getsizes call to node"
2428
                        " %s, ignoring", node)
2429
        continue
2430
      if len(result.data) != len(dskl):
2431
        self.LogWarning("Invalid result from node %s, ignoring node results",
2432
                        node)
2433
        continue
2434
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2435
        if size is None:
2436
          self.LogWarning("Disk %d of instance %s did not return size"
2437
                          " information, ignoring", idx, instance.name)
2438
          continue
2439
        if not isinstance(size, (int, long)):
2440
          self.LogWarning("Disk %d of instance %s did not return valid"
2441
                          " size information, ignoring", idx, instance.name)
2442
          continue
2443
        size = size >> 20
2444
        if size != disk.size:
2445
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2446
                       " correcting: recorded %d, actual %d", idx,
2447
                       instance.name, disk.size, size)
2448
          disk.size = size
2449
          self.cfg.Update(instance, feedback_fn)
2450
          changed.append((instance.name, idx, size))
2451
        if self._EnsureChildSizes(disk):
2452
          self.cfg.Update(instance, feedback_fn)
2453
          changed.append((instance.name, idx, disk.size))
2454
    return changed
2455

    
2456

    
2457
class LURenameCluster(LogicalUnit):
2458
  """Rename the cluster.
2459

2460
  """
2461
  HPATH = "cluster-rename"
2462
  HTYPE = constants.HTYPE_CLUSTER
2463
  _OP_PARAMS = [("name", ht.NoDefault, ht.TNonEmptyString)]
2464

    
2465
  def BuildHooksEnv(self):
2466
    """Build hooks env.
2467

2468
    """
2469
    env = {
2470
      "OP_TARGET": self.cfg.GetClusterName(),
2471
      "NEW_NAME": self.op.name,
2472
      }
2473
    mn = self.cfg.GetMasterNode()
2474
    all_nodes = self.cfg.GetNodeList()
2475
    return env, [mn], all_nodes
2476

    
2477
  def CheckPrereq(self):
2478
    """Verify that the passed name is a valid one.
2479

2480
    """
2481
    hostname = netutils.GetHostname(name=self.op.name,
2482
                                    family=self.cfg.GetPrimaryIPFamily())
2483

    
2484
    new_name = hostname.name
2485
    self.ip = new_ip = hostname.ip
2486
    old_name = self.cfg.GetClusterName()
2487
    old_ip = self.cfg.GetMasterIP()
2488
    if new_name == old_name and new_ip == old_ip:
2489
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2490
                                 " cluster has changed",
2491
                                 errors.ECODE_INVAL)
2492
    if new_ip != old_ip:
2493
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2494
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2495
                                   " reachable on the network" %
2496
                                   new_ip, errors.ECODE_NOTUNIQUE)
2497

    
2498
    self.op.name = new_name
2499

    
2500
  def Exec(self, feedback_fn):
2501
    """Rename the cluster.
2502

2503
    """
2504
    clustername = self.op.name
2505
    ip = self.ip
2506

    
2507
    # shutdown the master IP
2508
    master = self.cfg.GetMasterNode()
2509
    result = self.rpc.call_node_stop_master(master, False)
2510
    result.Raise("Could not disable the master role")
2511

    
2512
    try:
2513
      cluster = self.cfg.GetClusterInfo()
2514
      cluster.cluster_name = clustername
2515
      cluster.master_ip = ip
2516
      self.cfg.Update(cluster, feedback_fn)
2517

    
2518
      # update the known hosts file
2519
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2520
      node_list = self.cfg.GetNodeList()
2521
      try:
2522
        node_list.remove(master)
2523
      except ValueError:
2524
        pass
2525
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2526
    finally:
2527
      result = self.rpc.call_node_start_master(master, False, False)
2528
      msg = result.fail_msg
2529
      if msg:
2530
        self.LogWarning("Could not re-enable the master role on"
2531
                        " the master, please restart manually: %s", msg)
2532

    
2533
    return clustername
2534

    
2535

    
2536
class LUSetClusterParams(LogicalUnit):
2537
  """Change the parameters of the cluster.
2538

2539
  """
2540
  HPATH = "cluster-modify"
2541
  HTYPE = constants.HTYPE_CLUSTER
2542
  _OP_PARAMS = [
2543
    ("vg_name", None, ht.TMaybeString),
2544
    ("enabled_hypervisors", None,
2545
     ht.TOr(ht.TAnd(ht.TListOf(ht.TElemOf(constants.HYPER_TYPES)), ht.TTrue),
2546
            ht.TNone)),
2547
    ("hvparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2548
                              ht.TNone)),
2549
    ("beparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2550
                              ht.TNone)),
2551
    ("os_hvp", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2552
                            ht.TNone)),
2553
    ("osparams", None, ht.TOr(ht.TDictOf(ht.TNonEmptyString, ht.TDict),
2554
                              ht.TNone)),
2555
    ("candidate_pool_size", None, ht.TOr(ht.TStrictPositiveInt, ht.TNone)),
2556
    ("uid_pool", None, ht.NoType),
2557
    ("add_uids", None, ht.NoType),
2558
    ("remove_uids", None, ht.NoType),
2559
    ("maintain_node_health", None, ht.TMaybeBool),
2560
    ("prealloc_wipe_disks", None, ht.TMaybeBool),
2561
    ("nicparams", None, ht.TOr(ht.TDict, ht.TNone)),
2562
    ("drbd_helper", None, ht.TOr(ht.TString, ht.TNone)),
2563
    ("default_iallocator", None, ht.TOr(ht.TString, ht.TNone)),
2564
    ("reserved_lvs", None, ht.TOr(ht.TListOf(ht.TNonEmptyString), ht.TNone)),
2565
    ("hidden_os", None, ht.TOr(ht.TListOf(\
2566
          ht.TAnd(ht.TList,
2567
                ht.TIsLength(2),
2568
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2569
          ht.TNone)),
2570
    ("blacklisted_os", None, ht.TOr(ht.TListOf(\
2571
          ht.TAnd(ht.TList,
2572
                ht.TIsLength(2),
2573
                ht.TMap(lambda v: v[0], ht.TElemOf(constants.DDMS_VALUES)))),
2574
          ht.TNone)),
2575
    ]
2576
  REQ_BGL = False
2577

    
2578
  def CheckArguments(self):
2579
    """Check parameters
2580

2581
    """
2582
    if self.op.uid_pool:
2583
      uidpool.CheckUidPool(self.op.uid_pool)
2584

    
2585
    if self.op.add_uids:
2586
      uidpool.CheckUidPool(self.op.add_uids)
2587

    
2588
    if self.op.remove_uids:
2589
      uidpool.CheckUidPool(self.op.remove_uids)
2590

    
2591
  def ExpandNames(self):
2592
    # FIXME: in the future maybe other cluster params won't require checking on
2593
    # all nodes to be modified.
2594
    self.needed_locks = {
2595
      locking.LEVEL_NODE: locking.ALL_SET,
2596
    }
2597
    self.share_locks[locking.LEVEL_NODE] = 1
2598

    
2599
  def BuildHooksEnv(self):
2600
    """Build hooks env.
2601

2602
    """
2603
    env = {
2604
      "OP_TARGET": self.cfg.GetClusterName(),
2605
      "NEW_VG_NAME": self.op.vg_name,
2606
      }
2607
    mn = self.cfg.GetMasterNode()
2608
    return env, [mn], [mn]
2609

    
2610
  def CheckPrereq(self):
2611
    """Check prerequisites.
2612

2613
    This checks whether the given params don't conflict and
2614
    if the given volume group is valid.
2615

2616
    """
2617
    if self.op.vg_name is not None and not self.op.vg_name:
2618
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2619
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2620
                                   " instances exist", errors.ECODE_INVAL)
2621

    
2622
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2623
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2624
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2625
                                   " drbd-based instances exist",
2626
                                   errors.ECODE_INVAL)
2627

    
2628
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2629

    
2630
    # if vg_name not None, checks given volume group on all nodes
2631
    if self.op.vg_name:
2632
      vglist = self.rpc.call_vg_list(node_list)
2633
      for node in node_list:
2634
        msg = vglist[node].fail_msg
2635
        if msg:
2636
          # ignoring down node
2637
          self.LogWarning("Error while gathering data on node %s"
2638
                          " (ignoring node): %s", node, msg)
2639
          continue
2640
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2641
                                              self.op.vg_name,
2642
                                              constants.MIN_VG_SIZE)
2643
        if vgstatus:
2644
          raise errors.OpPrereqError("Error on node '%s': %s" %
2645
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2646

    
2647
    if self.op.drbd_helper:
2648
      # checks given drbd helper on all nodes
2649
      helpers = self.rpc.call_drbd_helper(node_list)
2650
      for node in node_list:
2651
        ninfo = self.cfg.GetNodeInfo(node)
2652
        if ninfo.offline:
2653
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2654
          continue
2655
        msg = helpers[node].fail_msg
2656
        if msg:
2657
          raise errors.OpPrereqError("Error checking drbd helper on node"
2658
                                     " '%s': %s" % (node, msg),
2659
                                     errors.ECODE_ENVIRON)
2660
        node_helper = helpers[node].payload
2661
        if node_helper != self.op.drbd_helper:
2662
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2663
                                     (node, node_helper), errors.ECODE_ENVIRON)
2664

    
2665
    self.cluster = cluster = self.cfg.GetClusterInfo()
2666
    # validate params changes
2667
    if self.op.beparams:
2668
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2669
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2670

    
2671
    if self.op.nicparams:
2672
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2673
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2674
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2675
      nic_errors = []
2676

    
2677
      # check all instances for consistency
2678
      for instance in self.cfg.GetAllInstancesInfo().values():
2679
        for nic_idx, nic in enumerate(instance.nics):
2680
          params_copy = copy.deepcopy(nic.nicparams)
2681
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2682

    
2683
          # check parameter syntax
2684
          try:
2685
            objects.NIC.CheckParameterSyntax(params_filled)
2686
          except errors.ConfigurationError, err:
2687
            nic_errors.append("Instance %s, nic/%d: %s" %
2688
                              (instance.name, nic_idx, err))
2689

    
2690
          # if we're moving instances to routed, check that they have an ip
2691
          target_mode = params_filled[constants.NIC_MODE]
2692
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2693
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2694
                              (instance.name, nic_idx))
2695
      if nic_errors:
2696
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2697
                                   "\n".join(nic_errors))
2698

    
2699
    # hypervisor list/parameters
2700
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2701
    if self.op.hvparams:
2702
      for hv_name, hv_dict in self.op.hvparams.items():
2703
        if hv_name not in self.new_hvparams:
2704
          self.new_hvparams[hv_name] = hv_dict
2705
        else:
2706
          self.new_hvparams[hv_name].update(hv_dict)
2707

    
2708
    # os hypervisor parameters
2709
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2710
    if self.op.os_hvp:
2711
      for os_name, hvs in self.op.os_hvp.items():
2712
        if os_name not in self.new_os_hvp:
2713
          self.new_os_hvp[os_name] = hvs
2714
        else:
2715
          for hv_name, hv_dict in hvs.items():
2716
            if hv_name not in self.new_os_hvp[os_name]:
2717
              self.new_os_hvp[os_name][hv_name] = hv_dict
2718
            else:
2719
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2720

    
2721
    # os parameters
2722
    self.new_osp = objects.FillDict(cluster.osparams, {})
2723
    if self.op.osparams:
2724
      for os_name, osp in self.op.osparams.items():
2725
        if os_name not in self.new_osp:
2726
          self.new_osp[os_name] = {}
2727

    
2728
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2729
                                                  use_none=True)
2730

    
2731
        if not self.new_osp[os_name]:
2732
          # we removed all parameters
2733
          del self.new_osp[os_name]
2734
        else:
2735
          # check the parameter validity (remote check)
2736
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2737
                         os_name, self.new_osp[os_name])
2738

    
2739
    # changes to the hypervisor list
2740
    if self.op.enabled_hypervisors is not None:
2741
      self.hv_list = self.op.enabled_hypervisors
2742
      for hv in self.hv_list:
2743
        # if the hypervisor doesn't already exist in the cluster
2744
        # hvparams, we initialize it to empty, and then (in both
2745
        # cases) we make sure to fill the defaults, as we might not
2746
        # have a complete defaults list if the hypervisor wasn't
2747
        # enabled before
2748
        if hv not in new_hvp:
2749
          new_hvp[hv] = {}
2750
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2751
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2752
    else:
2753
      self.hv_list = cluster.enabled_hypervisors
2754

    
2755
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2756
      # either the enabled list has changed, or the parameters have, validate
2757
      for hv_name, hv_params in self.new_hvparams.items():
2758
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2759
            (self.op.enabled_hypervisors and
2760
             hv_name in self.op.enabled_hypervisors)):
2761
          # either this is a new hypervisor, or its parameters have changed
2762
          hv_class = hypervisor.GetHypervisor(hv_name)
2763
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2764
          hv_class.CheckParameterSyntax(hv_params)
2765
          _CheckHVParams(self, node_list, hv_name, hv_params)
2766

    
2767
    if self.op.os_hvp:
2768
      # no need to check any newly-enabled hypervisors, since the
2769
      # defaults have already been checked in the above code-block
2770
      for os_name, os_hvp in self.new_os_hvp.items():
2771
        for hv_name, hv_params in os_hvp.items():
2772
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2773
          # we need to fill in the new os_hvp on top of the actual hv_p
2774
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2775
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2776
          hv_class = hypervisor.GetHypervisor(hv_name)
2777
          hv_class.CheckParameterSyntax(new_osp)
2778
          _CheckHVParams(self, node_list, hv_name, new_osp)
2779

    
2780
    if self.op.default_iallocator:
2781
      alloc_script = utils.FindFile(self.op.default_iallocator,
2782
                                    constants.IALLOCATOR_SEARCH_PATH,
2783
                                    os.path.isfile)
2784
      if alloc_script is None:
2785
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2786
                                   " specified" % self.op.default_iallocator,
2787
                                   errors.ECODE_INVAL)
2788

    
2789
  def Exec(self, feedback_fn):
2790
    """Change the parameters of the cluster.
2791

2792
    """
2793
    if self.op.vg_name is not None:
2794
      new_volume = self.op.vg_name
2795
      if not new_volume:
2796
        new_volume = None
2797
      if new_volume != self.cfg.GetVGName():
2798
        self.cfg.SetVGName(new_volume)
2799
      else:
2800
        feedback_fn("Cluster LVM configuration already in desired"
2801
                    " state, not changing")
2802
    if self.op.drbd_helper is not None:
2803
      new_helper = self.op.drbd_helper
2804
      if not new_helper:
2805
        new_helper = None
2806
      if new_helper != self.cfg.GetDRBDHelper():
2807
        self.cfg.SetDRBDHelper(new_helper)
2808
      else:
2809
        feedback_fn("Cluster DRBD helper already in desired state,"
2810
                    " not changing")
2811
    if self.op.hvparams:
2812
      self.cluster.hvparams = self.new_hvparams
2813
    if self.op.os_hvp:
2814
      self.cluster.os_hvp = self.new_os_hvp
2815
    if self.op.enabled_hypervisors is not None:
2816
      self.cluster.hvparams = self.new_hvparams
2817
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2818
    if self.op.beparams:
2819
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2820
    if self.op.nicparams:
2821
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2822
    if self.op.osparams:
2823
      self.cluster.osparams = self.new_osp
2824

    
2825
    if self.op.candidate_pool_size is not None:
2826
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2827
      # we need to update the pool size here, otherwise the save will fail
2828
      _AdjustCandidatePool(self, [])
2829

    
2830
    if self.op.maintain_node_health is not None:
2831
      self.cluster.maintain_node_health = self.op.maintain_node_health
2832

    
2833
    if self.op.prealloc_wipe_disks is not None:
2834
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
2835

    
2836
    if self.op.add_uids is not None:
2837
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2838

    
2839
    if self.op.remove_uids is not None:
2840
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2841

    
2842
    if self.op.uid_pool is not None:
2843
      self.cluster.uid_pool = self.op.uid_pool
2844

    
2845
    if self.op.default_iallocator is not None:
2846
      self.cluster.default_iallocator = self.op.default_iallocator
2847

    
2848
    if self.op.reserved_lvs is not None:
2849
      self.cluster.reserved_lvs = self.op.reserved_lvs
2850

    
2851
    def helper_os(aname, mods, desc):
2852
      desc += " OS list"
2853
      lst = getattr(self.cluster, aname)
2854
      for key, val in mods:
2855
        if key == constants.DDM_ADD:
2856
          if val in lst:
2857
            feedback_fn("OS %s already in %s, ignoring", val, desc)
2858
          else:
2859
            lst.append(val)
2860
        elif key == constants.DDM_REMOVE:
2861
          if val in lst:
2862
            lst.remove(val)
2863
          else:
2864
            feedback_fn("OS %s not found in %s, ignoring", val, desc)
2865
        else:
2866
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
2867

    
2868
    if self.op.hidden_os:
2869
      helper_os("hidden_os", self.op.hidden_os, "hidden")
2870

    
2871
    if self.op.blacklisted_os:
2872
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
2873

    
2874
    self.cfg.Update(self.cluster, feedback_fn)
2875

    
2876

    
2877
def _UploadHelper(lu, nodes, fname):
2878
  """Helper for uploading a file and showing warnings.
2879

2880
  """
2881
  if os.path.exists(fname):
2882
    result = lu.rpc.call_upload_file(nodes, fname)
2883
    for to_node, to_result in result.items():
2884
      msg = to_result.fail_msg
2885
      if msg:
2886
        msg = ("Copy of file %s to node %s failed: %s" %
2887
               (fname, to_node, msg))
2888
        lu.proc.LogWarning(msg)
2889

    
2890

    
2891
def _RedistributeAncillaryFiles(lu, additional_nodes=None, additional_vm=True):
2892
  """Distribute additional files which are part of the cluster configuration.
2893

2894
  ConfigWriter takes care of distributing the config and ssconf files, but
2895
  there are more files which should be distributed to all nodes. This function
2896
  makes sure those are copied.
2897

2898
  @param lu: calling logical unit
2899
  @param additional_nodes: list of nodes not in the config to distribute to
2900
  @type additional_vm: boolean
2901
  @param additional_vm: whether the additional nodes are vm-capable or not
2902

2903
  """
2904
  # 1. Gather target nodes
2905
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2906
  dist_nodes = lu.cfg.GetOnlineNodeList()
2907
  nvm_nodes = lu.cfg.GetNonVmCapableNodeList()
2908
  vm_nodes = [name for name in dist_nodes if name not in nvm_nodes]
2909
  if additional_nodes is not None:
2910
    dist_nodes.extend(additional_nodes)
2911
    if additional_vm:
2912
      vm_nodes.extend(additional_nodes)
2913
  if myself.name in dist_nodes:
2914
    dist_nodes.remove(myself.name)
2915
  if myself.name in vm_nodes:
2916
    vm_nodes.remove(myself.name)
2917

    
2918
  # 2. Gather files to distribute
2919
  dist_files = set([constants.ETC_HOSTS,
2920
                    constants.SSH_KNOWN_HOSTS_FILE,
2921
                    constants.RAPI_CERT_FILE,
2922
                    constants.RAPI_USERS_FILE,
2923
                    constants.CONFD_HMAC_KEY,
2924
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2925
                   ])
2926

    
2927
  vm_files = set()
2928
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2929
  for hv_name in enabled_hypervisors:
2930
    hv_class = hypervisor.GetHypervisor(hv_name)
2931
    vm_files.update(hv_class.GetAncillaryFiles())
2932

    
2933
  # 3. Perform the files upload
2934
  for fname in dist_files:
2935
    _UploadHelper(lu, dist_nodes, fname)
2936
  for fname in vm_files:
2937
    _UploadHelper(lu, vm_nodes, fname)
2938

    
2939

    
2940
class LURedistributeConfig(NoHooksLU):
2941
  """Force the redistribution of cluster configuration.
2942

2943
  This is a very simple LU.
2944

2945
  """
2946
  REQ_BGL = False
2947

    
2948
  def ExpandNames(self):
2949
    self.needed_locks = {
2950
      locking.LEVEL_NODE: locking.ALL_SET,
2951
    }
2952
    self.share_locks[locking.LEVEL_NODE] = 1
2953

    
2954
  def Exec(self, feedback_fn):
2955
    """Redistribute the configuration.
2956

2957
    """
2958
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2959
    _RedistributeAncillaryFiles(self)
2960

    
2961

    
2962
def _WaitForSync(lu, instance, disks=None, oneshot=False):
2963
  """Sleep and poll for an instance's disk to sync.
2964

2965
  """
2966
  if not instance.disks or disks is not None and not disks:
2967
    return True
2968

    
2969
  disks = _ExpandCheckDisks(instance, disks)
2970

    
2971
  if not oneshot:
2972
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2973

    
2974
  node = instance.primary_node
2975

    
2976
  for dev in disks:
2977
    lu.cfg.SetDiskID(dev, node)
2978

    
2979
  # TODO: Convert to utils.Retry
2980

    
2981
  retries = 0
2982
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2983
  while True:
2984
    max_time = 0
2985
    done = True
2986
    cumul_degraded = False
2987
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2988
    msg = rstats.fail_msg
2989
    if msg:
2990
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2991
      retries += 1
2992
      if retries >= 10:
2993
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2994
                                 " aborting." % node)
2995
      time.sleep(6)
2996
      continue
2997
    rstats = rstats.payload
2998
    retries = 0
2999
    for i, mstat in enumerate(rstats):
3000
      if mstat is None:
3001
        lu.LogWarning("Can't compute data for node %s/%s",
3002
                           node, disks[i].iv_name)
3003
        continue
3004

    
3005
      cumul_degraded = (cumul_degraded or
3006
                        (mstat.is_degraded and mstat.sync_percent is None))
3007
      if mstat.sync_percent is not None:
3008
        done = False
3009
        if mstat.estimated_time is not None:
3010
          rem_time = ("%s remaining (estimated)" %
3011
                      utils.FormatSeconds(mstat.estimated_time))
3012
          max_time = mstat.estimated_time
3013
        else:
3014
          rem_time = "no time estimate"
3015
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3016
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3017

    
3018
    # if we're done but degraded, let's do a few small retries, to
3019
    # make sure we see a stable and not transient situation; therefore
3020
    # we force restart of the loop
3021
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3022
      logging.info("Degraded disks found, %d retries left", degr_retries)
3023
      degr_retries -= 1
3024
      time.sleep(1)
3025
      continue
3026

    
3027
    if done or oneshot:
3028
      break
3029

    
3030
    time.sleep(min(60, max_time))
3031

    
3032
  if done:
3033
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3034
  return not cumul_degraded
3035

    
3036

    
3037
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3038
  """Check that mirrors are not degraded.
3039

3040
  The ldisk parameter, if True, will change the test from the
3041
  is_degraded attribute (which represents overall non-ok status for
3042
  the device(s)) to the ldisk (representing the local storage status).
3043

3044
  """
3045
  lu.cfg.SetDiskID(dev, node)
3046

    
3047
  result = True
3048

    
3049
  if on_primary or dev.AssembleOnSecondary():
3050
    rstats = lu.rpc.call_blockdev_find(node, dev)
3051
    msg = rstats.fail_msg
3052
    if msg:
3053
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3054
      result = False
3055
    elif not rstats.payload:
3056
      lu.LogWarning("Can't find disk on node %s", node)
3057
      result = False
3058
    else:
3059
      if ldisk:
3060
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3061
      else:
3062
        result = result and not rstats.payload.is_degraded
3063

    
3064
  if dev.children:
3065
    for child in dev.children:
3066
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3067

    
3068
  return result
3069

    
3070

    
3071
class LUDiagnoseOS(NoHooksLU):
3072
  """Logical unit for OS diagnose/query.
3073

3074
  """
3075
  _OP_PARAMS = [
3076
    _POutputFields,
3077
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3078
    ]
3079
  REQ_BGL = False
3080
  _HID = "hidden"
3081
  _BLK = "blacklisted"
3082
  _VLD = "valid"
3083
  _FIELDS_STATIC = utils.FieldSet()
3084
  _FIELDS_DYNAMIC = utils.FieldSet("name", _VLD, "node_status", "variants",
3085
                                   "parameters", "api_versions", _HID, _BLK)
3086

    
3087
  def CheckArguments(self):
3088
    if self.op.names:
3089
      raise errors.OpPrereqError("Selective OS query not supported",
3090
                                 errors.ECODE_INVAL)
3091

    
3092
    _CheckOutputFields(static=self._FIELDS_STATIC,
3093
                       dynamic=self._FIELDS_DYNAMIC,
3094
                       selected=self.op.output_fields)
3095

    
3096
  def ExpandNames(self):
3097
    # Lock all nodes, in shared mode
3098
    # Temporary removal of locks, should be reverted later
3099
    # TODO: reintroduce locks when they are lighter-weight
3100
    self.needed_locks = {}
3101
    #self.share_locks[locking.LEVEL_NODE] = 1
3102
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3103

    
3104
  @staticmethod
3105
  def _DiagnoseByOS(rlist):
3106
    """Remaps a per-node return list into an a per-os per-node dictionary
3107

3108
    @param rlist: a map with node names as keys and OS objects as values
3109

3110
    @rtype: dict
3111
    @return: a dictionary with osnames as keys and as value another
3112
        map, with nodes as keys and tuples of (path, status, diagnose,
3113
        variants, parameters, api_versions) as values, eg::
3114

3115
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3116
                                     (/srv/..., False, "invalid api")],
3117
                           "node2": [(/srv/..., True, "", [], [])]}
3118
          }
3119

3120
    """
3121
    all_os = {}
3122
    # we build here the list of nodes that didn't fail the RPC (at RPC
3123
    # level), so that nodes with a non-responding node daemon don't
3124
    # make all OSes invalid
3125
    good_nodes = [node_name for node_name in rlist
3126
                  if not rlist[node_name].fail_msg]
3127
    for node_name, nr in rlist.items():
3128
      if nr.fail_msg or not nr.payload:
3129
        continue
3130
      for (name, path, status, diagnose, variants,
3131
           params, api_versions) in nr.payload:
3132
        if name not in all_os:
3133
          # build a list of nodes for this os containing empty lists
3134
          # for each node in node_list
3135
          all_os[name] = {}
3136
          for nname in good_nodes:
3137
            all_os[name][nname] = []
3138
        # convert params from [name, help] to (name, help)
3139
        params = [tuple(v) for v in params]
3140
        all_os[name][node_name].append((path, status, diagnose,
3141
                                        variants, params, api_versions))
3142
    return all_os
3143

    
3144
  def Exec(self, feedback_fn):
3145
    """Compute the list of OSes.
3146

3147
    """
3148
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3149
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3150
    pol = self._DiagnoseByOS(node_data)
3151
    output = []
3152
    cluster = self.cfg.GetClusterInfo()
3153

    
3154
    for os_name in utils.NiceSort(pol.keys()):
3155
      os_data = pol[os_name]
3156
      row = []
3157
      valid = True
3158
      (variants, params, api_versions) = null_state = (set(), set(), set())
3159
      for idx, osl in enumerate(os_data.values()):
3160
        valid = bool(valid and osl and osl[0][1])
3161
        if not valid:
3162
          (variants, params, api_versions) = null_state
3163
          break
3164
        node_variants, node_params, node_api = osl[0][3:6]
3165
        if idx == 0: # first entry
3166
          variants = set(node_variants)
3167
          params = set(node_params)
3168
          api_versions = set(node_api)
3169
        else: # keep consistency
3170
          variants.intersection_update(node_variants)
3171
          params.intersection_update(node_params)
3172
          api_versions.intersection_update(node_api)
3173

    
3174
      is_hid = os_name in cluster.hidden_os
3175
      is_blk = os_name in cluster.blacklisted_os
3176
      if ((self._HID not in self.op.output_fields and is_hid) or
3177
          (self._BLK not in self.op.output_fields and is_blk) or
3178
          (self._VLD not in self.op.output_fields and not valid)):
3179
        continue
3180

    
3181
      for field in self.op.output_fields:
3182
        if field == "name":
3183
          val = os_name
3184
        elif field == self._VLD:
3185
          val = valid
3186
        elif field == "node_status":
3187
          # this is just a copy of the dict
3188
          val = {}
3189
          for node_name, nos_list in os_data.items():
3190
            val[node_name] = nos_list
3191
        elif field == "variants":
3192
          val = utils.NiceSort(list(variants))
3193
        elif field == "parameters":
3194
          val = list(params)
3195
        elif field == "api_versions":
3196
          val = list(api_versions)
3197
        elif field == self._HID:
3198
          val = is_hid
3199
        elif field == self._BLK:
3200
          val = is_blk
3201
        else:
3202
          raise errors.ParameterError(field)
3203
        row.append(val)
3204
      output.append(row)
3205

    
3206
    return output
3207

    
3208

    
3209
class LURemoveNode(LogicalUnit):
3210
  """Logical unit for removing a node.
3211

3212
  """
3213
  HPATH = "node-remove"
3214
  HTYPE = constants.HTYPE_NODE
3215
  _OP_PARAMS = [
3216
    _PNodeName,
3217
    ]
3218

    
3219
  def BuildHooksEnv(self):
3220
    """Build hooks env.
3221

3222
    This doesn't run on the target node in the pre phase as a failed
3223
    node would then be impossible to remove.
3224

3225
    """
3226
    env = {
3227
      "OP_TARGET": self.op.node_name,
3228
      "NODE_NAME": self.op.node_name,
3229
      }
3230
    all_nodes = self.cfg.GetNodeList()
3231
    try:
3232
      all_nodes.remove(self.op.node_name)
3233
    except ValueError:
3234
      logging.warning("Node %s which is about to be removed not found"
3235
                      " in the all nodes list", self.op.node_name)
3236
    return env, all_nodes, all_nodes
3237

    
3238
  def CheckPrereq(self):
3239
    """Check prerequisites.
3240

3241
    This checks:
3242
     - the node exists in the configuration
3243
     - it does not have primary or secondary instances
3244
     - it's not the master
3245

3246
    Any errors are signaled by raising errors.OpPrereqError.
3247

3248
    """
3249
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3250
    node = self.cfg.GetNodeInfo(self.op.node_name)
3251
    assert node is not None
3252

    
3253
    instance_list = self.cfg.GetInstanceList()
3254

    
3255
    masternode = self.cfg.GetMasterNode()
3256
    if node.name == masternode:
3257
      raise errors.OpPrereqError("Node is the master node,"
3258
                                 " you need to failover first.",
3259
                                 errors.ECODE_INVAL)
3260

    
3261
    for instance_name in instance_list:
3262
      instance = self.cfg.GetInstanceInfo(instance_name)
3263
      if node.name in instance.all_nodes:
3264
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3265
                                   " please remove first." % instance_name,
3266
                                   errors.ECODE_INVAL)
3267
    self.op.node_name = node.name
3268
    self.node = node
3269

    
3270
  def Exec(self, feedback_fn):
3271
    """Removes the node from the cluster.
3272

3273
    """
3274
    node = self.node
3275
    logging.info("Stopping the node daemon and removing configs from node %s",
3276
                 node.name)
3277

    
3278
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3279

    
3280
    # Promote nodes to master candidate as needed
3281
    _AdjustCandidatePool(self, exceptions=[node.name])
3282
    self.context.RemoveNode(node.name)
3283

    
3284
    # Run post hooks on the node before it's removed
3285
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3286
    try:
3287
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3288
    except:
3289
      # pylint: disable-msg=W0702
3290
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3291

    
3292
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3293
    msg = result.fail_msg
3294
    if msg:
3295
      self.LogWarning("Errors encountered on the remote node while leaving"
3296
                      " the cluster: %s", msg)
3297

    
3298
    # Remove node from our /etc/hosts
3299
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3300
      master_node = self.cfg.GetMasterNode()
3301
      result = self.rpc.call_etc_hosts_modify(master_node,
3302
                                              constants.ETC_HOSTS_REMOVE,
3303
                                              node.name, None)
3304
      result.Raise("Can't update hosts file with new host data")
3305
      _RedistributeAncillaryFiles(self)
3306

    
3307

    
3308
class LUQueryNodes(NoHooksLU):
3309
  """Logical unit for querying nodes.
3310

3311
  """
3312
  # pylint: disable-msg=W0142
3313
  _OP_PARAMS = [
3314
    _POutputFields,
3315
    ("names", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3316
    ("use_locking", False, ht.TBool),
3317
    ]
3318
  REQ_BGL = False
3319

    
3320
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3321
                    "master_candidate", "offline", "drained",
3322
                    "master_capable", "vm_capable"]
3323

    
3324
  _FIELDS_DYNAMIC = utils.FieldSet(
3325
    "dtotal", "dfree",
3326
    "mtotal", "mnode", "mfree",
3327
    "bootid",
3328
    "ctotal", "cnodes", "csockets",
3329
    )
3330

    
3331
  _FIELDS_STATIC = utils.FieldSet(*[
3332
    "pinst_cnt", "sinst_cnt",
3333
    "pinst_list", "sinst_list",
3334
    "pip", "sip", "tags",
3335
    "master",
3336
    "role"] + _SIMPLE_FIELDS
3337
    )
3338

    
3339
  def CheckArguments(self):
3340
    _CheckOutputFields(static=self._FIELDS_STATIC,
3341
                       dynamic=self._FIELDS_DYNAMIC,
3342
                       selected=self.op.output_fields)
3343

    
3344
  def ExpandNames(self):
3345
    self.needed_locks = {}
3346
    self.share_locks[locking.LEVEL_NODE] = 1
3347

    
3348
    if self.op.names:
3349
      self.wanted = _GetWantedNodes(self, self.op.names)
3350
    else:
3351
      self.wanted = locking.ALL_SET
3352

    
3353
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3354
    self.do_locking = self.do_node_query and self.op.use_locking
3355
    if self.do_locking:
3356
      # if we don't request only static fields, we need to lock the nodes
3357
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3358

    
3359
  def Exec(self, feedback_fn):
3360
    """Computes the list of nodes and their attributes.
3361

3362
    """
3363
    all_info = self.cfg.GetAllNodesInfo()
3364
    if self.do_locking:
3365
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3366
    elif self.wanted != locking.ALL_SET:
3367
      nodenames = self.wanted
3368
      missing = set(nodenames).difference(all_info.keys())
3369
      if missing:
3370
        raise errors.OpExecError(
3371
          "Some nodes were removed before retrieving their data: %s" % missing)
3372
    else:
3373
      nodenames = all_info.keys()
3374

    
3375
    nodenames = utils.NiceSort(nodenames)
3376
    nodelist = [all_info[name] for name in nodenames]
3377

    
3378
    # begin data gathering
3379

    
3380
    if self.do_node_query:
3381
      live_data = {}
3382
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3383
                                          self.cfg.GetHypervisorType())
3384
      for name in nodenames:
3385
        nodeinfo = node_data[name]
3386
        if not nodeinfo.fail_msg and nodeinfo.payload:
3387
          nodeinfo = nodeinfo.payload
3388
          fn = utils.TryConvert
3389
          live_data[name] = {
3390
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3391
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3392
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3393
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3394
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3395
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3396
            "bootid": nodeinfo.get('bootid', None),
3397
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3398
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3399
            }
3400
        else:
3401
          live_data[name] = {}
3402
    else:
3403
      live_data = dict.fromkeys(nodenames, {})
3404

    
3405
    node_to_primary = dict([(name, set()) for name in nodenames])
3406
    node_to_secondary = dict([(name, set()) for name in nodenames])
3407

    
3408
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3409
                             "sinst_cnt", "sinst_list"))
3410
    if inst_fields & frozenset(self.op.output_fields):
3411
      inst_data = self.cfg.GetAllInstancesInfo()
3412

    
3413
      for inst in inst_data.values():
3414
        if inst.primary_node in node_to_primary:
3415
          node_to_primary[inst.primary_node].add(inst.name)
3416
        for secnode in inst.secondary_nodes:
3417
          if secnode in node_to_secondary:
3418
            node_to_secondary[secnode].add(inst.name)
3419

    
3420
    master_node = self.cfg.GetMasterNode()
3421

    
3422
    # end data gathering
3423

    
3424
    output = []
3425
    for node in nodelist:
3426
      node_output = []
3427
      for field in self.op.output_fields:
3428
        if field in self._SIMPLE_FIELDS:
3429
          val = getattr(node, field)
3430
        elif field == "pinst_list":
3431
          val = list(node_to_primary[node.name])
3432
        elif field == "sinst_list":
3433
          val = list(node_to_secondary[node.name])
3434
        elif field == "pinst_cnt":
3435
          val = len(node_to_primary[node.name])
3436
        elif field == "sinst_cnt":
3437
          val = len(node_to_secondary[node.name])
3438
        elif field == "pip":
3439
          val = node.primary_ip
3440
        elif field == "sip":
3441
          val = node.secondary_ip
3442
        elif field == "tags":
3443
          val = list(node.GetTags())
3444
        elif field == "master":
3445
          val = node.name == master_node
3446
        elif self._FIELDS_DYNAMIC.Matches(field):
3447
          val = live_data[node.name].get(field, None)
3448
        elif field == "role":
3449
          if node.name == master_node:
3450
            val = "M"
3451
          elif node.master_candidate:
3452
            val = "C"
3453
          elif node.drained:
3454
            val = "D"
3455
          elif node.offline:
3456
            val = "O"
3457
          else:
3458
            val = "R"
3459
        else:
3460
          raise errors.ParameterError(field)
3461
        node_output.append(val)
3462
      output.append(node_output)
3463

    
3464
    return output
3465

    
3466

    
3467
class LUQueryNodeVolumes(NoHooksLU):
3468
  """Logical unit for getting volumes on node(s).
3469

3470
  """
3471
  _OP_PARAMS = [
3472
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3473
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3474
    ]
3475
  REQ_BGL = False
3476
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3477
  _FIELDS_STATIC = utils.FieldSet("node")
3478

    
3479
  def CheckArguments(self):
3480
    _CheckOutputFields(static=self._FIELDS_STATIC,
3481
                       dynamic=self._FIELDS_DYNAMIC,
3482
                       selected=self.op.output_fields)
3483

    
3484
  def ExpandNames(self):
3485
    self.needed_locks = {}
3486
    self.share_locks[locking.LEVEL_NODE] = 1
3487
    if not self.op.nodes:
3488
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3489
    else:
3490
      self.needed_locks[locking.LEVEL_NODE] = \
3491
        _GetWantedNodes(self, self.op.nodes)
3492

    
3493
  def Exec(self, feedback_fn):
3494
    """Computes the list of nodes and their attributes.
3495

3496
    """
3497
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3498
    volumes = self.rpc.call_node_volumes(nodenames)
3499

    
3500
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3501
             in self.cfg.GetInstanceList()]
3502

    
3503
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3504

    
3505
    output = []
3506
    for node in nodenames:
3507
      nresult = volumes[node]
3508
      if nresult.offline:
3509
        continue
3510
      msg = nresult.fail_msg
3511
      if msg:
3512
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3513
        continue
3514

    
3515
      node_vols = nresult.payload[:]
3516
      node_vols.sort(key=lambda vol: vol['dev'])
3517

    
3518
      for vol in node_vols:
3519
        node_output = []
3520
        for field in self.op.output_fields:
3521
          if field == "node":
3522
            val = node
3523
          elif field == "phys":
3524
            val = vol['dev']
3525
          elif field == "vg":
3526
            val = vol['vg']
3527
          elif field == "name":
3528
            val = vol['name']
3529
          elif field == "size":
3530
            val = int(float(vol['size']))
3531
          elif field == "instance":
3532
            for inst in ilist:
3533
              if node not in lv_by_node[inst]:
3534
                continue
3535
              if vol['name'] in lv_by_node[inst][node]:
3536
                val = inst.name
3537
                break
3538
            else:
3539
              val = '-'
3540
          else:
3541
            raise errors.ParameterError(field)
3542
          node_output.append(str(val))
3543

    
3544
        output.append(node_output)
3545

    
3546
    return output
3547

    
3548

    
3549
class LUQueryNodeStorage(NoHooksLU):
3550
  """Logical unit for getting information on storage units on node(s).
3551

3552
  """
3553
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3554
  _OP_PARAMS = [
3555
    ("nodes", ht.EmptyList, ht.TListOf(ht.TNonEmptyString)),
3556
    ("storage_type", ht.NoDefault, _CheckStorageType),
3557
    ("output_fields", ht.NoDefault, ht.TListOf(ht.TNonEmptyString)),
3558
    ("name", None, ht.TMaybeString),
3559
    ]
3560
  REQ_BGL = False
3561

    
3562
  def CheckArguments(self):
3563
    _CheckOutputFields(static=self._FIELDS_STATIC,
3564
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3565
                       selected=self.op.output_fields)
3566

    
3567
  def ExpandNames(self):
3568
    self.needed_locks = {}
3569
    self.share_locks[locking.LEVEL_NODE] = 1
3570

    
3571
    if self.op.nodes:
3572
      self.needed_locks[locking.LEVEL_NODE] = \
3573
        _GetWantedNodes(self, self.op.nodes)
3574
    else:
3575
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3576

    
3577
  def Exec(self, feedback_fn):
3578
    """Computes the list of nodes and their attributes.
3579

3580
    """
3581
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3582

    
3583
    # Always get name to sort by
3584
    if constants.SF_NAME in self.op.output_fields:
3585
      fields = self.op.output_fields[:]
3586
    else:
3587
      fields = [constants.SF_NAME] + self.op.output_fields
3588

    
3589
    # Never ask for node or type as it's only known to the LU
3590
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3591
      while extra in fields:
3592
        fields.remove(extra)
3593

    
3594
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3595
    name_idx = field_idx[constants.SF_NAME]
3596

    
3597
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3598
    data = self.rpc.call_storage_list(self.nodes,
3599
                                      self.op.storage_type, st_args,
3600
                                      self.op.name, fields)
3601

    
3602
    result = []
3603

    
3604
    for node in utils.NiceSort(self.nodes):
3605
      nresult = data[node]
3606
      if nresult.offline:
3607
        continue
3608

    
3609
      msg = nresult.fail_msg
3610
      if msg:
3611
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3612
        continue
3613

    
3614
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3615

    
3616
      for name in utils.NiceSort(rows.keys()):
3617
        row = rows[name]
3618

    
3619
        out = []
3620

    
3621
        for field in self.op.output_fields:
3622
          if field == constants.SF_NODE:
3623
            val = node
3624
          elif field == constants.SF_TYPE:
3625
            val = self.op.storage_type
3626
          elif field in field_idx:
3627
            val = row[field_idx[field]]
3628
          else:
3629
            raise errors.ParameterError(field)
3630

    
3631
          out.append(val)
3632

    
3633
        result.append(out)
3634

    
3635
    return result
3636

    
3637

    
3638
class LUModifyNodeStorage(NoHooksLU):
3639
  """Logical unit for modifying a storage volume on a node.
3640

3641
  """
3642
  _OP_PARAMS = [
3643
    _PNodeName,
3644
    ("storage_type", ht.NoDefault, _CheckStorageType),
3645
    ("name", ht.NoDefault, ht.TNonEmptyString),
3646
    ("changes", ht.NoDefault, ht.TDict),
3647
    ]
3648
  REQ_BGL = False
3649

    
3650
  def CheckArguments(self):
3651
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3652

    
3653
    storage_type = self.op.storage_type
3654

    
3655
    try:
3656
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3657
    except KeyError:
3658
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3659
                                 " modified" % storage_type,
3660
                                 errors.ECODE_INVAL)
3661

    
3662
    diff = set(self.op.changes.keys()) - modifiable
3663
    if diff:
3664
      raise errors.OpPrereqError("The following fields can not be modified for"
3665
                                 " storage units of type '%s': %r" %
3666
                                 (storage_type, list(diff)),
3667
                                 errors.ECODE_INVAL)
3668

    
3669
  def ExpandNames(self):
3670
    self.needed_locks = {
3671
      locking.LEVEL_NODE: self.op.node_name,
3672
      }
3673

    
3674
  def Exec(self, feedback_fn):
3675
    """Computes the list of nodes and their attributes.
3676

3677
    """
3678
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3679
    result = self.rpc.call_storage_modify(self.op.node_name,
3680
                                          self.op.storage_type, st_args,
3681
                                          self.op.name, self.op.changes)
3682
    result.Raise("Failed to modify storage unit '%s' on %s" %
3683
                 (self.op.name, self.op.node_name))
3684

    
3685

    
3686
class LUAddNode(LogicalUnit):
3687
  """Logical unit for adding node to the cluster.
3688

3689
  """
3690
  HPATH = "node-add"
3691
  HTYPE = constants.HTYPE_NODE
3692
  _OP_PARAMS = [
3693
    _PNodeName,
3694
    ("primary_ip", None, ht.NoType),
3695
    ("secondary_ip", None, ht.TMaybeString),
3696
    ("readd", False, ht.TBool),
3697
    ("group", None, ht.TMaybeString),
3698
    ("master_capable", None, ht.TMaybeBool),
3699
    ("vm_capable", None, ht.TMaybeBool),
3700
    ]
3701
  _NFLAGS = ["master_capable", "vm_capable"]
3702

    
3703
  def CheckArguments(self):
3704
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
3705
    # validate/normalize the node name
3706
    self.hostname = netutils.GetHostname(name=self.op.node_name,
3707
                                         family=self.primary_ip_family)
3708
    self.op.node_name = self.hostname.name
3709
    if self.op.readd and self.op.group:
3710
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
3711
                                 " being readded", errors.ECODE_INVAL)
3712

    
3713
  def BuildHooksEnv(self):
3714
    """Build hooks env.
3715

3716
    This will run on all nodes before, and on all nodes + the new node after.
3717

3718
    """
3719
    env = {
3720
      "OP_TARGET": self.op.node_name,
3721
      "NODE_NAME": self.op.node_name,
3722
      "NODE_PIP": self.op.primary_ip,
3723
      "NODE_SIP": self.op.secondary_ip,
3724
      "MASTER_CAPABLE": str(self.op.master_capable),
3725
      "VM_CAPABLE": str(self.op.vm_capable),
3726
      }
3727
    nodes_0 = self.cfg.GetNodeList()
3728
    nodes_1 = nodes_0 + [self.op.node_name, ]
3729
    return env, nodes_0, nodes_1
3730

    
3731
  def CheckPrereq(self):
3732
    """Check prerequisites.
3733

3734
    This checks:
3735
     - the new node is not already in the config
3736
     - it is resolvable
3737
     - its parameters (single/dual homed) matches the cluster
3738

3739
    Any errors are signaled by raising errors.OpPrereqError.
3740

3741
    """
3742
    cfg = self.cfg
3743
    hostname = self.hostname
3744
    node = hostname.name
3745
    primary_ip = self.op.primary_ip = hostname.ip
3746
    if self.op.secondary_ip is None:
3747
      if self.primary_ip_family == netutils.IP6Address.family:
3748
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
3749
                                   " IPv4 address must be given as secondary",
3750
                                   errors.ECODE_INVAL)
3751
      self.op.secondary_ip = primary_ip
3752

    
3753
    secondary_ip = self.op.secondary_ip
3754
    if not netutils.IP4Address.IsValid(secondary_ip):
3755
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
3756
                                 " address" % secondary_ip, errors.ECODE_INVAL)
3757

    
3758
    node_list = cfg.GetNodeList()
3759
    if not self.op.readd and node in node_list:
3760
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3761
                                 node, errors.ECODE_EXISTS)
3762
    elif self.op.readd and node not in node_list:
3763
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3764
                                 errors.ECODE_NOENT)
3765

    
3766
    self.changed_primary_ip = False
3767

    
3768
    for existing_node_name in node_list:
3769
      existing_node = cfg.GetNodeInfo(existing_node_name)
3770

    
3771
      if self.op.readd and node == existing_node_name:
3772
        if existing_node.secondary_ip != secondary_ip:
3773
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3774
                                     " address configuration as before",
3775
                                     errors.ECODE_INVAL)
3776
        if existing_node.primary_ip != primary_ip:
3777
          self.changed_primary_ip = True
3778

    
3779
        continue
3780

    
3781
      if (existing_node.primary_ip == primary_ip or
3782
          existing_node.secondary_ip == primary_ip or
3783
          existing_node.primary_ip == secondary_ip or
3784
          existing_node.secondary_ip == secondary_ip):
3785
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3786
                                   " existing node %s" % existing_node.name,
3787
                                   errors.ECODE_NOTUNIQUE)
3788

    
3789
    # After this 'if' block, None is no longer a valid value for the
3790
    # _capable op attributes
3791
    if self.op.readd:
3792
      old_node = self.cfg.GetNodeInfo(node)
3793
      assert old_node is not None, "Can't retrieve locked node %s" % node
3794
      for attr in self._NFLAGS:
3795
        if getattr(self.op, attr) is None:
3796
          setattr(self.op, attr, getattr(old_node, attr))
3797
    else:
3798
      for attr in self._NFLAGS:
3799
        if getattr(self.op, attr) is None:
3800
          setattr(self.op, attr, True)
3801

    
3802
    if self.op.readd and not self.op.vm_capable:
3803
      pri, sec = cfg.GetNodeInstances(node)
3804
      if pri or sec:
3805
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
3806
                                   " flag set to false, but it already holds"
3807
                                   " instances" % node,
3808
                                   errors.ECODE_STATE)
3809

    
3810
    # check that the type of the node (single versus dual homed) is the
3811
    # same as for the master
3812
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3813
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3814
    newbie_singlehomed = secondary_ip == primary_ip
3815
    if master_singlehomed != newbie_singlehomed:
3816
      if master_singlehomed:
3817
        raise errors.OpPrereqError("The master has no private ip but the"
3818
                                   " new node has one",
3819
                                   errors.ECODE_INVAL)
3820
      else:
3821
        raise errors.OpPrereqError("The master has a private ip but the"
3822
                                   " new node doesn't have one",
3823
                                   errors.ECODE_INVAL)
3824

    
3825
    # checks reachability
3826
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3827
      raise errors.OpPrereqError("Node not reachable by ping",
3828
                                 errors.ECODE_ENVIRON)
3829

    
3830
    if not newbie_singlehomed:
3831
      # check reachability from my secondary ip to newbie's secondary ip
3832
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3833
                           source=myself.secondary_ip):
3834
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3835
                                   " based ping to noded port",
3836
                                   errors.ECODE_ENVIRON)
3837

    
3838
    if self.op.readd:
3839
      exceptions = [node]
3840
    else:
3841
      exceptions = []
3842

    
3843
    if self.op.master_capable:
3844
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3845
    else:
3846
      self.master_candidate = False
3847

    
3848
    if self.op.readd:
3849
      self.new_node = old_node
3850
    else:
3851
      node_group = cfg.LookupNodeGroup(self.op.group)
3852
      self.new_node = objects.Node(name=node,
3853
                                   primary_ip=primary_ip,
3854
                                   secondary_ip=secondary_ip,
3855
                                   master_candidate=self.master_candidate,
3856
                                   offline=False, drained=False,
3857
                                   group=node_group)
3858

    
3859
  def Exec(self, feedback_fn):
3860
    """Adds the new node to the cluster.
3861

3862
    """
3863
    new_node = self.new_node
3864
    node = new_node.name
3865

    
3866
    # for re-adds, reset the offline/drained/master-candidate flags;
3867
    # we need to reset here, otherwise offline would prevent RPC calls
3868
    # later in the procedure; this also means that if the re-add
3869
    # fails, we are left with a non-offlined, broken node
3870
    if self.op.readd:
3871
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3872
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3873
      # if we demote the node, we do cleanup later in the procedure
3874
      new_node.master_candidate = self.master_candidate
3875
      if self.changed_primary_ip:
3876
        new_node.primary_ip = self.op.primary_ip
3877

    
3878
    # copy the master/vm_capable flags
3879
    for attr in self._NFLAGS:
3880
      setattr(new_node, attr, getattr(self.op, attr))
3881

    
3882
    # notify the user about any possible mc promotion
3883
    if new_node.master_candidate:
3884
      self.LogInfo("Node will be a master candidate")
3885

    
3886
    # check connectivity
3887
    result = self.rpc.call_version([node])[node]
3888
    result.Raise("Can't get version information from node %s" % node)
3889
    if constants.PROTOCOL_VERSION == result.payload:
3890
      logging.info("Communication to node %s fine, sw version %s match",
3891
                   node, result.payload)
3892
    else:
3893
      raise errors.OpExecError("Version mismatch master version %s,"
3894
                               " node version %s" %
3895
                               (constants.PROTOCOL_VERSION, result.payload))
3896

    
3897
    # Add node to our /etc/hosts, and add key to known_hosts
3898
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3899
      master_node = self.cfg.GetMasterNode()
3900
      result = self.rpc.call_etc_hosts_modify(master_node,
3901
                                              constants.ETC_HOSTS_ADD,
3902
                                              self.hostname.name,
3903
                                              self.hostname.ip)
3904
      result.Raise("Can't update hosts file with new host data")
3905

    
3906
    if new_node.secondary_ip != new_node.primary_ip:
3907
      result = self.rpc.call_node_has_ip_address(new_node.name,
3908
                                                 new_node.secondary_ip)
3909
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3910
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3911
      if not result.payload:
3912
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3913
                                 " you gave (%s). Please fix and re-run this"
3914
                                 " command." % new_node.secondary_ip)
3915

    
3916
    node_verify_list = [self.cfg.GetMasterNode()]
3917
    node_verify_param = {
3918
      constants.NV_NODELIST: [node],
3919
      # TODO: do a node-net-test as well?
3920
    }
3921

    
3922
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3923
                                       self.cfg.GetClusterName())
3924
    for verifier in node_verify_list:
3925
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3926
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3927
      if nl_payload:
3928
        for failed in nl_payload:
3929
          feedback_fn("ssh/hostname verification failed"
3930
                      " (checking from %s): %s" %
3931
                      (verifier, nl_payload[failed]))
3932
        raise errors.OpExecError("ssh/hostname verification failed.")
3933

    
3934
    if self.op.readd:
3935
      _RedistributeAncillaryFiles(self)
3936
      self.context.ReaddNode(new_node)
3937
      # make sure we redistribute the config
3938
      self.cfg.Update(new_node, feedback_fn)
3939
      # and make sure the new node will not have old files around
3940
      if not new_node.master_candidate:
3941
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3942
        msg = result.fail_msg
3943
        if msg:
3944
          self.LogWarning("Node failed to demote itself from master"
3945
                          " candidate status: %s" % msg)
3946
    else:
3947
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
3948
                                  additional_vm=self.op.vm_capable)
3949
      self.context.AddNode(new_node, self.proc.GetECId())
3950

    
3951

    
3952
class LUSetNodeParams(LogicalUnit):
3953
  """Modifies the parameters of a node.
3954

3955
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
3956
      to the node role (as _ROLE_*)
3957
  @cvar _R2F: a dictionary from node role to tuples of flags
3958
  @cvar _FLAGS: a list of attribute names corresponding to the flags
3959

3960
  """
3961
  HPATH = "node-modify"
3962
  HTYPE = constants.HTYPE_NODE
3963
  _OP_PARAMS = [
3964
    _PNodeName,
3965
    ("master_candidate", None, ht.TMaybeBool),
3966
    ("offline", None, ht.TMaybeBool),
3967
    ("drained", None, ht.TMaybeBool),
3968
    ("auto_promote", False, ht.TBool),
3969
    ("master_capable", None, ht.TMaybeBool),
3970
    ("vm_capable", None, ht.TMaybeBool),
3971
    _PForce,
3972
    ]
3973
  REQ_BGL = False
3974
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
3975
  _F2R = {
3976
    (True, False, False): _ROLE_CANDIDATE,
3977
    (False, True, False): _ROLE_DRAINED,
3978
    (False, False, True): _ROLE_OFFLINE,
3979
    (False, False, False): _ROLE_REGULAR,
3980
    }
3981
  _R2F = dict((v, k) for k, v in _F2R.items())
3982
  _FLAGS = ["master_candidate", "drained", "offline"]
3983

    
3984
  def CheckArguments(self):
3985
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3986
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
3987
                self.op.master_capable, self.op.vm_capable]
3988
    if all_mods.count(None) == len(all_mods):
3989
      raise errors.OpPrereqError("Please pass at least one modification",
3990
                                 errors.ECODE_INVAL)
3991
    if all_mods.count(True) > 1:
3992
      raise errors.OpPrereqError("Can't set the node into more than one"
3993
                                 " state at the same time",
3994
                                 errors.ECODE_INVAL)
3995

    
3996
    # Boolean value that tells us whether we might be demoting from MC
3997
    self.might_demote = (self.op.master_candidate == False or
3998
                         self.op.offline == True or
3999
                         self.op.drained == True or
4000
                         self.op.master_capable == False)
4001

    
4002
    self.lock_all = self.op.auto_promote and self.might_demote
4003

    
4004
  def ExpandNames(self):
4005
    if self.lock_all:
4006
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4007
    else:
4008
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4009

    
4010
  def BuildHooksEnv(self):
4011
    """Build hooks env.
4012

4013
    This runs on the master node.
4014

4015
    """
4016
    env = {
4017
      "OP_TARGET": self.op.node_name,
4018
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4019
      "OFFLINE": str(self.op.offline),
4020
      "DRAINED": str(self.op.drained),
4021
      "MASTER_CAPABLE": str(self.op.master_capable),
4022
      "VM_CAPABLE": str(self.op.vm_capable),
4023
      }
4024
    nl = [self.cfg.GetMasterNode(),
4025
          self.op.node_name]
4026
    return env, nl, nl
4027

    
4028
  def CheckPrereq(self):
4029
    """Check prerequisites.
4030

4031
    This only checks the instance list against the existing names.
4032

4033
    """
4034
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4035

    
4036
    if (self.op.master_candidate is not None or
4037
        self.op.drained is not None or
4038
        self.op.offline is not None):
4039
      # we can't change the master's node flags
4040
      if self.op.node_name == self.cfg.GetMasterNode():
4041
        raise errors.OpPrereqError("The master role can be changed"
4042
                                   " only via master-failover",
4043
                                   errors.ECODE_INVAL)
4044

    
4045
    if self.op.master_candidate and not node.master_capable:
4046
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4047
                                 " it a master can