Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 9dd6889b

History | View | Annotate | Download (358.9 kB)

1
#
2
#
3

    
4
# Copyright (C) 2006, 2007, 2008 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

    
40
from ganeti import ssh
41
from ganeti import utils
42
from ganeti import errors
43
from ganeti import hypervisor
44
from ganeti import locking
45
from ganeti import constants
46
from ganeti import objects
47
from ganeti import serializer
48
from ganeti import ssconf
49
from ganeti import uidpool
50
from ganeti import compat
51
from ganeti import masterd
52
from ganeti import netutils
53

    
54
import ganeti.masterd.instance # pylint: disable-msg=W0611
55

    
56

    
57
# Modifiable default values; need to define these here before the
58
# actual LUs
59

    
60
def _EmptyList():
61
  """Returns an empty list.
62

63
  """
64
  return []
65

    
66

    
67
def _EmptyDict():
68
  """Returns an empty dict.
69

70
  """
71
  return {}
72

    
73

    
74
#: The without-default default value
75
_NoDefault = object()
76

    
77

    
78
#: The no-type (value to complex to check it in the type system)
79
_NoType = object()
80

    
81

    
82
# Some basic types
83
def _TNotNone(val):
84
  """Checks if the given value is not None.
85

86
  """
87
  return val is not None
88

    
89

    
90
def _TNone(val):
91
  """Checks if the given value is None.
92

93
  """
94
  return val is None
95

    
96

    
97
def _TBool(val):
98
  """Checks if the given value is a boolean.
99

100
  """
101
  return isinstance(val, bool)
102

    
103

    
104
def _TInt(val):
105
  """Checks if the given value is an integer.
106

107
  """
108
  return isinstance(val, int)
109

    
110

    
111
def _TFloat(val):
112
  """Checks if the given value is a float.
113

114
  """
115
  return isinstance(val, float)
116

    
117

    
118
def _TString(val):
119
  """Checks if the given value is a string.
120

121
  """
122
  return isinstance(val, basestring)
123

    
124

    
125
def _TTrue(val):
126
  """Checks if a given value evaluates to a boolean True value.
127

128
  """
129
  return bool(val)
130

    
131

    
132
def _TElemOf(target_list):
133
  """Builds a function that checks if a given value is a member of a list.
134

135
  """
136
  return lambda val: val in target_list
137

    
138

    
139
# Container types
140
def _TList(val):
141
  """Checks if the given value is a list.
142

143
  """
144
  return isinstance(val, list)
145

    
146

    
147
def _TDict(val):
148
  """Checks if the given value is a dictionary.
149

150
  """
151
  return isinstance(val, dict)
152

    
153

    
154
# Combinator types
155
def _TAnd(*args):
156
  """Combine multiple functions using an AND operation.
157

158
  """
159
  def fn(val):
160
    return compat.all(t(val) for t in args)
161
  return fn
162

    
163

    
164
def _TOr(*args):
165
  """Combine multiple functions using an AND operation.
166

167
  """
168
  def fn(val):
169
    return compat.any(t(val) for t in args)
170
  return fn
171

    
172

    
173
# Type aliases
174

    
175
#: a non-empty string
176
_TNonEmptyString = _TAnd(_TString, _TTrue)
177

    
178

    
179
#: a maybe non-empty string
180
_TMaybeString = _TOr(_TNonEmptyString, _TNone)
181

    
182

    
183
#: a maybe boolean (bool or none)
184
_TMaybeBool = _TOr(_TBool, _TNone)
185

    
186

    
187
#: a positive integer
188
_TPositiveInt = _TAnd(_TInt, lambda v: v >= 0)
189

    
190
#: a strictly positive integer
191
_TStrictPositiveInt = _TAnd(_TInt, lambda v: v > 0)
192

    
193

    
194
def _TListOf(my_type):
195
  """Checks if a given value is a list with all elements of the same type.
196

197
  """
198
  return _TAnd(_TList,
199
               lambda lst: compat.all(my_type(v) for v in lst))
200

    
201

    
202
def _TDictOf(key_type, val_type):
203
  """Checks a dict type for the type of its key/values.
204

205
  """
206
  return _TAnd(_TDict,
207
               lambda my_dict: (compat.all(key_type(v) for v in my_dict.keys())
208
                                and compat.all(val_type(v)
209
                                               for v in my_dict.values())))
210

    
211

    
212
# Common opcode attributes
213

    
214
#: output fields for a query operation
215
_POutputFields = ("output_fields", _NoDefault, _TListOf(_TNonEmptyString))
216

    
217

    
218
#: the shutdown timeout
219
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
220
                     _TPositiveInt)
221

    
222
#: the force parameter
223
_PForce = ("force", False, _TBool)
224

    
225
#: a required instance name (for single-instance LUs)
226
_PInstanceName = ("instance_name", _NoDefault, _TNonEmptyString)
227

    
228

    
229
#: a required node name (for single-node LUs)
230
_PNodeName = ("node_name", _NoDefault, _TNonEmptyString)
231

    
232

    
233
# End types
234
class LogicalUnit(object):
235
  """Logical Unit base class.
236

237
  Subclasses must follow these rules:
238
    - implement ExpandNames
239
    - implement CheckPrereq (except when tasklets are used)
240
    - implement Exec (except when tasklets are used)
241
    - implement BuildHooksEnv
242
    - redefine HPATH and HTYPE
243
    - optionally redefine their run requirements:
244
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
245

246
  Note that all commands require root permissions.
247

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

253
  """
254
  HPATH = None
255
  HTYPE = None
256
  _OP_PARAMS = []
257
  REQ_BGL = True
258

    
259
  def __init__(self, processor, op, context, rpc):
260
    """Constructor for LogicalUnit.
261

262
    This needs to be overridden in derived classes in order to check op
263
    validity.
264

265
    """
266
    self.proc = processor
267
    self.op = op
268
    self.cfg = context.cfg
269
    self.context = context
270
    self.rpc = rpc
271
    # Dicts used to declare locking needs to mcpu
272
    self.needed_locks = None
273
    self.acquired_locks = {}
274
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
275
    self.add_locks = {}
276
    self.remove_locks = {}
277
    # Used to force good behavior when calling helper functions
278
    self.recalculate_locks = {}
279
    self.__ssh = None
280
    # logging
281
    self.Log = processor.Log # pylint: disable-msg=C0103
282
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
283
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
284
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
285
    # support for dry-run
286
    self.dry_run_result = None
287
    # support for generic debug attribute
288
    if (not hasattr(self.op, "debug_level") or
289
        not isinstance(self.op.debug_level, int)):
290
      self.op.debug_level = 0
291

    
292
    # Tasklets
293
    self.tasklets = None
294

    
295
    # The new kind-of-type-system
296
    op_id = self.op.OP_ID
297
    for attr_name, aval, test in self._OP_PARAMS:
298
      if not hasattr(op, attr_name):
299
        if aval == _NoDefault:
300
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
301
                                     (op_id, attr_name), errors.ECODE_INVAL)
302
        else:
303
          if callable(aval):
304
            dval = aval()
305
          else:
306
            dval = aval
307
          setattr(self.op, attr_name, dval)
308
      attr_val = getattr(op, attr_name)
309
      if test == _NoType:
310
        # no tests here
311
        continue
312
      if not callable(test):
313
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
314
                                     " given type is not a proper type (%s)" %
315
                                     (op_id, attr_name, test))
316
      if not test(attr_val):
317
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
318
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
319
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
320
                                   (op_id, attr_name), errors.ECODE_INVAL)
321

    
322
    self.CheckArguments()
323

    
324
  def __GetSSH(self):
325
    """Returns the SshRunner object
326

327
    """
328
    if not self.__ssh:
329
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
330
    return self.__ssh
331

    
332
  ssh = property(fget=__GetSSH)
333

    
334
  def CheckArguments(self):
335
    """Check syntactic validity for the opcode arguments.
336

337
    This method is for doing a simple syntactic check and ensure
338
    validity of opcode parameters, without any cluster-related
339
    checks. While the same can be accomplished in ExpandNames and/or
340
    CheckPrereq, doing these separate is better because:
341

342
      - ExpandNames is left as as purely a lock-related function
343
      - CheckPrereq is run after we have acquired locks (and possible
344
        waited for them)
345

346
    The function is allowed to change the self.op attribute so that
347
    later methods can no longer worry about missing parameters.
348

349
    """
350
    pass
351

    
352
  def ExpandNames(self):
353
    """Expand names for this LU.
354

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

360
    LUs which implement this method must also populate the self.needed_locks
361
    member, as a dict with lock levels as keys, and a list of needed lock names
362
    as values. Rules:
363

364
      - use an empty dict if you don't need any lock
365
      - if you don't need any lock at a particular level omit that level
366
      - don't put anything for the BGL level
367
      - if you want all locks at a level use locking.ALL_SET as a value
368

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

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

377
    Examples::
378

379
      # Acquire all nodes and one instance
380
      self.needed_locks = {
381
        locking.LEVEL_NODE: locking.ALL_SET,
382
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
383
      }
384
      # Acquire just two nodes
385
      self.needed_locks = {
386
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
387
      }
388
      # Acquire no locks
389
      self.needed_locks = {} # No, you can't leave it to the default value None
390

391
    """
392
    # The implementation of this method is mandatory only if the new LU is
393
    # concurrent, so that old LUs don't need to be changed all at the same
394
    # time.
395
    if self.REQ_BGL:
396
      self.needed_locks = {} # Exclusive LUs don't need locks.
397
    else:
398
      raise NotImplementedError
399

    
400
  def DeclareLocks(self, level):
401
    """Declare LU locking needs for a level
402

403
    While most LUs can just declare their locking needs at ExpandNames time,
404
    sometimes there's the need to calculate some locks after having acquired
405
    the ones before. This function is called just before acquiring locks at a
406
    particular level, but after acquiring the ones at lower levels, and permits
407
    such calculations. It can be used to modify self.needed_locks, and by
408
    default it does nothing.
409

410
    This function is only called if you have something already set in
411
    self.needed_locks for the level.
412

413
    @param level: Locking level which is going to be locked
414
    @type level: member of ganeti.locking.LEVELS
415

416
    """
417

    
418
  def CheckPrereq(self):
419
    """Check prerequisites for this LU.
420

421
    This method should check that the prerequisites for the execution
422
    of this LU are fulfilled. It can do internode communication, but
423
    it should be idempotent - no cluster or system changes are
424
    allowed.
425

426
    The method should raise errors.OpPrereqError in case something is
427
    not fulfilled. Its return value is ignored.
428

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

432
    """
433
    if self.tasklets is not None:
434
      for (idx, tl) in enumerate(self.tasklets):
435
        logging.debug("Checking prerequisites for tasklet %s/%s",
436
                      idx + 1, len(self.tasklets))
437
        tl.CheckPrereq()
438
    else:
439
      pass
440

    
441
  def Exec(self, feedback_fn):
442
    """Execute the LU.
443

444
    This method should implement the actual work. It should raise
445
    errors.OpExecError for failures that are somewhat dealt with in
446
    code, or expected.
447

448
    """
449
    if self.tasklets is not None:
450
      for (idx, tl) in enumerate(self.tasklets):
451
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
452
        tl.Exec(feedback_fn)
453
    else:
454
      raise NotImplementedError
455

    
456
  def BuildHooksEnv(self):
457
    """Build hooks environment for this LU.
458

459
    This method should return a three-node tuple consisting of: a dict
460
    containing the environment that will be used for running the
461
    specific hook for this LU, a list of node names on which the hook
462
    should run before the execution, and a list of node names on which
463
    the hook should run after the execution.
464

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

470
    No nodes should be returned as an empty list (and not None).
471

472
    Note that if the HPATH for a LU class is None, this function will
473
    not be called.
474

475
    """
476
    raise NotImplementedError
477

    
478
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
479
    """Notify the LU about the results of its hooks.
480

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

487
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
488
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
489
    @param hook_results: the results of the multi-node hooks rpc call
490
    @param feedback_fn: function used send feedback back to the caller
491
    @param lu_result: the previous Exec result this LU had, or None
492
        in the PRE phase
493
    @return: the new Exec result, based on the previous result
494
        and hook results
495

496
    """
497
    # API must be kept, thus we ignore the unused argument and could
498
    # be a function warnings
499
    # pylint: disable-msg=W0613,R0201
500
    return lu_result
501

    
502
  def _ExpandAndLockInstance(self):
503
    """Helper function to expand and lock an instance.
504

505
    Many LUs that work on an instance take its name in self.op.instance_name
506
    and need to expand it and then declare the expanded name for locking. This
507
    function does it, and then updates self.op.instance_name to the expanded
508
    name. It also initializes needed_locks as a dict, if this hasn't been done
509
    before.
510

511
    """
512
    if self.needed_locks is None:
513
      self.needed_locks = {}
514
    else:
515
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
516
        "_ExpandAndLockInstance called with instance-level locks set"
517
    self.op.instance_name = _ExpandInstanceName(self.cfg,
518
                                                self.op.instance_name)
519
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
520

    
521
  def _LockInstancesNodes(self, primary_only=False):
522
    """Helper function to declare instances' nodes for locking.
523

524
    This function should be called after locking one or more instances to lock
525
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
526
    with all primary or secondary nodes for instances already locked and
527
    present in self.needed_locks[locking.LEVEL_INSTANCE].
528

529
    It should be called from DeclareLocks, and for safety only works if
530
    self.recalculate_locks[locking.LEVEL_NODE] is set.
531

532
    In the future it may grow parameters to just lock some instance's nodes, or
533
    to just lock primaries or secondary nodes, if needed.
534

535
    If should be called in DeclareLocks in a way similar to::
536

537
      if level == locking.LEVEL_NODE:
538
        self._LockInstancesNodes()
539

540
    @type primary_only: boolean
541
    @param primary_only: only lock primary nodes of locked instances
542

543
    """
544
    assert locking.LEVEL_NODE in self.recalculate_locks, \
545
      "_LockInstancesNodes helper function called with no nodes to recalculate"
546

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

    
549
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
550
    # future we might want to have different behaviors depending on the value
551
    # of self.recalculate_locks[locking.LEVEL_NODE]
552
    wanted_nodes = []
553
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
554
      instance = self.context.cfg.GetInstanceInfo(instance_name)
555
      wanted_nodes.append(instance.primary_node)
556
      if not primary_only:
557
        wanted_nodes.extend(instance.secondary_nodes)
558

    
559
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
560
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
561
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
562
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
563

    
564
    del self.recalculate_locks[locking.LEVEL_NODE]
565

    
566

    
567
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
568
  """Simple LU which runs no hooks.
569

570
  This LU is intended as a parent for other LogicalUnits which will
571
  run no hooks, in order to reduce duplicate code.
572

573
  """
574
  HPATH = None
575
  HTYPE = None
576

    
577
  def BuildHooksEnv(self):
578
    """Empty BuildHooksEnv for NoHooksLu.
579

580
    This just raises an error.
581

582
    """
583
    assert False, "BuildHooksEnv called for NoHooksLUs"
584

    
585

    
586
class Tasklet:
587
  """Tasklet base class.
588

589
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
590
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
591
  tasklets know nothing about locks.
592

593
  Subclasses must follow these rules:
594
    - Implement CheckPrereq
595
    - Implement Exec
596

597
  """
598
  def __init__(self, lu):
599
    self.lu = lu
600

    
601
    # Shortcuts
602
    self.cfg = lu.cfg
603
    self.rpc = lu.rpc
604

    
605
  def CheckPrereq(self):
606
    """Check prerequisites for this tasklets.
607

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

612
    The method should raise errors.OpPrereqError in case something is not
613
    fulfilled. Its return value is ignored.
614

615
    This method should also update all parameters to their canonical form if it
616
    hasn't been done before.
617

618
    """
619
    pass
620

    
621
  def Exec(self, feedback_fn):
622
    """Execute the tasklet.
623

624
    This method should implement the actual work. It should raise
625
    errors.OpExecError for failures that are somewhat dealt with in code, or
626
    expected.
627

628
    """
629
    raise NotImplementedError
630

    
631

    
632
def _GetWantedNodes(lu, nodes):
633
  """Returns list of checked and expanded node names.
634

635
  @type lu: L{LogicalUnit}
636
  @param lu: the logical unit on whose behalf we execute
637
  @type nodes: list
638
  @param nodes: list of node names or None for all nodes
639
  @rtype: list
640
  @return: the list of nodes, sorted
641
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
642

643
  """
644
  if not nodes:
645
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
646
      " non-empty list of nodes whose name is to be expanded.")
647

    
648
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
649
  return utils.NiceSort(wanted)
650

    
651

    
652
def _GetWantedInstances(lu, instances):
653
  """Returns list of checked and expanded instance names.
654

655
  @type lu: L{LogicalUnit}
656
  @param lu: the logical unit on whose behalf we execute
657
  @type instances: list
658
  @param instances: list of instance names or None for all instances
659
  @rtype: list
660
  @return: the list of instances, sorted
661
  @raise errors.OpPrereqError: if the instances parameter is wrong type
662
  @raise errors.OpPrereqError: if any of the passed instances is not found
663

664
  """
665
  if instances:
666
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
667
  else:
668
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
669
  return wanted
670

    
671

    
672
def _GetUpdatedParams(old_params, update_dict,
673
                      use_default=True, use_none=False):
674
  """Return the new version of a parameter dictionary.
675

676
  @type old_params: dict
677
  @param old_params: old parameters
678
  @type update_dict: dict
679
  @param update_dict: dict containing new parameter values, or
680
      constants.VALUE_DEFAULT to reset the parameter to its default
681
      value
682
  @param use_default: boolean
683
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
684
      values as 'to be deleted' values
685
  @param use_none: boolean
686
  @type use_none: whether to recognise C{None} values as 'to be
687
      deleted' values
688
  @rtype: dict
689
  @return: the new parameter dictionary
690

691
  """
692
  params_copy = copy.deepcopy(old_params)
693
  for key, val in update_dict.iteritems():
694
    if ((use_default and val == constants.VALUE_DEFAULT) or
695
        (use_none and val is None)):
696
      try:
697
        del params_copy[key]
698
      except KeyError:
699
        pass
700
    else:
701
      params_copy[key] = val
702
  return params_copy
703

    
704

    
705
def _CheckOutputFields(static, dynamic, selected):
706
  """Checks whether all selected fields are valid.
707

708
  @type static: L{utils.FieldSet}
709
  @param static: static fields set
710
  @type dynamic: L{utils.FieldSet}
711
  @param dynamic: dynamic fields set
712

713
  """
714
  f = utils.FieldSet()
715
  f.Extend(static)
716
  f.Extend(dynamic)
717

    
718
  delta = f.NonMatching(selected)
719
  if delta:
720
    raise errors.OpPrereqError("Unknown output fields selected: %s"
721
                               % ",".join(delta), errors.ECODE_INVAL)
722

    
723

    
724
def _CheckGlobalHvParams(params):
725
  """Validates that given hypervisor params are not global ones.
726

727
  This will ensure that instances don't get customised versions of
728
  global params.
729

730
  """
731
  used_globals = constants.HVC_GLOBALS.intersection(params)
732
  if used_globals:
733
    msg = ("The following hypervisor parameters are global and cannot"
734
           " be customized at instance level, please modify them at"
735
           " cluster level: %s" % utils.CommaJoin(used_globals))
736
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
737

    
738

    
739
def _CheckNodeOnline(lu, node):
740
  """Ensure that a given node is online.
741

742
  @param lu: the LU on behalf of which we make the check
743
  @param node: the node to check
744
  @raise errors.OpPrereqError: if the node is offline
745

746
  """
747
  if lu.cfg.GetNodeInfo(node).offline:
748
    raise errors.OpPrereqError("Can't use offline node %s" % node,
749
                               errors.ECODE_INVAL)
750

    
751

    
752
def _CheckNodeNotDrained(lu, node):
753
  """Ensure that a given node is not drained.
754

755
  @param lu: the LU on behalf of which we make the check
756
  @param node: the node to check
757
  @raise errors.OpPrereqError: if the node is drained
758

759
  """
760
  if lu.cfg.GetNodeInfo(node).drained:
761
    raise errors.OpPrereqError("Can't use drained node %s" % node,
762
                               errors.ECODE_INVAL)
763

    
764

    
765
def _CheckNodeHasOS(lu, node, os_name, force_variant):
766
  """Ensure that a node supports a given OS.
767

768
  @param lu: the LU on behalf of which we make the check
769
  @param node: the node to check
770
  @param os_name: the OS to query about
771
  @param force_variant: whether to ignore variant errors
772
  @raise errors.OpPrereqError: if the node is not supporting the OS
773

774
  """
775
  result = lu.rpc.call_os_get(node, os_name)
776
  result.Raise("OS '%s' not in supported OS list for node %s" %
777
               (os_name, node),
778
               prereq=True, ecode=errors.ECODE_INVAL)
779
  if not force_variant:
780
    _CheckOSVariant(result.payload, os_name)
781

    
782

    
783
def _RequireFileStorage():
784
  """Checks that file storage is enabled.
785

786
  @raise errors.OpPrereqError: when file storage is disabled
787

788
  """
789
  if not constants.ENABLE_FILE_STORAGE:
790
    raise errors.OpPrereqError("File storage disabled at configure time",
791
                               errors.ECODE_INVAL)
792

    
793

    
794
def _CheckDiskTemplate(template):
795
  """Ensure a given disk template is valid.
796

797
  """
798
  if template not in constants.DISK_TEMPLATES:
799
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
800
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
801
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
802
  if template == constants.DT_FILE:
803
    _RequireFileStorage()
804
  return True
805

    
806

    
807
def _CheckStorageType(storage_type):
808
  """Ensure a given storage type is valid.
809

810
  """
811
  if storage_type not in constants.VALID_STORAGE_TYPES:
812
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
813
                               errors.ECODE_INVAL)
814
  if storage_type == constants.ST_FILE:
815
    _RequireFileStorage()
816
  return True
817

    
818

    
819
def _GetClusterDomainSecret():
820
  """Reads the cluster domain secret.
821

822
  """
823
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
824
                               strict=True)
825

    
826

    
827
def _CheckInstanceDown(lu, instance, reason):
828
  """Ensure that an instance is not running."""
829
  if instance.admin_up:
830
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
831
                               (instance.name, reason), errors.ECODE_STATE)
832

    
833
  pnode = instance.primary_node
834
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
835
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
836
              prereq=True, ecode=errors.ECODE_ENVIRON)
837

    
838
  if instance.name in ins_l.payload:
839
    raise errors.OpPrereqError("Instance %s is running, %s" %
840
                               (instance.name, reason), errors.ECODE_STATE)
841

    
842

    
843
def _ExpandItemName(fn, name, kind):
844
  """Expand an item name.
845

846
  @param fn: the function to use for expansion
847
  @param name: requested item name
848
  @param kind: text description ('Node' or 'Instance')
849
  @return: the resolved (full) name
850
  @raise errors.OpPrereqError: if the item is not found
851

852
  """
853
  full_name = fn(name)
854
  if full_name is None:
855
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
856
                               errors.ECODE_NOENT)
857
  return full_name
858

    
859

    
860
def _ExpandNodeName(cfg, name):
861
  """Wrapper over L{_ExpandItemName} for nodes."""
862
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
863

    
864

    
865
def _ExpandInstanceName(cfg, name):
866
  """Wrapper over L{_ExpandItemName} for instance."""
867
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
868

    
869

    
870
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
871
                          memory, vcpus, nics, disk_template, disks,
872
                          bep, hvp, hypervisor_name):
873
  """Builds instance related env variables for hooks
874

875
  This builds the hook environment from individual variables.
876

877
  @type name: string
878
  @param name: the name of the instance
879
  @type primary_node: string
880
  @param primary_node: the name of the instance's primary node
881
  @type secondary_nodes: list
882
  @param secondary_nodes: list of secondary nodes as strings
883
  @type os_type: string
884
  @param os_type: the name of the instance's OS
885
  @type status: boolean
886
  @param status: the should_run status of the instance
887
  @type memory: string
888
  @param memory: the memory size of the instance
889
  @type vcpus: string
890
  @param vcpus: the count of VCPUs the instance has
891
  @type nics: list
892
  @param nics: list of tuples (ip, mac, mode, link) representing
893
      the NICs the instance has
894
  @type disk_template: string
895
  @param disk_template: the disk template of the instance
896
  @type disks: list
897
  @param disks: the list of (size, mode) pairs
898
  @type bep: dict
899
  @param bep: the backend parameters for the instance
900
  @type hvp: dict
901
  @param hvp: the hypervisor parameters for the instance
902
  @type hypervisor_name: string
903
  @param hypervisor_name: the hypervisor for the instance
904
  @rtype: dict
905
  @return: the hook environment for this instance
906

907
  """
908
  if status:
909
    str_status = "up"
910
  else:
911
    str_status = "down"
912
  env = {
913
    "OP_TARGET": name,
914
    "INSTANCE_NAME": name,
915
    "INSTANCE_PRIMARY": primary_node,
916
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
917
    "INSTANCE_OS_TYPE": os_type,
918
    "INSTANCE_STATUS": str_status,
919
    "INSTANCE_MEMORY": memory,
920
    "INSTANCE_VCPUS": vcpus,
921
    "INSTANCE_DISK_TEMPLATE": disk_template,
922
    "INSTANCE_HYPERVISOR": hypervisor_name,
923
  }
924

    
925
  if nics:
926
    nic_count = len(nics)
927
    for idx, (ip, mac, mode, link) in enumerate(nics):
928
      if ip is None:
929
        ip = ""
930
      env["INSTANCE_NIC%d_IP" % idx] = ip
931
      env["INSTANCE_NIC%d_MAC" % idx] = mac
932
      env["INSTANCE_NIC%d_MODE" % idx] = mode
933
      env["INSTANCE_NIC%d_LINK" % idx] = link
934
      if mode == constants.NIC_MODE_BRIDGED:
935
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
936
  else:
937
    nic_count = 0
938

    
939
  env["INSTANCE_NIC_COUNT"] = nic_count
940

    
941
  if disks:
942
    disk_count = len(disks)
943
    for idx, (size, mode) in enumerate(disks):
944
      env["INSTANCE_DISK%d_SIZE" % idx] = size
945
      env["INSTANCE_DISK%d_MODE" % idx] = mode
946
  else:
947
    disk_count = 0
948

    
949
  env["INSTANCE_DISK_COUNT"] = disk_count
950

    
951
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
952
    for key, value in source.items():
953
      env["INSTANCE_%s_%s" % (kind, key)] = value
954

    
955
  return env
956

    
957

    
958
def _NICListToTuple(lu, nics):
959
  """Build a list of nic information tuples.
960

961
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
962
  value in LUQueryInstanceData.
963

964
  @type lu:  L{LogicalUnit}
965
  @param lu: the logical unit on whose behalf we execute
966
  @type nics: list of L{objects.NIC}
967
  @param nics: list of nics to convert to hooks tuples
968

969
  """
970
  hooks_nics = []
971
  cluster = lu.cfg.GetClusterInfo()
972
  for nic in nics:
973
    ip = nic.ip
974
    mac = nic.mac
975
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
976
    mode = filled_params[constants.NIC_MODE]
977
    link = filled_params[constants.NIC_LINK]
978
    hooks_nics.append((ip, mac, mode, link))
979
  return hooks_nics
980

    
981

    
982
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
983
  """Builds instance related env variables for hooks from an object.
984

985
  @type lu: L{LogicalUnit}
986
  @param lu: the logical unit on whose behalf we execute
987
  @type instance: L{objects.Instance}
988
  @param instance: the instance for which we should build the
989
      environment
990
  @type override: dict
991
  @param override: dictionary with key/values that will override
992
      our values
993
  @rtype: dict
994
  @return: the hook environment dictionary
995

996
  """
997
  cluster = lu.cfg.GetClusterInfo()
998
  bep = cluster.FillBE(instance)
999
  hvp = cluster.FillHV(instance)
1000
  args = {
1001
    'name': instance.name,
1002
    'primary_node': instance.primary_node,
1003
    'secondary_nodes': instance.secondary_nodes,
1004
    'os_type': instance.os,
1005
    'status': instance.admin_up,
1006
    'memory': bep[constants.BE_MEMORY],
1007
    'vcpus': bep[constants.BE_VCPUS],
1008
    'nics': _NICListToTuple(lu, instance.nics),
1009
    'disk_template': instance.disk_template,
1010
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
1011
    'bep': bep,
1012
    'hvp': hvp,
1013
    'hypervisor_name': instance.hypervisor,
1014
  }
1015
  if override:
1016
    args.update(override)
1017
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
1018

    
1019

    
1020
def _AdjustCandidatePool(lu, exceptions):
1021
  """Adjust the candidate pool after node operations.
1022

1023
  """
1024
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1025
  if mod_list:
1026
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1027
               utils.CommaJoin(node.name for node in mod_list))
1028
    for name in mod_list:
1029
      lu.context.ReaddNode(name)
1030
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1031
  if mc_now > mc_max:
1032
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1033
               (mc_now, mc_max))
1034

    
1035

    
1036
def _DecideSelfPromotion(lu, exceptions=None):
1037
  """Decide whether I should promote myself as a master candidate.
1038

1039
  """
1040
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1041
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1042
  # the new node will increase mc_max with one, so:
1043
  mc_should = min(mc_should + 1, cp_size)
1044
  return mc_now < mc_should
1045

    
1046

    
1047
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1048
  """Check that the brigdes needed by a list of nics exist.
1049

1050
  """
1051
  cluster = lu.cfg.GetClusterInfo()
1052
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1053
  brlist = [params[constants.NIC_LINK] for params in paramslist
1054
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1055
  if brlist:
1056
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1057
    result.Raise("Error checking bridges on destination node '%s'" %
1058
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1059

    
1060

    
1061
def _CheckInstanceBridgesExist(lu, instance, node=None):
1062
  """Check that the brigdes needed by an instance exist.
1063

1064
  """
1065
  if node is None:
1066
    node = instance.primary_node
1067
  _CheckNicsBridgesExist(lu, instance.nics, node)
1068

    
1069

    
1070
def _CheckOSVariant(os_obj, name):
1071
  """Check whether an OS name conforms to the os variants specification.
1072

1073
  @type os_obj: L{objects.OS}
1074
  @param os_obj: OS object to check
1075
  @type name: string
1076
  @param name: OS name passed by the user, to check for validity
1077

1078
  """
1079
  if not os_obj.supported_variants:
1080
    return
1081
  try:
1082
    variant = name.split("+", 1)[1]
1083
  except IndexError:
1084
    raise errors.OpPrereqError("OS name must include a variant",
1085
                               errors.ECODE_INVAL)
1086

    
1087
  if variant not in os_obj.supported_variants:
1088
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1089

    
1090

    
1091
def _GetNodeInstancesInner(cfg, fn):
1092
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1093

    
1094

    
1095
def _GetNodeInstances(cfg, node_name):
1096
  """Returns a list of all primary and secondary instances on a node.
1097

1098
  """
1099

    
1100
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1101

    
1102

    
1103
def _GetNodePrimaryInstances(cfg, node_name):
1104
  """Returns primary instances on a node.
1105

1106
  """
1107
  return _GetNodeInstancesInner(cfg,
1108
                                lambda inst: node_name == inst.primary_node)
1109

    
1110

    
1111
def _GetNodeSecondaryInstances(cfg, node_name):
1112
  """Returns secondary instances on a node.
1113

1114
  """
1115
  return _GetNodeInstancesInner(cfg,
1116
                                lambda inst: node_name in inst.secondary_nodes)
1117

    
1118

    
1119
def _GetStorageTypeArgs(cfg, storage_type):
1120
  """Returns the arguments for a storage type.
1121

1122
  """
1123
  # Special case for file storage
1124
  if storage_type == constants.ST_FILE:
1125
    # storage.FileStorage wants a list of storage directories
1126
    return [[cfg.GetFileStorageDir()]]
1127

    
1128
  return []
1129

    
1130

    
1131
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1132
  faulty = []
1133

    
1134
  for dev in instance.disks:
1135
    cfg.SetDiskID(dev, node_name)
1136

    
1137
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1138
  result.Raise("Failed to get disk status from node %s" % node_name,
1139
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1140

    
1141
  for idx, bdev_status in enumerate(result.payload):
1142
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1143
      faulty.append(idx)
1144

    
1145
  return faulty
1146

    
1147

    
1148
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1149
  """Check the sanity of iallocator and node arguments and use the
1150
  cluster-wide iallocator if appropriate.
1151

1152
  Check that at most one of (iallocator, node) is specified. If none is
1153
  specified, then the LU's opcode's iallocator slot is filled with the
1154
  cluster-wide default iallocator.
1155

1156
  @type iallocator_slot: string
1157
  @param iallocator_slot: the name of the opcode iallocator slot
1158
  @type node_slot: string
1159
  @param node_slot: the name of the opcode target node slot
1160

1161
  """
1162
  node = getattr(lu.op, node_slot, None)
1163
  iallocator = getattr(lu.op, iallocator_slot, None)
1164

    
1165
  if node is not None and iallocator is not None:
1166
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1167
                               errors.ECODE_INVAL)
1168
  elif node is None and iallocator is None:
1169
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1170
    if default_iallocator:
1171
      setattr(lu.op, iallocator_slot, default_iallocator)
1172
    else:
1173
      raise errors.OpPrereqError("No iallocator or node given and no"
1174
                                 " cluster-wide default iallocator found."
1175
                                 " Please specify either an iallocator or a"
1176
                                 " node, or set a cluster-wide default"
1177
                                 " iallocator.")
1178

    
1179

    
1180
class LUPostInitCluster(LogicalUnit):
1181
  """Logical unit for running hooks after cluster initialization.
1182

1183
  """
1184
  HPATH = "cluster-init"
1185
  HTYPE = constants.HTYPE_CLUSTER
1186

    
1187
  def BuildHooksEnv(self):
1188
    """Build hooks env.
1189

1190
    """
1191
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1192
    mn = self.cfg.GetMasterNode()
1193
    return env, [], [mn]
1194

    
1195
  def Exec(self, feedback_fn):
1196
    """Nothing to do.
1197

1198
    """
1199
    return True
1200

    
1201

    
1202
class LUDestroyCluster(LogicalUnit):
1203
  """Logical unit for destroying the cluster.
1204

1205
  """
1206
  HPATH = "cluster-destroy"
1207
  HTYPE = constants.HTYPE_CLUSTER
1208

    
1209
  def BuildHooksEnv(self):
1210
    """Build hooks env.
1211

1212
    """
1213
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1214
    return env, [], []
1215

    
1216
  def CheckPrereq(self):
1217
    """Check prerequisites.
1218

1219
    This checks whether the cluster is empty.
1220

1221
    Any errors are signaled by raising errors.OpPrereqError.
1222

1223
    """
1224
    master = self.cfg.GetMasterNode()
1225

    
1226
    nodelist = self.cfg.GetNodeList()
1227
    if len(nodelist) != 1 or nodelist[0] != master:
1228
      raise errors.OpPrereqError("There are still %d node(s) in"
1229
                                 " this cluster." % (len(nodelist) - 1),
1230
                                 errors.ECODE_INVAL)
1231
    instancelist = self.cfg.GetInstanceList()
1232
    if instancelist:
1233
      raise errors.OpPrereqError("There are still %d instance(s) in"
1234
                                 " this cluster." % len(instancelist),
1235
                                 errors.ECODE_INVAL)
1236

    
1237
  def Exec(self, feedback_fn):
1238
    """Destroys the cluster.
1239

1240
    """
1241
    master = self.cfg.GetMasterNode()
1242
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1243

    
1244
    # Run post hooks on master node before it's removed
1245
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1246
    try:
1247
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1248
    except:
1249
      # pylint: disable-msg=W0702
1250
      self.LogWarning("Errors occurred running hooks on %s" % master)
1251

    
1252
    result = self.rpc.call_node_stop_master(master, False)
1253
    result.Raise("Could not disable the master role")
1254

    
1255
    if modify_ssh_setup:
1256
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1257
      utils.CreateBackup(priv_key)
1258
      utils.CreateBackup(pub_key)
1259

    
1260
    return master
1261

    
1262

    
1263
def _VerifyCertificate(filename):
1264
  """Verifies a certificate for LUVerifyCluster.
1265

1266
  @type filename: string
1267
  @param filename: Path to PEM file
1268

1269
  """
1270
  try:
1271
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1272
                                           utils.ReadFile(filename))
1273
  except Exception, err: # pylint: disable-msg=W0703
1274
    return (LUVerifyCluster.ETYPE_ERROR,
1275
            "Failed to load X509 certificate %s: %s" % (filename, err))
1276

    
1277
  (errcode, msg) = \
1278
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1279
                                constants.SSL_CERT_EXPIRATION_ERROR)
1280

    
1281
  if msg:
1282
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1283
  else:
1284
    fnamemsg = None
1285

    
1286
  if errcode is None:
1287
    return (None, fnamemsg)
1288
  elif errcode == utils.CERT_WARNING:
1289
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1290
  elif errcode == utils.CERT_ERROR:
1291
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1292

    
1293
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1294

    
1295

    
1296
class LUVerifyCluster(LogicalUnit):
1297
  """Verifies the cluster status.
1298

1299
  """
1300
  HPATH = "cluster-verify"
1301
  HTYPE = constants.HTYPE_CLUSTER
1302
  _OP_PARAMS = [
1303
    ("skip_checks", _EmptyList,
1304
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1305
    ("verbose", False, _TBool),
1306
    ("error_codes", False, _TBool),
1307
    ("debug_simulate_errors", False, _TBool),
1308
    ]
1309
  REQ_BGL = False
1310

    
1311
  TCLUSTER = "cluster"
1312
  TNODE = "node"
1313
  TINSTANCE = "instance"
1314

    
1315
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1316
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1317
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1318
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1319
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1320
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1321
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1322
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1323
  ENODEDRBD = (TNODE, "ENODEDRBD")
1324
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1325
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1326
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1327
  ENODEHV = (TNODE, "ENODEHV")
1328
  ENODELVM = (TNODE, "ENODELVM")
1329
  ENODEN1 = (TNODE, "ENODEN1")
1330
  ENODENET = (TNODE, "ENODENET")
1331
  ENODEOS = (TNODE, "ENODEOS")
1332
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1333
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1334
  ENODERPC = (TNODE, "ENODERPC")
1335
  ENODESSH = (TNODE, "ENODESSH")
1336
  ENODEVERSION = (TNODE, "ENODEVERSION")
1337
  ENODESETUP = (TNODE, "ENODESETUP")
1338
  ENODETIME = (TNODE, "ENODETIME")
1339

    
1340
  ETYPE_FIELD = "code"
1341
  ETYPE_ERROR = "ERROR"
1342
  ETYPE_WARNING = "WARNING"
1343

    
1344
  class NodeImage(object):
1345
    """A class representing the logical and physical status of a node.
1346

1347
    @type name: string
1348
    @ivar name: the node name to which this object refers
1349
    @ivar volumes: a structure as returned from
1350
        L{ganeti.backend.GetVolumeList} (runtime)
1351
    @ivar instances: a list of running instances (runtime)
1352
    @ivar pinst: list of configured primary instances (config)
1353
    @ivar sinst: list of configured secondary instances (config)
1354
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1355
        of this node (config)
1356
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1357
    @ivar dfree: free disk, as reported by the node (runtime)
1358
    @ivar offline: the offline status (config)
1359
    @type rpc_fail: boolean
1360
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1361
        not whether the individual keys were correct) (runtime)
1362
    @type lvm_fail: boolean
1363
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1364
    @type hyp_fail: boolean
1365
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1366
    @type ghost: boolean
1367
    @ivar ghost: whether this is a known node or not (config)
1368
    @type os_fail: boolean
1369
    @ivar os_fail: whether the RPC call didn't return valid OS data
1370
    @type oslist: list
1371
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1372

1373
    """
1374
    def __init__(self, offline=False, name=None):
1375
      self.name = name
1376
      self.volumes = {}
1377
      self.instances = []
1378
      self.pinst = []
1379
      self.sinst = []
1380
      self.sbp = {}
1381
      self.mfree = 0
1382
      self.dfree = 0
1383
      self.offline = offline
1384
      self.rpc_fail = False
1385
      self.lvm_fail = False
1386
      self.hyp_fail = False
1387
      self.ghost = False
1388
      self.os_fail = False
1389
      self.oslist = {}
1390

    
1391
  def ExpandNames(self):
1392
    self.needed_locks = {
1393
      locking.LEVEL_NODE: locking.ALL_SET,
1394
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1395
    }
1396
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1397

    
1398
  def _Error(self, ecode, item, msg, *args, **kwargs):
1399
    """Format an error message.
1400

1401
    Based on the opcode's error_codes parameter, either format a
1402
    parseable error code, or a simpler error string.
1403

1404
    This must be called only from Exec and functions called from Exec.
1405

1406
    """
1407
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1408
    itype, etxt = ecode
1409
    # first complete the msg
1410
    if args:
1411
      msg = msg % args
1412
    # then format the whole message
1413
    if self.op.error_codes:
1414
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1415
    else:
1416
      if item:
1417
        item = " " + item
1418
      else:
1419
        item = ""
1420
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1421
    # and finally report it via the feedback_fn
1422
    self._feedback_fn("  - %s" % msg)
1423

    
1424
  def _ErrorIf(self, cond, *args, **kwargs):
1425
    """Log an error message if the passed condition is True.
1426

1427
    """
1428
    cond = bool(cond) or self.op.debug_simulate_errors
1429
    if cond:
1430
      self._Error(*args, **kwargs)
1431
    # do not mark the operation as failed for WARN cases only
1432
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1433
      self.bad = self.bad or cond
1434

    
1435
  def _VerifyNode(self, ninfo, nresult):
1436
    """Perform some basic validation on data returned from a node.
1437

1438
    - check the result data structure is well formed and has all the mandatory
1439
      fields
1440
    - check ganeti version
1441

1442
    @type ninfo: L{objects.Node}
1443
    @param ninfo: the node to check
1444
    @param nresult: the results from the node
1445
    @rtype: boolean
1446
    @return: whether overall this call was successful (and we can expect
1447
         reasonable values in the respose)
1448

1449
    """
1450
    node = ninfo.name
1451
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1452

    
1453
    # main result, nresult should be a non-empty dict
1454
    test = not nresult or not isinstance(nresult, dict)
1455
    _ErrorIf(test, self.ENODERPC, node,
1456
                  "unable to verify node: no data returned")
1457
    if test:
1458
      return False
1459

    
1460
    # compares ganeti version
1461
    local_version = constants.PROTOCOL_VERSION
1462
    remote_version = nresult.get("version", None)
1463
    test = not (remote_version and
1464
                isinstance(remote_version, (list, tuple)) and
1465
                len(remote_version) == 2)
1466
    _ErrorIf(test, self.ENODERPC, node,
1467
             "connection to node returned invalid data")
1468
    if test:
1469
      return False
1470

    
1471
    test = local_version != remote_version[0]
1472
    _ErrorIf(test, self.ENODEVERSION, node,
1473
             "incompatible protocol versions: master %s,"
1474
             " node %s", local_version, remote_version[0])
1475
    if test:
1476
      return False
1477

    
1478
    # node seems compatible, we can actually try to look into its results
1479

    
1480
    # full package version
1481
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1482
                  self.ENODEVERSION, node,
1483
                  "software version mismatch: master %s, node %s",
1484
                  constants.RELEASE_VERSION, remote_version[1],
1485
                  code=self.ETYPE_WARNING)
1486

    
1487
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1488
    if isinstance(hyp_result, dict):
1489
      for hv_name, hv_result in hyp_result.iteritems():
1490
        test = hv_result is not None
1491
        _ErrorIf(test, self.ENODEHV, node,
1492
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1493

    
1494

    
1495
    test = nresult.get(constants.NV_NODESETUP,
1496
                           ["Missing NODESETUP results"])
1497
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1498
             "; ".join(test))
1499

    
1500
    return True
1501

    
1502
  def _VerifyNodeTime(self, ninfo, nresult,
1503
                      nvinfo_starttime, nvinfo_endtime):
1504
    """Check the node time.
1505

1506
    @type ninfo: L{objects.Node}
1507
    @param ninfo: the node to check
1508
    @param nresult: the remote results for the node
1509
    @param nvinfo_starttime: the start time of the RPC call
1510
    @param nvinfo_endtime: the end time of the RPC call
1511

1512
    """
1513
    node = ninfo.name
1514
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1515

    
1516
    ntime = nresult.get(constants.NV_TIME, None)
1517
    try:
1518
      ntime_merged = utils.MergeTime(ntime)
1519
    except (ValueError, TypeError):
1520
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1521
      return
1522

    
1523
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1524
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1525
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1526
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1527
    else:
1528
      ntime_diff = None
1529

    
1530
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1531
             "Node time diverges by at least %s from master node time",
1532
             ntime_diff)
1533

    
1534
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1535
    """Check the node time.
1536

1537
    @type ninfo: L{objects.Node}
1538
    @param ninfo: the node to check
1539
    @param nresult: the remote results for the node
1540
    @param vg_name: the configured VG name
1541

1542
    """
1543
    if vg_name is None:
1544
      return
1545

    
1546
    node = ninfo.name
1547
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1548

    
1549
    # checks vg existence and size > 20G
1550
    vglist = nresult.get(constants.NV_VGLIST, None)
1551
    test = not vglist
1552
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1553
    if not test:
1554
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1555
                                            constants.MIN_VG_SIZE)
1556
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1557

    
1558
    # check pv names
1559
    pvlist = nresult.get(constants.NV_PVLIST, None)
1560
    test = pvlist is None
1561
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1562
    if not test:
1563
      # check that ':' is not present in PV names, since it's a
1564
      # special character for lvcreate (denotes the range of PEs to
1565
      # use on the PV)
1566
      for _, pvname, owner_vg in pvlist:
1567
        test = ":" in pvname
1568
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1569
                 " '%s' of VG '%s'", pvname, owner_vg)
1570

    
1571
  def _VerifyNodeNetwork(self, ninfo, nresult):
1572
    """Check the node time.
1573

1574
    @type ninfo: L{objects.Node}
1575
    @param ninfo: the node to check
1576
    @param nresult: the remote results for the node
1577

1578
    """
1579
    node = ninfo.name
1580
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1581

    
1582
    test = constants.NV_NODELIST not in nresult
1583
    _ErrorIf(test, self.ENODESSH, node,
1584
             "node hasn't returned node ssh connectivity data")
1585
    if not test:
1586
      if nresult[constants.NV_NODELIST]:
1587
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1588
          _ErrorIf(True, self.ENODESSH, node,
1589
                   "ssh communication with node '%s': %s", a_node, a_msg)
1590

    
1591
    test = constants.NV_NODENETTEST not in nresult
1592
    _ErrorIf(test, self.ENODENET, node,
1593
             "node hasn't returned node tcp connectivity data")
1594
    if not test:
1595
      if nresult[constants.NV_NODENETTEST]:
1596
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1597
        for anode in nlist:
1598
          _ErrorIf(True, self.ENODENET, node,
1599
                   "tcp communication with node '%s': %s",
1600
                   anode, nresult[constants.NV_NODENETTEST][anode])
1601

    
1602
    test = constants.NV_MASTERIP not in nresult
1603
    _ErrorIf(test, self.ENODENET, node,
1604
             "node hasn't returned node master IP reachability data")
1605
    if not test:
1606
      if not nresult[constants.NV_MASTERIP]:
1607
        if node == self.master_node:
1608
          msg = "the master node cannot reach the master IP (not configured?)"
1609
        else:
1610
          msg = "cannot reach the master IP"
1611
        _ErrorIf(True, self.ENODENET, node, msg)
1612

    
1613

    
1614
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1615
    """Verify an instance.
1616

1617
    This function checks to see if the required block devices are
1618
    available on the instance's node.
1619

1620
    """
1621
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1622
    node_current = instanceconfig.primary_node
1623

    
1624
    node_vol_should = {}
1625
    instanceconfig.MapLVsByNode(node_vol_should)
1626

    
1627
    for node in node_vol_should:
1628
      n_img = node_image[node]
1629
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1630
        # ignore missing volumes on offline or broken nodes
1631
        continue
1632
      for volume in node_vol_should[node]:
1633
        test = volume not in n_img.volumes
1634
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1635
                 "volume %s missing on node %s", volume, node)
1636

    
1637
    if instanceconfig.admin_up:
1638
      pri_img = node_image[node_current]
1639
      test = instance not in pri_img.instances and not pri_img.offline
1640
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1641
               "instance not running on its primary node %s",
1642
               node_current)
1643

    
1644
    for node, n_img in node_image.items():
1645
      if (not node == node_current):
1646
        test = instance in n_img.instances
1647
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1648
                 "instance should not run on node %s", node)
1649

    
1650
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1651
    """Verify if there are any unknown volumes in the cluster.
1652

1653
    The .os, .swap and backup volumes are ignored. All other volumes are
1654
    reported as unknown.
1655

1656
    """
1657
    for node, n_img in node_image.items():
1658
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1659
        # skip non-healthy nodes
1660
        continue
1661
      for volume in n_img.volumes:
1662
        test = (node not in node_vol_should or
1663
                volume not in node_vol_should[node])
1664
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1665
                      "volume %s is unknown", volume)
1666

    
1667
  def _VerifyOrphanInstances(self, instancelist, node_image):
1668
    """Verify the list of running instances.
1669

1670
    This checks what instances are running but unknown to the cluster.
1671

1672
    """
1673
    for node, n_img in node_image.items():
1674
      for o_inst in n_img.instances:
1675
        test = o_inst not in instancelist
1676
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1677
                      "instance %s on node %s should not exist", o_inst, node)
1678

    
1679
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1680
    """Verify N+1 Memory Resilience.
1681

1682
    Check that if one single node dies we can still start all the
1683
    instances it was primary for.
1684

1685
    """
1686
    for node, n_img in node_image.items():
1687
      # This code checks that every node which is now listed as
1688
      # secondary has enough memory to host all instances it is
1689
      # supposed to should a single other node in the cluster fail.
1690
      # FIXME: not ready for failover to an arbitrary node
1691
      # FIXME: does not support file-backed instances
1692
      # WARNING: we currently take into account down instances as well
1693
      # as up ones, considering that even if they're down someone
1694
      # might want to start them even in the event of a node failure.
1695
      for prinode, instances in n_img.sbp.items():
1696
        needed_mem = 0
1697
        for instance in instances:
1698
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1699
          if bep[constants.BE_AUTO_BALANCE]:
1700
            needed_mem += bep[constants.BE_MEMORY]
1701
        test = n_img.mfree < needed_mem
1702
        self._ErrorIf(test, self.ENODEN1, node,
1703
                      "not enough memory on to accommodate"
1704
                      " failovers should peer node %s fail", prinode)
1705

    
1706
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1707
                       master_files):
1708
    """Verifies and computes the node required file checksums.
1709

1710
    @type ninfo: L{objects.Node}
1711
    @param ninfo: the node to check
1712
    @param nresult: the remote results for the node
1713
    @param file_list: required list of files
1714
    @param local_cksum: dictionary of local files and their checksums
1715
    @param master_files: list of files that only masters should have
1716

1717
    """
1718
    node = ninfo.name
1719
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1720

    
1721
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1722
    test = not isinstance(remote_cksum, dict)
1723
    _ErrorIf(test, self.ENODEFILECHECK, node,
1724
             "node hasn't returned file checksum data")
1725
    if test:
1726
      return
1727

    
1728
    for file_name in file_list:
1729
      node_is_mc = ninfo.master_candidate
1730
      must_have = (file_name not in master_files) or node_is_mc
1731
      # missing
1732
      test1 = file_name not in remote_cksum
1733
      # invalid checksum
1734
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1735
      # existing and good
1736
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1737
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1738
               "file '%s' missing", file_name)
1739
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1740
               "file '%s' has wrong checksum", file_name)
1741
      # not candidate and this is not a must-have file
1742
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1743
               "file '%s' should not exist on non master"
1744
               " candidates (and the file is outdated)", file_name)
1745
      # all good, except non-master/non-must have combination
1746
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1747
               "file '%s' should not exist"
1748
               " on non master candidates", file_name)
1749

    
1750
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1751
                      drbd_map):
1752
    """Verifies and the node DRBD status.
1753

1754
    @type ninfo: L{objects.Node}
1755
    @param ninfo: the node to check
1756
    @param nresult: the remote results for the node
1757
    @param instanceinfo: the dict of instances
1758
    @param drbd_helper: the configured DRBD usermode helper
1759
    @param drbd_map: the DRBD map as returned by
1760
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1761

1762
    """
1763
    node = ninfo.name
1764
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1765

    
1766
    if drbd_helper:
1767
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1768
      test = (helper_result == None)
1769
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1770
               "no drbd usermode helper returned")
1771
      if helper_result:
1772
        status, payload = helper_result
1773
        test = not status
1774
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1775
                 "drbd usermode helper check unsuccessful: %s", payload)
1776
        test = status and (payload != drbd_helper)
1777
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1778
                 "wrong drbd usermode helper: %s", payload)
1779

    
1780
    # compute the DRBD minors
1781
    node_drbd = {}
1782
    for minor, instance in drbd_map[node].items():
1783
      test = instance not in instanceinfo
1784
      _ErrorIf(test, self.ECLUSTERCFG, None,
1785
               "ghost instance '%s' in temporary DRBD map", instance)
1786
        # ghost instance should not be running, but otherwise we
1787
        # don't give double warnings (both ghost instance and
1788
        # unallocated minor in use)
1789
      if test:
1790
        node_drbd[minor] = (instance, False)
1791
      else:
1792
        instance = instanceinfo[instance]
1793
        node_drbd[minor] = (instance.name, instance.admin_up)
1794

    
1795
    # and now check them
1796
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1797
    test = not isinstance(used_minors, (tuple, list))
1798
    _ErrorIf(test, self.ENODEDRBD, node,
1799
             "cannot parse drbd status file: %s", str(used_minors))
1800
    if test:
1801
      # we cannot check drbd status
1802
      return
1803

    
1804
    for minor, (iname, must_exist) in node_drbd.items():
1805
      test = minor not in used_minors and must_exist
1806
      _ErrorIf(test, self.ENODEDRBD, node,
1807
               "drbd minor %d of instance %s is not active", minor, iname)
1808
    for minor in used_minors:
1809
      test = minor not in node_drbd
1810
      _ErrorIf(test, self.ENODEDRBD, node,
1811
               "unallocated drbd minor %d is in use", minor)
1812

    
1813
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1814
    """Builds the node OS structures.
1815

1816
    @type ninfo: L{objects.Node}
1817
    @param ninfo: the node to check
1818
    @param nresult: the remote results for the node
1819
    @param nimg: the node image object
1820

1821
    """
1822
    node = ninfo.name
1823
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1824

    
1825
    remote_os = nresult.get(constants.NV_OSLIST, None)
1826
    test = (not isinstance(remote_os, list) or
1827
            not compat.all(isinstance(v, list) and len(v) == 7
1828
                           for v in remote_os))
1829

    
1830
    _ErrorIf(test, self.ENODEOS, node,
1831
             "node hasn't returned valid OS data")
1832

    
1833
    nimg.os_fail = test
1834

    
1835
    if test:
1836
      return
1837

    
1838
    os_dict = {}
1839

    
1840
    for (name, os_path, status, diagnose,
1841
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1842

    
1843
      if name not in os_dict:
1844
        os_dict[name] = []
1845

    
1846
      # parameters is a list of lists instead of list of tuples due to
1847
      # JSON lacking a real tuple type, fix it:
1848
      parameters = [tuple(v) for v in parameters]
1849
      os_dict[name].append((os_path, status, diagnose,
1850
                            set(variants), set(parameters), set(api_ver)))
1851

    
1852
    nimg.oslist = os_dict
1853

    
1854
  def _VerifyNodeOS(self, ninfo, nimg, base):
1855
    """Verifies the node OS list.
1856

1857
    @type ninfo: L{objects.Node}
1858
    @param ninfo: the node to check
1859
    @param nimg: the node image object
1860
    @param base: the 'template' node we match against (e.g. from the master)
1861

1862
    """
1863
    node = ninfo.name
1864
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1865

    
1866
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1867

    
1868
    for os_name, os_data in nimg.oslist.items():
1869
      assert os_data, "Empty OS status for OS %s?!" % os_name
1870
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1871
      _ErrorIf(not f_status, self.ENODEOS, node,
1872
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1873
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1874
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1875
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1876
      # this will catched in backend too
1877
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1878
               and not f_var, self.ENODEOS, node,
1879
               "OS %s with API at least %d does not declare any variant",
1880
               os_name, constants.OS_API_V15)
1881
      # comparisons with the 'base' image
1882
      test = os_name not in base.oslist
1883
      _ErrorIf(test, self.ENODEOS, node,
1884
               "Extra OS %s not present on reference node (%s)",
1885
               os_name, base.name)
1886
      if test:
1887
        continue
1888
      assert base.oslist[os_name], "Base node has empty OS status?"
1889
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1890
      if not b_status:
1891
        # base OS is invalid, skipping
1892
        continue
1893
      for kind, a, b in [("API version", f_api, b_api),
1894
                         ("variants list", f_var, b_var),
1895
                         ("parameters", f_param, b_param)]:
1896
        _ErrorIf(a != b, self.ENODEOS, node,
1897
                 "OS %s %s differs from reference node %s: %s vs. %s",
1898
                 kind, os_name, base.name,
1899
                 utils.CommaJoin(a), utils.CommaJoin(b))
1900

    
1901
    # check any missing OSes
1902
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1903
    _ErrorIf(missing, self.ENODEOS, node,
1904
             "OSes present on reference node %s but missing on this node: %s",
1905
             base.name, utils.CommaJoin(missing))
1906

    
1907
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1908
    """Verifies and updates the node volume data.
1909

1910
    This function will update a L{NodeImage}'s internal structures
1911
    with data from the remote call.
1912

1913
    @type ninfo: L{objects.Node}
1914
    @param ninfo: the node to check
1915
    @param nresult: the remote results for the node
1916
    @param nimg: the node image object
1917
    @param vg_name: the configured VG name
1918

1919
    """
1920
    node = ninfo.name
1921
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1922

    
1923
    nimg.lvm_fail = True
1924
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1925
    if vg_name is None:
1926
      pass
1927
    elif isinstance(lvdata, basestring):
1928
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1929
               utils.SafeEncode(lvdata))
1930
    elif not isinstance(lvdata, dict):
1931
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1932
    else:
1933
      nimg.volumes = lvdata
1934
      nimg.lvm_fail = False
1935

    
1936
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1937
    """Verifies and updates the node instance list.
1938

1939
    If the listing was successful, then updates this node's instance
1940
    list. Otherwise, it marks the RPC call as failed for the instance
1941
    list key.
1942

1943
    @type ninfo: L{objects.Node}
1944
    @param ninfo: the node to check
1945
    @param nresult: the remote results for the node
1946
    @param nimg: the node image object
1947

1948
    """
1949
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1950
    test = not isinstance(idata, list)
1951
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1952
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1953
    if test:
1954
      nimg.hyp_fail = True
1955
    else:
1956
      nimg.instances = idata
1957

    
1958
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1959
    """Verifies and computes a node information map
1960

1961
    @type ninfo: L{objects.Node}
1962
    @param ninfo: the node to check
1963
    @param nresult: the remote results for the node
1964
    @param nimg: the node image object
1965
    @param vg_name: the configured VG name
1966

1967
    """
1968
    node = ninfo.name
1969
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1970

    
1971
    # try to read free memory (from the hypervisor)
1972
    hv_info = nresult.get(constants.NV_HVINFO, None)
1973
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1974
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1975
    if not test:
1976
      try:
1977
        nimg.mfree = int(hv_info["memory_free"])
1978
      except (ValueError, TypeError):
1979
        _ErrorIf(True, self.ENODERPC, node,
1980
                 "node returned invalid nodeinfo, check hypervisor")
1981

    
1982
    # FIXME: devise a free space model for file based instances as well
1983
    if vg_name is not None:
1984
      test = (constants.NV_VGLIST not in nresult or
1985
              vg_name not in nresult[constants.NV_VGLIST])
1986
      _ErrorIf(test, self.ENODELVM, node,
1987
               "node didn't return data for the volume group '%s'"
1988
               " - it is either missing or broken", vg_name)
1989
      if not test:
1990
        try:
1991
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1992
        except (ValueError, TypeError):
1993
          _ErrorIf(True, self.ENODERPC, node,
1994
                   "node returned invalid LVM info, check LVM status")
1995

    
1996
  def BuildHooksEnv(self):
1997
    """Build hooks env.
1998

1999
    Cluster-Verify hooks just ran in the post phase and their failure makes
2000
    the output be logged in the verify output and the verification to fail.
2001

2002
    """
2003
    all_nodes = self.cfg.GetNodeList()
2004
    env = {
2005
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2006
      }
2007
    for node in self.cfg.GetAllNodesInfo().values():
2008
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2009

    
2010
    return env, [], all_nodes
2011

    
2012
  def Exec(self, feedback_fn):
2013
    """Verify integrity of cluster, performing various test on nodes.
2014

2015
    """
2016
    self.bad = False
2017
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2018
    verbose = self.op.verbose
2019
    self._feedback_fn = feedback_fn
2020
    feedback_fn("* Verifying global settings")
2021
    for msg in self.cfg.VerifyConfig():
2022
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2023

    
2024
    # Check the cluster certificates
2025
    for cert_filename in constants.ALL_CERT_FILES:
2026
      (errcode, msg) = _VerifyCertificate(cert_filename)
2027
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2028

    
2029
    vg_name = self.cfg.GetVGName()
2030
    drbd_helper = self.cfg.GetDRBDHelper()
2031
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2032
    cluster = self.cfg.GetClusterInfo()
2033
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2034
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2035
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2036
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2037
                        for iname in instancelist)
2038
    i_non_redundant = [] # Non redundant instances
2039
    i_non_a_balanced = [] # Non auto-balanced instances
2040
    n_offline = 0 # Count of offline nodes
2041
    n_drained = 0 # Count of nodes being drained
2042
    node_vol_should = {}
2043

    
2044
    # FIXME: verify OS list
2045
    # do local checksums
2046
    master_files = [constants.CLUSTER_CONF_FILE]
2047
    master_node = self.master_node = self.cfg.GetMasterNode()
2048
    master_ip = self.cfg.GetMasterIP()
2049

    
2050
    file_names = ssconf.SimpleStore().GetFileList()
2051
    file_names.extend(constants.ALL_CERT_FILES)
2052
    file_names.extend(master_files)
2053
    if cluster.modify_etc_hosts:
2054
      file_names.append(constants.ETC_HOSTS)
2055

    
2056
    local_checksums = utils.FingerprintFiles(file_names)
2057

    
2058
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2059
    node_verify_param = {
2060
      constants.NV_FILELIST: file_names,
2061
      constants.NV_NODELIST: [node.name for node in nodeinfo
2062
                              if not node.offline],
2063
      constants.NV_HYPERVISOR: hypervisors,
2064
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2065
                                  node.secondary_ip) for node in nodeinfo
2066
                                 if not node.offline],
2067
      constants.NV_INSTANCELIST: hypervisors,
2068
      constants.NV_VERSION: None,
2069
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2070
      constants.NV_NODESETUP: None,
2071
      constants.NV_TIME: None,
2072
      constants.NV_MASTERIP: (master_node, master_ip),
2073
      constants.NV_OSLIST: None,
2074
      }
2075

    
2076
    if vg_name is not None:
2077
      node_verify_param[constants.NV_VGLIST] = None
2078
      node_verify_param[constants.NV_LVLIST] = vg_name
2079
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2080
      node_verify_param[constants.NV_DRBDLIST] = None
2081

    
2082
    if drbd_helper:
2083
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2084

    
2085
    # Build our expected cluster state
2086
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2087
                                                 name=node.name))
2088
                      for node in nodeinfo)
2089

    
2090
    for instance in instancelist:
2091
      inst_config = instanceinfo[instance]
2092

    
2093
      for nname in inst_config.all_nodes:
2094
        if nname not in node_image:
2095
          # ghost node
2096
          gnode = self.NodeImage(name=nname)
2097
          gnode.ghost = True
2098
          node_image[nname] = gnode
2099

    
2100
      inst_config.MapLVsByNode(node_vol_should)
2101

    
2102
      pnode = inst_config.primary_node
2103
      node_image[pnode].pinst.append(instance)
2104

    
2105
      for snode in inst_config.secondary_nodes:
2106
        nimg = node_image[snode]
2107
        nimg.sinst.append(instance)
2108
        if pnode not in nimg.sbp:
2109
          nimg.sbp[pnode] = []
2110
        nimg.sbp[pnode].append(instance)
2111

    
2112
    # At this point, we have the in-memory data structures complete,
2113
    # except for the runtime information, which we'll gather next
2114

    
2115
    # Due to the way our RPC system works, exact response times cannot be
2116
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2117
    # time before and after executing the request, we can at least have a time
2118
    # window.
2119
    nvinfo_starttime = time.time()
2120
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2121
                                           self.cfg.GetClusterName())
2122
    nvinfo_endtime = time.time()
2123

    
2124
    all_drbd_map = self.cfg.ComputeDRBDMap()
2125

    
2126
    feedback_fn("* Verifying node status")
2127

    
2128
    refos_img = None
2129

    
2130
    for node_i in nodeinfo:
2131
      node = node_i.name
2132
      nimg = node_image[node]
2133

    
2134
      if node_i.offline:
2135
        if verbose:
2136
          feedback_fn("* Skipping offline node %s" % (node,))
2137
        n_offline += 1
2138
        continue
2139

    
2140
      if node == master_node:
2141
        ntype = "master"
2142
      elif node_i.master_candidate:
2143
        ntype = "master candidate"
2144
      elif node_i.drained:
2145
        ntype = "drained"
2146
        n_drained += 1
2147
      else:
2148
        ntype = "regular"
2149
      if verbose:
2150
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2151

    
2152
      msg = all_nvinfo[node].fail_msg
2153
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2154
      if msg:
2155
        nimg.rpc_fail = True
2156
        continue
2157

    
2158
      nresult = all_nvinfo[node].payload
2159

    
2160
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2161
      self._VerifyNodeNetwork(node_i, nresult)
2162
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2163
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2164
                            master_files)
2165
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2166
                           all_drbd_map)
2167
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2168

    
2169
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2170
      self._UpdateNodeInstances(node_i, nresult, nimg)
2171
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2172
      self._UpdateNodeOS(node_i, nresult, nimg)
2173
      if not nimg.os_fail:
2174
        if refos_img is None:
2175
          refos_img = nimg
2176
        self._VerifyNodeOS(node_i, nimg, refos_img)
2177

    
2178
    feedback_fn("* Verifying instance status")
2179
    for instance in instancelist:
2180
      if verbose:
2181
        feedback_fn("* Verifying instance %s" % instance)
2182
      inst_config = instanceinfo[instance]
2183
      self._VerifyInstance(instance, inst_config, node_image)
2184
      inst_nodes_offline = []
2185

    
2186
      pnode = inst_config.primary_node
2187
      pnode_img = node_image[pnode]
2188
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2189
               self.ENODERPC, pnode, "instance %s, connection to"
2190
               " primary node failed", instance)
2191

    
2192
      if pnode_img.offline:
2193
        inst_nodes_offline.append(pnode)
2194

    
2195
      # If the instance is non-redundant we cannot survive losing its primary
2196
      # node, so we are not N+1 compliant. On the other hand we have no disk
2197
      # templates with more than one secondary so that situation is not well
2198
      # supported either.
2199
      # FIXME: does not support file-backed instances
2200
      if not inst_config.secondary_nodes:
2201
        i_non_redundant.append(instance)
2202
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2203
               instance, "instance has multiple secondary nodes: %s",
2204
               utils.CommaJoin(inst_config.secondary_nodes),
2205
               code=self.ETYPE_WARNING)
2206

    
2207
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2208
        i_non_a_balanced.append(instance)
2209

    
2210
      for snode in inst_config.secondary_nodes:
2211
        s_img = node_image[snode]
2212
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2213
                 "instance %s, connection to secondary node failed", instance)
2214

    
2215
        if s_img.offline:
2216
          inst_nodes_offline.append(snode)
2217

    
2218
      # warn that the instance lives on offline nodes
2219
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2220
               "instance lives on offline node(s) %s",
2221
               utils.CommaJoin(inst_nodes_offline))
2222
      # ... or ghost nodes
2223
      for node in inst_config.all_nodes:
2224
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2225
                 "instance lives on ghost node %s", node)
2226

    
2227
    feedback_fn("* Verifying orphan volumes")
2228
    self._VerifyOrphanVolumes(node_vol_should, node_image)
2229

    
2230
    feedback_fn("* Verifying orphan instances")
2231
    self._VerifyOrphanInstances(instancelist, node_image)
2232

    
2233
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2234
      feedback_fn("* Verifying N+1 Memory redundancy")
2235
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2236

    
2237
    feedback_fn("* Other Notes")
2238
    if i_non_redundant:
2239
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2240
                  % len(i_non_redundant))
2241

    
2242
    if i_non_a_balanced:
2243
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2244
                  % len(i_non_a_balanced))
2245

    
2246
    if n_offline:
2247
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2248

    
2249
    if n_drained:
2250
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2251

    
2252
    return not self.bad
2253

    
2254
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2255
    """Analyze the post-hooks' result
2256

2257
    This method analyses the hook result, handles it, and sends some
2258
    nicely-formatted feedback back to the user.
2259

2260
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2261
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2262
    @param hooks_results: the results of the multi-node hooks rpc call
2263
    @param feedback_fn: function used send feedback back to the caller
2264
    @param lu_result: previous Exec result
2265
    @return: the new Exec result, based on the previous result
2266
        and hook results
2267

2268
    """
2269
    # We only really run POST phase hooks, and are only interested in
2270
    # their results
2271
    if phase == constants.HOOKS_PHASE_POST:
2272
      # Used to change hooks' output to proper indentation
2273
      indent_re = re.compile('^', re.M)
2274
      feedback_fn("* Hooks Results")
2275
      assert hooks_results, "invalid result from hooks"
2276

    
2277
      for node_name in hooks_results:
2278
        res = hooks_results[node_name]
2279
        msg = res.fail_msg
2280
        test = msg and not res.offline
2281
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2282
                      "Communication failure in hooks execution: %s", msg)
2283
        if res.offline or msg:
2284
          # No need to investigate payload if node is offline or gave an error.
2285
          # override manually lu_result here as _ErrorIf only
2286
          # overrides self.bad
2287
          lu_result = 1
2288
          continue
2289
        for script, hkr, output in res.payload:
2290
          test = hkr == constants.HKR_FAIL
2291
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2292
                        "Script %s failed, output:", script)
2293
          if test:
2294
            output = indent_re.sub('      ', output)
2295
            feedback_fn("%s" % output)
2296
            lu_result = 0
2297

    
2298
      return lu_result
2299

    
2300

    
2301
class LUVerifyDisks(NoHooksLU):
2302
  """Verifies the cluster disks status.
2303

2304
  """
2305
  REQ_BGL = False
2306

    
2307
  def ExpandNames(self):
2308
    self.needed_locks = {
2309
      locking.LEVEL_NODE: locking.ALL_SET,
2310
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2311
    }
2312
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2313

    
2314
  def Exec(self, feedback_fn):
2315
    """Verify integrity of cluster disks.
2316

2317
    @rtype: tuple of three items
2318
    @return: a tuple of (dict of node-to-node_error, list of instances
2319
        which need activate-disks, dict of instance: (node, volume) for
2320
        missing volumes
2321

2322
    """
2323
    result = res_nodes, res_instances, res_missing = {}, [], {}
2324

    
2325
    vg_name = self.cfg.GetVGName()
2326
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2327
    instances = [self.cfg.GetInstanceInfo(name)
2328
                 for name in self.cfg.GetInstanceList()]
2329

    
2330
    nv_dict = {}
2331
    for inst in instances:
2332
      inst_lvs = {}
2333
      if (not inst.admin_up or
2334
          inst.disk_template not in constants.DTS_NET_MIRROR):
2335
        continue
2336
      inst.MapLVsByNode(inst_lvs)
2337
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2338
      for node, vol_list in inst_lvs.iteritems():
2339
        for vol in vol_list:
2340
          nv_dict[(node, vol)] = inst
2341

    
2342
    if not nv_dict:
2343
      return result
2344

    
2345
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2346

    
2347
    for node in nodes:
2348
      # node_volume
2349
      node_res = node_lvs[node]
2350
      if node_res.offline:
2351
        continue
2352
      msg = node_res.fail_msg
2353
      if msg:
2354
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2355
        res_nodes[node] = msg
2356
        continue
2357

    
2358
      lvs = node_res.payload
2359
      for lv_name, (_, _, lv_online) in lvs.items():
2360
        inst = nv_dict.pop((node, lv_name), None)
2361
        if (not lv_online and inst is not None
2362
            and inst.name not in res_instances):
2363
          res_instances.append(inst.name)
2364

    
2365
    # any leftover items in nv_dict are missing LVs, let's arrange the
2366
    # data better
2367
    for key, inst in nv_dict.iteritems():
2368
      if inst.name not in res_missing:
2369
        res_missing[inst.name] = []
2370
      res_missing[inst.name].append(key)
2371

    
2372
    return result
2373

    
2374

    
2375
class LURepairDiskSizes(NoHooksLU):
2376
  """Verifies the cluster disks sizes.
2377

2378
  """
2379
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2380
  REQ_BGL = False
2381

    
2382
  def ExpandNames(self):
2383
    if self.op.instances:
2384
      self.wanted_names = []
2385
      for name in self.op.instances:
2386
        full_name = _ExpandInstanceName(self.cfg, name)
2387
        self.wanted_names.append(full_name)
2388
      self.needed_locks = {
2389
        locking.LEVEL_NODE: [],
2390
        locking.LEVEL_INSTANCE: self.wanted_names,
2391
        }
2392
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2393
    else:
2394
      self.wanted_names = None
2395
      self.needed_locks = {
2396
        locking.LEVEL_NODE: locking.ALL_SET,
2397
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2398
        }
2399
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2400

    
2401
  def DeclareLocks(self, level):
2402
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2403
      self._LockInstancesNodes(primary_only=True)
2404

    
2405
  def CheckPrereq(self):
2406
    """Check prerequisites.
2407

2408
    This only checks the optional instance list against the existing names.
2409

2410
    """
2411
    if self.wanted_names is None:
2412
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2413

    
2414
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2415
                             in self.wanted_names]
2416

    
2417
  def _EnsureChildSizes(self, disk):
2418
    """Ensure children of the disk have the needed disk size.
2419

2420
    This is valid mainly for DRBD8 and fixes an issue where the
2421
    children have smaller disk size.
2422

2423
    @param disk: an L{ganeti.objects.Disk} object
2424

2425
    """
2426
    if disk.dev_type == constants.LD_DRBD8:
2427
      assert disk.children, "Empty children for DRBD8?"
2428
      fchild = disk.children[0]
2429
      mismatch = fchild.size < disk.size
2430
      if mismatch:
2431
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2432
                     fchild.size, disk.size)
2433
        fchild.size = disk.size
2434

    
2435
      # and we recurse on this child only, not on the metadev
2436
      return self._EnsureChildSizes(fchild) or mismatch
2437
    else:
2438
      return False
2439

    
2440
  def Exec(self, feedback_fn):
2441
    """Verify the size of cluster disks.
2442

2443
    """
2444
    # TODO: check child disks too
2445
    # TODO: check differences in size between primary/secondary nodes
2446
    per_node_disks = {}
2447
    for instance in self.wanted_instances:
2448
      pnode = instance.primary_node
2449
      if pnode not in per_node_disks:
2450
        per_node_disks[pnode] = []
2451
      for idx, disk in enumerate(instance.disks):
2452
        per_node_disks[pnode].append((instance, idx, disk))
2453

    
2454
    changed = []
2455
    for node, dskl in per_node_disks.items():
2456
      newl = [v[2].Copy() for v in dskl]
2457
      for dsk in newl:
2458
        self.cfg.SetDiskID(dsk, node)
2459
      result = self.rpc.call_blockdev_getsizes(node, newl)
2460
      if result.fail_msg:
2461
        self.LogWarning("Failure in blockdev_getsizes call to node"
2462
                        " %s, ignoring", node)
2463
        continue
2464
      if len(result.data) != len(dskl):
2465
        self.LogWarning("Invalid result from node %s, ignoring node results",
2466
                        node)
2467
        continue
2468
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2469
        if size is None:
2470
          self.LogWarning("Disk %d of instance %s did not return size"
2471
                          " information, ignoring", idx, instance.name)
2472
          continue
2473
        if not isinstance(size, (int, long)):
2474
          self.LogWarning("Disk %d of instance %s did not return valid"
2475
                          " size information, ignoring", idx, instance.name)
2476
          continue
2477
        size = size >> 20
2478
        if size != disk.size:
2479
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2480
                       " correcting: recorded %d, actual %d", idx,
2481
                       instance.name, disk.size, size)
2482
          disk.size = size
2483
          self.cfg.Update(instance, feedback_fn)
2484
          changed.append((instance.name, idx, size))
2485
        if self._EnsureChildSizes(disk):
2486
          self.cfg.Update(instance, feedback_fn)
2487
          changed.append((instance.name, idx, disk.size))
2488
    return changed
2489

    
2490

    
2491
class LURenameCluster(LogicalUnit):
2492
  """Rename the cluster.
2493

2494
  """
2495
  HPATH = "cluster-rename"
2496
  HTYPE = constants.HTYPE_CLUSTER
2497
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2498

    
2499
  def BuildHooksEnv(self):
2500
    """Build hooks env.
2501

2502
    """
2503
    env = {
2504
      "OP_TARGET": self.cfg.GetClusterName(),
2505
      "NEW_NAME": self.op.name,
2506
      }
2507
    mn = self.cfg.GetMasterNode()
2508
    all_nodes = self.cfg.GetNodeList()
2509
    return env, [mn], all_nodes
2510

    
2511
  def CheckPrereq(self):
2512
    """Verify that the passed name is a valid one.
2513

2514
    """
2515
    hostname = netutils.GetHostInfo(self.op.name)
2516

    
2517
    new_name = hostname.name
2518
    self.ip = new_ip = hostname.ip
2519
    old_name = self.cfg.GetClusterName()
2520
    old_ip = self.cfg.GetMasterIP()
2521
    if new_name == old_name and new_ip == old_ip:
2522
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2523
                                 " cluster has changed",
2524
                                 errors.ECODE_INVAL)
2525
    if new_ip != old_ip:
2526
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2527
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2528
                                   " reachable on the network. Aborting." %
2529
                                   new_ip, errors.ECODE_NOTUNIQUE)
2530

    
2531
    self.op.name = new_name
2532

    
2533
  def Exec(self, feedback_fn):
2534
    """Rename the cluster.
2535

2536
    """
2537
    clustername = self.op.name
2538
    ip = self.ip
2539

    
2540
    # shutdown the master IP
2541
    master = self.cfg.GetMasterNode()
2542
    result = self.rpc.call_node_stop_master(master, False)
2543
    result.Raise("Could not disable the master role")
2544

    
2545
    try:
2546
      cluster = self.cfg.GetClusterInfo()
2547
      cluster.cluster_name = clustername
2548
      cluster.master_ip = ip
2549
      self.cfg.Update(cluster, feedback_fn)
2550

    
2551
      # update the known hosts file
2552
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2553
      node_list = self.cfg.GetNodeList()
2554
      try:
2555
        node_list.remove(master)
2556
      except ValueError:
2557
        pass
2558
      result = self.rpc.call_upload_file(node_list,
2559
                                         constants.SSH_KNOWN_HOSTS_FILE)
2560
      for to_node, to_result in result.iteritems():
2561
        msg = to_result.fail_msg
2562
        if msg:
2563
          msg = ("Copy of file %s to node %s failed: %s" %
2564
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2565
          self.proc.LogWarning(msg)
2566

    
2567
    finally:
2568
      result = self.rpc.call_node_start_master(master, False, False)
2569
      msg = result.fail_msg
2570
      if msg:
2571
        self.LogWarning("Could not re-enable the master role on"
2572
                        " the master, please restart manually: %s", msg)
2573

    
2574

    
2575
class LUSetClusterParams(LogicalUnit):
2576
  """Change the parameters of the cluster.
2577

2578
  """
2579
  HPATH = "cluster-modify"
2580
  HTYPE = constants.HTYPE_CLUSTER
2581
  _OP_PARAMS = [
2582
    ("vg_name", None, _TMaybeString),
2583
    ("enabled_hypervisors", None,
2584
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2585
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2586
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2587
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2588
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2589
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2590
    ("uid_pool", None, _NoType),
2591
    ("add_uids", None, _NoType),
2592
    ("remove_uids", None, _NoType),
2593
    ("maintain_node_health", None, _TMaybeBool),
2594
    ("nicparams", None, _TOr(_TDict, _TNone)),
2595
    ("drbd_helper", None, _TOr(_TString, _TNone)),
2596
    ("default_iallocator", None, _TMaybeString),
2597
    ]
2598
  REQ_BGL = False
2599

    
2600
  def CheckArguments(self):
2601
    """Check parameters
2602

2603
    """
2604
    if self.op.uid_pool:
2605
      uidpool.CheckUidPool(self.op.uid_pool)
2606

    
2607
    if self.op.add_uids:
2608
      uidpool.CheckUidPool(self.op.add_uids)
2609

    
2610
    if self.op.remove_uids:
2611
      uidpool.CheckUidPool(self.op.remove_uids)
2612

    
2613
  def ExpandNames(self):
2614
    # FIXME: in the future maybe other cluster params won't require checking on
2615
    # all nodes to be modified.
2616
    self.needed_locks = {
2617
      locking.LEVEL_NODE: locking.ALL_SET,
2618
    }
2619
    self.share_locks[locking.LEVEL_NODE] = 1
2620

    
2621
  def BuildHooksEnv(self):
2622
    """Build hooks env.
2623

2624
    """
2625
    env = {
2626
      "OP_TARGET": self.cfg.GetClusterName(),
2627
      "NEW_VG_NAME": self.op.vg_name,
2628
      }
2629
    mn = self.cfg.GetMasterNode()
2630
    return env, [mn], [mn]
2631

    
2632
  def CheckPrereq(self):
2633
    """Check prerequisites.
2634

2635
    This checks whether the given params don't conflict and
2636
    if the given volume group is valid.
2637

2638
    """
2639
    if self.op.vg_name is not None and not self.op.vg_name:
2640
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2641
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2642
                                   " instances exist", errors.ECODE_INVAL)
2643

    
2644
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2645
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2646
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2647
                                   " drbd-based instances exist",
2648
                                   errors.ECODE_INVAL)
2649

    
2650
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2651

    
2652
    # if vg_name not None, checks given volume group on all nodes
2653
    if self.op.vg_name:
2654
      vglist = self.rpc.call_vg_list(node_list)
2655
      for node in node_list:
2656
        msg = vglist[node].fail_msg
2657
        if msg:
2658
          # ignoring down node
2659
          self.LogWarning("Error while gathering data on node %s"
2660
                          " (ignoring node): %s", node, msg)
2661
          continue
2662
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2663
                                              self.op.vg_name,
2664
                                              constants.MIN_VG_SIZE)
2665
        if vgstatus:
2666
          raise errors.OpPrereqError("Error on node '%s': %s" %
2667
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2668

    
2669
    if self.op.drbd_helper:
2670
      # checks given drbd helper on all nodes
2671
      helpers = self.rpc.call_drbd_helper(node_list)
2672
      for node in node_list:
2673
        ninfo = self.cfg.GetNodeInfo(node)
2674
        if ninfo.offline:
2675
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2676
          continue
2677
        msg = helpers[node].fail_msg
2678
        if msg:
2679
          raise errors.OpPrereqError("Error checking drbd helper on node"
2680
                                     " '%s': %s" % (node, msg),
2681
                                     errors.ECODE_ENVIRON)
2682
        node_helper = helpers[node].payload
2683
        if node_helper != self.op.drbd_helper:
2684
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2685
                                     (node, node_helper), errors.ECODE_ENVIRON)
2686

    
2687
    self.cluster = cluster = self.cfg.GetClusterInfo()
2688
    # validate params changes
2689
    if self.op.beparams:
2690
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2691
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2692

    
2693
    if self.op.nicparams:
2694
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2695
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2696
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2697
      nic_errors = []
2698

    
2699
      # check all instances for consistency
2700
      for instance in self.cfg.GetAllInstancesInfo().values():
2701
        for nic_idx, nic in enumerate(instance.nics):
2702
          params_copy = copy.deepcopy(nic.nicparams)
2703
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2704

    
2705
          # check parameter syntax
2706
          try:
2707
            objects.NIC.CheckParameterSyntax(params_filled)
2708
          except errors.ConfigurationError, err:
2709
            nic_errors.append("Instance %s, nic/%d: %s" %
2710
                              (instance.name, nic_idx, err))
2711

    
2712
          # if we're moving instances to routed, check that they have an ip
2713
          target_mode = params_filled[constants.NIC_MODE]
2714
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2715
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2716
                              (instance.name, nic_idx))
2717
      if nic_errors:
2718
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2719
                                   "\n".join(nic_errors))
2720

    
2721
    # hypervisor list/parameters
2722
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2723
    if self.op.hvparams:
2724
      for hv_name, hv_dict in self.op.hvparams.items():
2725
        if hv_name not in self.new_hvparams:
2726
          self.new_hvparams[hv_name] = hv_dict
2727
        else:
2728
          self.new_hvparams[hv_name].update(hv_dict)
2729

    
2730
    # os hypervisor parameters
2731
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2732
    if self.op.os_hvp:
2733
      for os_name, hvs in self.op.os_hvp.items():
2734
        if os_name not in self.new_os_hvp:
2735
          self.new_os_hvp[os_name] = hvs
2736
        else:
2737
          for hv_name, hv_dict in hvs.items():
2738
            if hv_name not in self.new_os_hvp[os_name]:
2739
              self.new_os_hvp[os_name][hv_name] = hv_dict
2740
            else:
2741
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2742

    
2743
    # os parameters
2744
    self.new_osp = objects.FillDict(cluster.osparams, {})
2745
    if self.op.osparams:
2746
      for os_name, osp in self.op.osparams.items():
2747
        if os_name not in self.new_osp:
2748
          self.new_osp[os_name] = {}
2749

    
2750
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2751
                                                  use_none=True)
2752

    
2753
        if not self.new_osp[os_name]:
2754
          # we removed all parameters
2755
          del self.new_osp[os_name]
2756
        else:
2757
          # check the parameter validity (remote check)
2758
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2759
                         os_name, self.new_osp[os_name])
2760

    
2761
    # changes to the hypervisor list
2762
    if self.op.enabled_hypervisors is not None:
2763
      self.hv_list = self.op.enabled_hypervisors
2764
      for hv in self.hv_list:
2765
        # if the hypervisor doesn't already exist in the cluster
2766
        # hvparams, we initialize it to empty, and then (in both
2767
        # cases) we make sure to fill the defaults, as we might not
2768
        # have a complete defaults list if the hypervisor wasn't
2769
        # enabled before
2770
        if hv not in new_hvp:
2771
          new_hvp[hv] = {}
2772
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2773
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2774
    else:
2775
      self.hv_list = cluster.enabled_hypervisors
2776

    
2777
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2778
      # either the enabled list has changed, or the parameters have, validate
2779
      for hv_name, hv_params in self.new_hvparams.items():
2780
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2781
            (self.op.enabled_hypervisors and
2782
             hv_name in self.op.enabled_hypervisors)):
2783
          # either this is a new hypervisor, or its parameters have changed
2784
          hv_class = hypervisor.GetHypervisor(hv_name)
2785
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2786
          hv_class.CheckParameterSyntax(hv_params)
2787
          _CheckHVParams(self, node_list, hv_name, hv_params)
2788

    
2789
    if self.op.os_hvp:
2790
      # no need to check any newly-enabled hypervisors, since the
2791
      # defaults have already been checked in the above code-block
2792
      for os_name, os_hvp in self.new_os_hvp.items():
2793
        for hv_name, hv_params in os_hvp.items():
2794
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2795
          # we need to fill in the new os_hvp on top of the actual hv_p
2796
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2797
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2798
          hv_class = hypervisor.GetHypervisor(hv_name)
2799
          hv_class.CheckParameterSyntax(new_osp)
2800
          _CheckHVParams(self, node_list, hv_name, new_osp)
2801

    
2802
    if self.op.default_iallocator:
2803
      alloc_script = utils.FindFile(self.op.default_iallocator,
2804
                                    constants.IALLOCATOR_SEARCH_PATH,
2805
                                    os.path.isfile)
2806
      if alloc_script is None:
2807
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2808
                                   " specified" % self.op.default_iallocator,
2809
                                   errors.ECODE_INVAL)
2810

    
2811
  def Exec(self, feedback_fn):
2812
    """Change the parameters of the cluster.
2813

2814
    """
2815
    if self.op.vg_name is not None:
2816
      new_volume = self.op.vg_name
2817
      if not new_volume:
2818
        new_volume = None
2819
      if new_volume != self.cfg.GetVGName():
2820
        self.cfg.SetVGName(new_volume)
2821
      else:
2822
        feedback_fn("Cluster LVM configuration already in desired"
2823
                    " state, not changing")
2824
    if self.op.drbd_helper is not None:
2825
      new_helper = self.op.drbd_helper
2826
      if not new_helper:
2827
        new_helper = None
2828
      if new_helper != self.cfg.GetDRBDHelper():
2829
        self.cfg.SetDRBDHelper(new_helper)
2830
      else:
2831
        feedback_fn("Cluster DRBD helper already in desired state,"
2832
                    " not changing")
2833
    if self.op.hvparams:
2834
      self.cluster.hvparams = self.new_hvparams
2835
    if self.op.os_hvp:
2836
      self.cluster.os_hvp = self.new_os_hvp
2837
    if self.op.enabled_hypervisors is not None:
2838
      self.cluster.hvparams = self.new_hvparams
2839
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2840
    if self.op.beparams:
2841
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2842
    if self.op.nicparams:
2843
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2844
    if self.op.osparams:
2845
      self.cluster.osparams = self.new_osp
2846

    
2847
    if self.op.candidate_pool_size is not None:
2848
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2849
      # we need to update the pool size here, otherwise the save will fail
2850
      _AdjustCandidatePool(self, [])
2851

    
2852
    if self.op.maintain_node_health is not None:
2853
      self.cluster.maintain_node_health = self.op.maintain_node_health
2854

    
2855
    if self.op.add_uids is not None:
2856
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2857

    
2858
    if self.op.remove_uids is not None:
2859
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2860

    
2861
    if self.op.uid_pool is not None:
2862
      self.cluster.uid_pool = self.op.uid_pool
2863

    
2864
    if self.op.default_iallocator is not None:
2865
      self.cluster.default_iallocator = self.op.default_iallocator
2866

    
2867
    self.cfg.Update(self.cluster, feedback_fn)
2868

    
2869

    
2870
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2871
  """Distribute additional files which are part of the cluster configuration.
2872

2873
  ConfigWriter takes care of distributing the config and ssconf files, but
2874
  there are more files which should be distributed to all nodes. This function
2875
  makes sure those are copied.
2876

2877
  @param lu: calling logical unit
2878
  @param additional_nodes: list of nodes not in the config to distribute to
2879

2880
  """
2881
  # 1. Gather target nodes
2882
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2883
  dist_nodes = lu.cfg.GetOnlineNodeList()
2884
  if additional_nodes is not None:
2885
    dist_nodes.extend(additional_nodes)
2886
  if myself.name in dist_nodes:
2887
    dist_nodes.remove(myself.name)
2888

    
2889
  # 2. Gather files to distribute
2890
  dist_files = set([constants.ETC_HOSTS,
2891
                    constants.SSH_KNOWN_HOSTS_FILE,
2892
                    constants.RAPI_CERT_FILE,
2893
                    constants.RAPI_USERS_FILE,
2894
                    constants.CONFD_HMAC_KEY,
2895
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2896
                   ])
2897

    
2898
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2899
  for hv_name in enabled_hypervisors:
2900
    hv_class = hypervisor.GetHypervisor(hv_name)
2901
    dist_files.update(hv_class.GetAncillaryFiles())
2902

    
2903
  # 3. Perform the files upload
2904
  for fname in dist_files:
2905
    if os.path.exists(fname):
2906
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2907
      for to_node, to_result in result.items():
2908
        msg = to_result.fail_msg
2909
        if msg:
2910
          msg = ("Copy of file %s to node %s failed: %s" %
2911
                 (fname, to_node, msg))
2912
          lu.proc.LogWarning(msg)
2913

    
2914

    
2915
class LURedistributeConfig(NoHooksLU):
2916
  """Force the redistribution of cluster configuration.
2917

2918
  This is a very simple LU.
2919

2920
  """
2921
  REQ_BGL = False
2922

    
2923
  def ExpandNames(self):
2924
    self.needed_locks = {
2925
      locking.LEVEL_NODE: locking.ALL_SET,
2926
    }
2927
    self.share_locks[locking.LEVEL_NODE] = 1
2928

    
2929
  def Exec(self, feedback_fn):
2930
    """Redistribute the configuration.
2931

2932
    """
2933
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2934
    _RedistributeAncillaryFiles(self)
2935

    
2936

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

2940
  """
2941
  if not instance.disks or disks is not None and not disks:
2942
    return True
2943

    
2944
  disks = _ExpandCheckDisks(instance, disks)
2945

    
2946
  if not oneshot:
2947
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2948

    
2949
  node = instance.primary_node
2950

    
2951
  for dev in disks:
2952
    lu.cfg.SetDiskID(dev, node)
2953

    
2954
  # TODO: Convert to utils.Retry
2955

    
2956
  retries = 0
2957
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2958
  while True:
2959
    max_time = 0
2960
    done = True
2961
    cumul_degraded = False
2962
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2963
    msg = rstats.fail_msg
2964
    if msg:
2965
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2966
      retries += 1
2967
      if retries >= 10:
2968
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2969
                                 " aborting." % node)
2970
      time.sleep(6)
2971
      continue
2972
    rstats = rstats.payload
2973
    retries = 0
2974
    for i, mstat in enumerate(rstats):
2975
      if mstat is None:
2976
        lu.LogWarning("Can't compute data for node %s/%s",
2977
                           node, disks[i].iv_name)
2978
        continue
2979

    
2980
      cumul_degraded = (cumul_degraded or
2981
                        (mstat.is_degraded and mstat.sync_percent is None))
2982
      if mstat.sync_percent is not None:
2983
        done = False
2984
        if mstat.estimated_time is not None:
2985
          rem_time = ("%s remaining (estimated)" %
2986
                      utils.FormatSeconds(mstat.estimated_time))
2987
          max_time = mstat.estimated_time
2988
        else:
2989
          rem_time = "no time estimate"
2990
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2991
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2992

    
2993
    # if we're done but degraded, let's do a few small retries, to
2994
    # make sure we see a stable and not transient situation; therefore
2995
    # we force restart of the loop
2996
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2997
      logging.info("Degraded disks found, %d retries left", degr_retries)
2998
      degr_retries -= 1
2999
      time.sleep(1)
3000
      continue
3001

    
3002
    if done or oneshot:
3003
      break
3004

    
3005
    time.sleep(min(60, max_time))
3006

    
3007
  if done:
3008
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3009
  return not cumul_degraded
3010

    
3011

    
3012
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3013
  """Check that mirrors are not degraded.
3014

3015
  The ldisk parameter, if True, will change the test from the
3016
  is_degraded attribute (which represents overall non-ok status for
3017
  the device(s)) to the ldisk (representing the local storage status).
3018

3019
  """
3020
  lu.cfg.SetDiskID(dev, node)
3021

    
3022
  result = True
3023

    
3024
  if on_primary or dev.AssembleOnSecondary():
3025
    rstats = lu.rpc.call_blockdev_find(node, dev)
3026
    msg = rstats.fail_msg
3027
    if msg:
3028
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3029
      result = False
3030
    elif not rstats.payload:
3031
      lu.LogWarning("Can't find disk on node %s", node)
3032
      result = False
3033
    else:
3034
      if ldisk:
3035
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3036
      else:
3037
        result = result and not rstats.payload.is_degraded
3038

    
3039
  if dev.children:
3040
    for child in dev.children:
3041
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3042

    
3043
  return result
3044

    
3045

    
3046
class LUDiagnoseOS(NoHooksLU):
3047
  """Logical unit for OS diagnose/query.
3048

3049
  """
3050
  _OP_PARAMS = [
3051
    _POutputFields,
3052
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3053
    ]
3054
  REQ_BGL = False
3055
  _FIELDS_STATIC = utils.FieldSet()
3056
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3057
                                   "parameters", "api_versions")
3058

    
3059
  def CheckArguments(self):
3060
    if self.op.names:
3061
      raise errors.OpPrereqError("Selective OS query not supported",
3062
                                 errors.ECODE_INVAL)
3063

    
3064
    _CheckOutputFields(static=self._FIELDS_STATIC,
3065
                       dynamic=self._FIELDS_DYNAMIC,
3066
                       selected=self.op.output_fields)
3067

    
3068
  def ExpandNames(self):
3069
    # Lock all nodes, in shared mode
3070
    # Temporary removal of locks, should be reverted later
3071
    # TODO: reintroduce locks when they are lighter-weight
3072
    self.needed_locks = {}
3073
    #self.share_locks[locking.LEVEL_NODE] = 1
3074
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3075

    
3076
  @staticmethod
3077
  def _DiagnoseByOS(rlist):
3078
    """Remaps a per-node return list into an a per-os per-node dictionary
3079

3080
    @param rlist: a map with node names as keys and OS objects as values
3081

3082
    @rtype: dict
3083
    @return: a dictionary with osnames as keys and as value another
3084
        map, with nodes as keys and tuples of (path, status, diagnose,
3085
        variants, parameters, api_versions) as values, eg::
3086

3087
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3088
                                     (/srv/..., False, "invalid api")],
3089
                           "node2": [(/srv/..., True, "", [], [])]}
3090
          }
3091

3092
    """
3093
    all_os = {}
3094
    # we build here the list of nodes that didn't fail the RPC (at RPC
3095
    # level), so that nodes with a non-responding node daemon don't
3096
    # make all OSes invalid
3097
    good_nodes = [node_name for node_name in rlist
3098
                  if not rlist[node_name].fail_msg]
3099
    for node_name, nr in rlist.items():
3100
      if nr.fail_msg or not nr.payload:
3101
        continue
3102
      for (name, path, status, diagnose, variants,
3103
           params, api_versions) in nr.payload:
3104
        if name not in all_os:
3105
          # build a list of nodes for this os containing empty lists
3106
          # for each node in node_list
3107
          all_os[name] = {}
3108
          for nname in good_nodes:
3109
            all_os[name][nname] = []
3110
        # convert params from [name, help] to (name, help)
3111
        params = [tuple(v) for v in params]
3112
        all_os[name][node_name].append((path, status, diagnose,
3113
                                        variants, params, api_versions))
3114
    return all_os
3115

    
3116
  def Exec(self, feedback_fn):
3117
    """Compute the list of OSes.
3118

3119
    """
3120
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3121
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3122
    pol = self._DiagnoseByOS(node_data)
3123
    output = []
3124

    
3125
    for os_name, os_data in pol.items():
3126
      row = []
3127
      valid = True
3128
      (variants, params, api_versions) = null_state = (set(), set(), set())
3129
      for idx, osl in enumerate(os_data.values()):
3130
        valid = bool(valid and osl and osl[0][1])
3131
        if not valid:
3132
          (variants, params, api_versions) = null_state
3133
          break
3134
        node_variants, node_params, node_api = osl[0][3:6]
3135
        if idx == 0: # first entry
3136
          variants = set(node_variants)
3137
          params = set(node_params)
3138
          api_versions = set(node_api)
3139
        else: # keep consistency
3140
          variants.intersection_update(node_variants)
3141
          params.intersection_update(node_params)
3142
          api_versions.intersection_update(node_api)
3143

    
3144
      for field in self.op.output_fields:
3145
        if field == "name":
3146
          val = os_name
3147
        elif field == "valid":
3148
          val = valid
3149
        elif field == "node_status":
3150
          # this is just a copy of the dict
3151
          val = {}
3152
          for node_name, nos_list in os_data.items():
3153
            val[node_name] = nos_list
3154
        elif field == "variants":
3155
          val = list(variants)
3156
        elif field == "parameters":
3157
          val = list(params)
3158
        elif field == "api_versions":
3159
          val = list(api_versions)
3160
        else:
3161
          raise errors.ParameterError(field)
3162
        row.append(val)
3163
      output.append(row)
3164

    
3165
    return output
3166

    
3167

    
3168
class LURemoveNode(LogicalUnit):
3169
  """Logical unit for removing a node.
3170

3171
  """
3172
  HPATH = "node-remove"
3173
  HTYPE = constants.HTYPE_NODE
3174
  _OP_PARAMS = [
3175
    _PNodeName,
3176
    ]
3177

    
3178
  def BuildHooksEnv(self):
3179
    """Build hooks env.
3180

3181
    This doesn't run on the target node in the pre phase as a failed
3182
    node would then be impossible to remove.
3183

3184
    """
3185
    env = {
3186
      "OP_TARGET": self.op.node_name,
3187
      "NODE_NAME": self.op.node_name,
3188
      }
3189
    all_nodes = self.cfg.GetNodeList()
3190
    try:
3191
      all_nodes.remove(self.op.node_name)
3192
    except ValueError:
3193
      logging.warning("Node %s which is about to be removed not found"
3194
                      " in the all nodes list", self.op.node_name)
3195
    return env, all_nodes, all_nodes
3196

    
3197
  def CheckPrereq(self):
3198
    """Check prerequisites.
3199

3200
    This checks:
3201
     - the node exists in the configuration
3202
     - it does not have primary or secondary instances
3203
     - it's not the master
3204

3205
    Any errors are signaled by raising errors.OpPrereqError.
3206

3207
    """
3208
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3209
    node = self.cfg.GetNodeInfo(self.op.node_name)
3210
    assert node is not None
3211

    
3212
    instance_list = self.cfg.GetInstanceList()
3213

    
3214
    masternode = self.cfg.GetMasterNode()
3215
    if node.name == masternode:
3216
      raise errors.OpPrereqError("Node is the master node,"
3217
                                 " you need to failover first.",
3218
                                 errors.ECODE_INVAL)
3219

    
3220
    for instance_name in instance_list:
3221
      instance = self.cfg.GetInstanceInfo(instance_name)
3222
      if node.name in instance.all_nodes:
3223
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3224
                                   " please remove first." % instance_name,
3225
                                   errors.ECODE_INVAL)
3226
    self.op.node_name = node.name
3227
    self.node = node
3228

    
3229
  def Exec(self, feedback_fn):
3230
    """Removes the node from the cluster.
3231

3232
    """
3233
    node = self.node
3234
    logging.info("Stopping the node daemon and removing configs from node %s",
3235
                 node.name)
3236

    
3237
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3238

    
3239
    # Promote nodes to master candidate as needed
3240
    _AdjustCandidatePool(self, exceptions=[node.name])
3241
    self.context.RemoveNode(node.name)
3242

    
3243
    # Run post hooks on the node before it's removed
3244
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3245
    try:
3246
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3247
    except:
3248
      # pylint: disable-msg=W0702
3249
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3250

    
3251
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3252
    msg = result.fail_msg
3253
    if msg:
3254
      self.LogWarning("Errors encountered on the remote node while leaving"
3255
                      " the cluster: %s", msg)
3256

    
3257
    # Remove node from our /etc/hosts
3258
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3259
      # FIXME: this should be done via an rpc call to node daemon
3260
      utils.RemoveHostFromEtcHosts(node.name)
3261
      _RedistributeAncillaryFiles(self)
3262

    
3263

    
3264
class LUQueryNodes(NoHooksLU):
3265
  """Logical unit for querying nodes.
3266

3267
  """
3268
  # pylint: disable-msg=W0142
3269
  _OP_PARAMS = [
3270
    _POutputFields,
3271
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3272
    ("use_locking", False, _TBool),
3273
    ]
3274
  REQ_BGL = False
3275

    
3276
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3277
                    "master_candidate", "offline", "drained"]
3278

    
3279
  _FIELDS_DYNAMIC = utils.FieldSet(
3280
    "dtotal", "dfree",
3281
    "mtotal", "mnode", "mfree",
3282
    "bootid",
3283
    "ctotal", "cnodes", "csockets",
3284
    )
3285

    
3286
  _FIELDS_STATIC = utils.FieldSet(*[
3287
    "pinst_cnt", "sinst_cnt",
3288
    "pinst_list", "sinst_list",
3289
    "pip", "sip", "tags",
3290
    "master",
3291
    "role"] + _SIMPLE_FIELDS
3292
    )
3293

    
3294
  def CheckArguments(self):
3295
    _CheckOutputFields(static=self._FIELDS_STATIC,
3296
                       dynamic=self._FIELDS_DYNAMIC,
3297
                       selected=self.op.output_fields)
3298

    
3299
  def ExpandNames(self):
3300
    self.needed_locks = {}
3301
    self.share_locks[locking.LEVEL_NODE] = 1
3302

    
3303
    if self.op.names:
3304
      self.wanted = _GetWantedNodes(self, self.op.names)
3305
    else:
3306
      self.wanted = locking.ALL_SET
3307

    
3308
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3309
    self.do_locking = self.do_node_query and self.op.use_locking
3310
    if self.do_locking:
3311
      # if we don't request only static fields, we need to lock the nodes
3312
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3313

    
3314
  def Exec(self, feedback_fn):
3315
    """Computes the list of nodes and their attributes.
3316

3317
    """
3318
    all_info = self.cfg.GetAllNodesInfo()
3319
    if self.do_locking:
3320
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3321
    elif self.wanted != locking.ALL_SET:
3322
      nodenames = self.wanted
3323
      missing = set(nodenames).difference(all_info.keys())
3324
      if missing:
3325
        raise errors.OpExecError(
3326
          "Some nodes were removed before retrieving their data: %s" % missing)
3327
    else:
3328
      nodenames = all_info.keys()
3329

    
3330
    nodenames = utils.NiceSort(nodenames)
3331
    nodelist = [all_info[name] for name in nodenames]
3332

    
3333
    # begin data gathering
3334

    
3335
    if self.do_node_query:
3336
      live_data = {}
3337
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3338
                                          self.cfg.GetHypervisorType())
3339
      for name in nodenames:
3340
        nodeinfo = node_data[name]
3341
        if not nodeinfo.fail_msg and nodeinfo.payload:
3342
          nodeinfo = nodeinfo.payload
3343
          fn = utils.TryConvert
3344
          live_data[name] = {
3345
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3346
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3347
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3348
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3349
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3350
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3351
            "bootid": nodeinfo.get('bootid', None),
3352
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3353
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3354
            }
3355
        else:
3356
          live_data[name] = {}
3357
    else:
3358
      live_data = dict.fromkeys(nodenames, {})
3359

    
3360
    node_to_primary = dict([(name, set()) for name in nodenames])
3361
    node_to_secondary = dict([(name, set()) for name in nodenames])
3362

    
3363
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3364
                             "sinst_cnt", "sinst_list"))
3365
    if inst_fields & frozenset(self.op.output_fields):
3366
      inst_data = self.cfg.GetAllInstancesInfo()
3367

    
3368
      for inst in inst_data.values():
3369
        if inst.primary_node in node_to_primary:
3370
          node_to_primary[inst.primary_node].add(inst.name)
3371
        for secnode in inst.secondary_nodes:
3372
          if secnode in node_to_secondary:
3373
            node_to_secondary[secnode].add(inst.name)
3374

    
3375
    master_node = self.cfg.GetMasterNode()
3376

    
3377
    # end data gathering
3378

    
3379
    output = []
3380
    for node in nodelist:
3381
      node_output = []
3382
      for field in self.op.output_fields:
3383
        if field in self._SIMPLE_FIELDS:
3384
          val = getattr(node, field)
3385
        elif field == "pinst_list":
3386
          val = list(node_to_primary[node.name])
3387
        elif field == "sinst_list":
3388
          val = list(node_to_secondary[node.name])
3389
        elif field == "pinst_cnt":
3390
          val = len(node_to_primary[node.name])
3391
        elif field == "sinst_cnt":
3392
          val = len(node_to_secondary[node.name])
3393
        elif field == "pip":
3394
          val = node.primary_ip
3395
        elif field == "sip":
3396
          val = node.secondary_ip
3397
        elif field == "tags":
3398
          val = list(node.GetTags())
3399
        elif field == "master":
3400
          val = node.name == master_node
3401
        elif self._FIELDS_DYNAMIC.Matches(field):
3402
          val = live_data[node.name].get(field, None)
3403
        elif field == "role":
3404
          if node.name == master_node:
3405
            val = "M"
3406
          elif node.master_candidate:
3407
            val = "C"
3408
          elif node.drained:
3409
            val = "D"
3410
          elif node.offline:
3411
            val = "O"
3412
          else:
3413
            val = "R"
3414
        else:
3415
          raise errors.ParameterError(field)
3416
        node_output.append(val)
3417
      output.append(node_output)
3418

    
3419
    return output
3420

    
3421

    
3422
class LUQueryNodeVolumes(NoHooksLU):
3423
  """Logical unit for getting volumes on node(s).
3424

3425
  """
3426
  _OP_PARAMS = [
3427
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3428
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3429
    ]
3430
  REQ_BGL = False
3431
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3432
  _FIELDS_STATIC = utils.FieldSet("node")
3433

    
3434
  def CheckArguments(self):
3435
    _CheckOutputFields(static=self._FIELDS_STATIC,
3436
                       dynamic=self._FIELDS_DYNAMIC,
3437
                       selected=self.op.output_fields)
3438

    
3439
  def ExpandNames(self):
3440
    self.needed_locks = {}
3441
    self.share_locks[locking.LEVEL_NODE] = 1
3442
    if not self.op.nodes:
3443
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3444
    else:
3445
      self.needed_locks[locking.LEVEL_NODE] = \
3446
        _GetWantedNodes(self, self.op.nodes)
3447

    
3448
  def Exec(self, feedback_fn):
3449
    """Computes the list of nodes and their attributes.
3450

3451
    """
3452
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3453
    volumes = self.rpc.call_node_volumes(nodenames)
3454

    
3455
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3456
             in self.cfg.GetInstanceList()]
3457

    
3458
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3459

    
3460
    output = []
3461
    for node in nodenames:
3462
      nresult = volumes[node]
3463
      if nresult.offline:
3464
        continue
3465
      msg = nresult.fail_msg
3466
      if msg:
3467
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3468
        continue
3469

    
3470
      node_vols = nresult.payload[:]
3471
      node_vols.sort(key=lambda vol: vol['dev'])
3472

    
3473
      for vol in node_vols:
3474
        node_output = []
3475
        for field in self.op.output_fields:
3476
          if field == "node":
3477
            val = node
3478
          elif field == "phys":
3479
            val = vol['dev']
3480
          elif field == "vg":
3481
            val = vol['vg']
3482
          elif field == "name":
3483
            val = vol['name']
3484
          elif field == "size":
3485
            val = int(float(vol['size']))
3486
          elif field == "instance":
3487
            for inst in ilist:
3488
              if node not in lv_by_node[inst]:
3489
                continue
3490
              if vol['name'] in lv_by_node[inst][node]:
3491
                val = inst.name
3492
                break
3493
            else:
3494
              val = '-'
3495
          else:
3496
            raise errors.ParameterError(field)
3497
          node_output.append(str(val))
3498

    
3499
        output.append(node_output)
3500

    
3501
    return output
3502

    
3503

    
3504
class LUQueryNodeStorage(NoHooksLU):
3505
  """Logical unit for getting information on storage units on node(s).
3506

3507
  """
3508
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3509
  _OP_PARAMS = [
3510
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3511
    ("storage_type", _NoDefault, _CheckStorageType),
3512
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3513
    ("name", None, _TMaybeString),
3514
    ]
3515
  REQ_BGL = False
3516

    
3517
  def CheckArguments(self):
3518
    _CheckOutputFields(static=self._FIELDS_STATIC,
3519
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3520
                       selected=self.op.output_fields)
3521

    
3522
  def ExpandNames(self):
3523
    self.needed_locks = {}
3524
    self.share_locks[locking.LEVEL_NODE] = 1
3525

    
3526
    if self.op.nodes:
3527
      self.needed_locks[locking.LEVEL_NODE] = \
3528
        _GetWantedNodes(self, self.op.nodes)
3529
    else:
3530
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3531

    
3532
  def Exec(self, feedback_fn):
3533
    """Computes the list of nodes and their attributes.
3534

3535
    """
3536
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3537

    
3538
    # Always get name to sort by
3539
    if constants.SF_NAME in self.op.output_fields:
3540
      fields = self.op.output_fields[:]
3541
    else:
3542
      fields = [constants.SF_NAME] + self.op.output_fields
3543

    
3544
    # Never ask for node or type as it's only known to the LU
3545
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3546
      while extra in fields:
3547
        fields.remove(extra)
3548

    
3549
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3550
    name_idx = field_idx[constants.SF_NAME]
3551

    
3552
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3553
    data = self.rpc.call_storage_list(self.nodes,
3554
                                      self.op.storage_type, st_args,
3555
                                      self.op.name, fields)
3556

    
3557
    result = []
3558

    
3559
    for node in utils.NiceSort(self.nodes):
3560
      nresult = data[node]
3561
      if nresult.offline:
3562
        continue
3563

    
3564
      msg = nresult.fail_msg
3565
      if msg:
3566
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3567
        continue
3568

    
3569
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3570

    
3571
      for name in utils.NiceSort(rows.keys()):
3572
        row = rows[name]
3573

    
3574
        out = []
3575

    
3576
        for field in self.op.output_fields:
3577
          if field == constants.SF_NODE:
3578
            val = node
3579
          elif field == constants.SF_TYPE:
3580
            val = self.op.storage_type
3581
          elif field in field_idx:
3582
            val = row[field_idx[field]]
3583
          else:
3584
            raise errors.ParameterError(field)
3585

    
3586
          out.append(val)
3587

    
3588
        result.append(out)
3589

    
3590
    return result
3591

    
3592

    
3593
class LUModifyNodeStorage(NoHooksLU):
3594
  """Logical unit for modifying a storage volume on a node.
3595

3596
  """
3597
  _OP_PARAMS = [
3598
    _PNodeName,
3599
    ("storage_type", _NoDefault, _CheckStorageType),
3600
    ("name", _NoDefault, _TNonEmptyString),
3601
    ("changes", _NoDefault, _TDict),
3602
    ]
3603
  REQ_BGL = False
3604

    
3605
  def CheckArguments(self):
3606
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3607

    
3608
    storage_type = self.op.storage_type
3609

    
3610
    try:
3611
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3612
    except KeyError:
3613
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3614
                                 " modified" % storage_type,
3615
                                 errors.ECODE_INVAL)
3616

    
3617
    diff = set(self.op.changes.keys()) - modifiable
3618
    if diff:
3619
      raise errors.OpPrereqError("The following fields can not be modified for"
3620
                                 " storage units of type '%s': %r" %
3621
                                 (storage_type, list(diff)),
3622
                                 errors.ECODE_INVAL)
3623

    
3624
  def ExpandNames(self):
3625
    self.needed_locks = {
3626
      locking.LEVEL_NODE: self.op.node_name,
3627
      }
3628

    
3629
  def Exec(self, feedback_fn):
3630
    """Computes the list of nodes and their attributes.
3631

3632
    """
3633
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3634
    result = self.rpc.call_storage_modify(self.op.node_name,
3635
                                          self.op.storage_type, st_args,
3636
                                          self.op.name, self.op.changes)
3637
    result.Raise("Failed to modify storage unit '%s' on %s" %
3638
                 (self.op.name, self.op.node_name))
3639

    
3640

    
3641
class LUAddNode(LogicalUnit):
3642
  """Logical unit for adding node to the cluster.
3643

3644
  """
3645
  HPATH = "node-add"
3646
  HTYPE = constants.HTYPE_NODE
3647
  _OP_PARAMS = [
3648
    _PNodeName,
3649
    ("primary_ip", None, _NoType),
3650
    ("secondary_ip", None, _TMaybeString),
3651
    ("readd", False, _TBool),
3652
    ]
3653

    
3654
  def CheckArguments(self):
3655
    # validate/normalize the node name
3656
    self.op.node_name = netutils.HostInfo.NormalizeName(self.op.node_name)
3657

    
3658
  def BuildHooksEnv(self):
3659
    """Build hooks env.
3660

3661
    This will run on all nodes before, and on all nodes + the new node after.
3662

3663
    """
3664
    env = {
3665
      "OP_TARGET": self.op.node_name,
3666
      "NODE_NAME": self.op.node_name,
3667
      "NODE_PIP": self.op.primary_ip,
3668
      "NODE_SIP": self.op.secondary_ip,
3669
      }
3670
    nodes_0 = self.cfg.GetNodeList()
3671
    nodes_1 = nodes_0 + [self.op.node_name, ]
3672
    return env, nodes_0, nodes_1
3673

    
3674
  def CheckPrereq(self):
3675
    """Check prerequisites.
3676

3677
    This checks:
3678
     - the new node is not already in the config
3679
     - it is resolvable
3680
     - its parameters (single/dual homed) matches the cluster
3681

3682
    Any errors are signaled by raising errors.OpPrereqError.
3683

3684
    """
3685
    node_name = self.op.node_name
3686
    cfg = self.cfg
3687

    
3688
    dns_data = netutils.GetHostInfo(node_name)
3689

    
3690
    node = dns_data.name
3691
    primary_ip = self.op.primary_ip = dns_data.ip
3692
    if self.op.secondary_ip is None:
3693
      self.op.secondary_ip = primary_ip
3694
    if not netutils.IsValidIP4(self.op.secondary_ip):
3695
      raise errors.OpPrereqError("Invalid secondary IP given",
3696
                                 errors.ECODE_INVAL)
3697
    secondary_ip = self.op.secondary_ip
3698

    
3699
    node_list = cfg.GetNodeList()
3700
    if not self.op.readd and node in node_list:
3701
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3702
                                 node, errors.ECODE_EXISTS)
3703
    elif self.op.readd and node not in node_list:
3704
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3705
                                 errors.ECODE_NOENT)
3706

    
3707
    self.changed_primary_ip = False
3708

    
3709
    for existing_node_name in node_list:
3710
      existing_node = cfg.GetNodeInfo(existing_node_name)
3711

    
3712
      if self.op.readd and node == existing_node_name:
3713
        if existing_node.secondary_ip != secondary_ip:
3714
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3715
                                     " address configuration as before",
3716
                                     errors.ECODE_INVAL)
3717
        if existing_node.primary_ip != primary_ip:
3718
          self.changed_primary_ip = True
3719

    
3720
        continue
3721

    
3722
      if (existing_node.primary_ip == primary_ip or
3723
          existing_node.secondary_ip == primary_ip or
3724
          existing_node.primary_ip == secondary_ip or
3725
          existing_node.secondary_ip == secondary_ip):
3726
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3727
                                   " existing node %s" % existing_node.name,
3728
                                   errors.ECODE_NOTUNIQUE)
3729

    
3730
    # check that the type of the node (single versus dual homed) is the
3731
    # same as for the master
3732
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3733
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3734
    newbie_singlehomed = secondary_ip == primary_ip
3735
    if master_singlehomed != newbie_singlehomed:
3736
      if master_singlehomed:
3737
        raise errors.OpPrereqError("The master has no private ip but the"
3738
                                   " new node has one",
3739
                                   errors.ECODE_INVAL)
3740
      else:
3741
        raise errors.OpPrereqError("The master has a private ip but the"
3742
                                   " new node doesn't have one",
3743
                                   errors.ECODE_INVAL)
3744

    
3745
    # checks reachability
3746
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3747
      raise errors.OpPrereqError("Node not reachable by ping",
3748
                                 errors.ECODE_ENVIRON)
3749

    
3750
    if not newbie_singlehomed:
3751
      # check reachability from my secondary ip to newbie's secondary ip
3752
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3753
                           source=myself.secondary_ip):
3754
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3755
                                   " based ping to noded port",
3756
                                   errors.ECODE_ENVIRON)
3757

    
3758
    if self.op.readd:
3759
      exceptions = [node]
3760
    else:
3761
      exceptions = []
3762

    
3763
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3764

    
3765
    if self.op.readd:
3766
      self.new_node = self.cfg.GetNodeInfo(node)
3767
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3768
    else:
3769
      self.new_node = objects.Node(name=node,
3770
                                   primary_ip=primary_ip,
3771
                                   secondary_ip=secondary_ip,
3772
                                   master_candidate=self.master_candidate,
3773
                                   offline=False, drained=False)
3774

    
3775
  def Exec(self, feedback_fn):
3776
    """Adds the new node to the cluster.
3777

3778
    """
3779
    new_node = self.new_node
3780
    node = new_node.name
3781

    
3782
    # for re-adds, reset the offline/drained/master-candidate flags;
3783
    # we need to reset here, otherwise offline would prevent RPC calls
3784
    # later in the procedure; this also means that if the re-add
3785
    # fails, we are left with a non-offlined, broken node
3786
    if self.op.readd:
3787
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3788
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3789
      # if we demote the node, we do cleanup later in the procedure
3790
      new_node.master_candidate = self.master_candidate
3791
      if self.changed_primary_ip:
3792
        new_node.primary_ip = self.op.primary_ip
3793

    
3794
    # notify the user about any possible mc promotion
3795
    if new_node.master_candidate:
3796
      self.LogInfo("Node will be a master candidate")
3797

    
3798
    # check connectivity
3799
    result = self.rpc.call_version([node])[node]
3800
    result.Raise("Can't get version information from node %s" % node)
3801
    if constants.PROTOCOL_VERSION == result.payload:
3802
      logging.info("Communication to node %s fine, sw version %s match",
3803
                   node, result.payload)
3804
    else:
3805
      raise errors.OpExecError("Version mismatch master version %s,"
3806
                               " node version %s" %
3807
                               (constants.PROTOCOL_VERSION, result.payload))
3808

    
3809
    # setup ssh on node
3810
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3811
      logging.info("Copy ssh key to node %s", node)
3812
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3813
      keyarray = []
3814
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3815
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3816
                  priv_key, pub_key]
3817

    
3818
      for i in keyfiles:
3819
        keyarray.append(utils.ReadFile(i))
3820

    
3821
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3822
                                      keyarray[2], keyarray[3], keyarray[4],
3823
                                      keyarray[5])
3824
      result.Raise("Cannot transfer ssh keys to the new node")
3825

    
3826
    # Add node to our /etc/hosts, and add key to known_hosts
3827
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3828
      # FIXME: this should be done via an rpc call to node daemon
3829
      utils.AddHostToEtcHosts(new_node.name)
3830

    
3831
    if new_node.secondary_ip != new_node.primary_ip:
3832
      result = self.rpc.call_node_has_ip_address(new_node.name,
3833
                                                 new_node.secondary_ip)
3834
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3835
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3836
      if not result.payload:
3837
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3838
                                 " you gave (%s). Please fix and re-run this"
3839
                                 " command." % new_node.secondary_ip)
3840

    
3841
    node_verify_list = [self.cfg.GetMasterNode()]
3842
    node_verify_param = {
3843
      constants.NV_NODELIST: [node],
3844
      # TODO: do a node-net-test as well?
3845
    }
3846

    
3847
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3848
                                       self.cfg.GetClusterName())
3849
    for verifier in node_verify_list:
3850
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3851
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3852
      if nl_payload:
3853
        for failed in nl_payload:
3854
          feedback_fn("ssh/hostname verification failed"
3855
                      " (checking from %s): %s" %
3856
                      (verifier, nl_payload[failed]))
3857
        raise errors.OpExecError("ssh/hostname verification failed.")
3858

    
3859
    if self.op.readd:
3860
      _RedistributeAncillaryFiles(self)
3861
      self.context.ReaddNode(new_node)
3862
      # make sure we redistribute the config
3863
      self.cfg.Update(new_node, feedback_fn)
3864
      # and make sure the new node will not have old files around
3865
      if not new_node.master_candidate:
3866
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3867
        msg = result.fail_msg
3868
        if msg:
3869
          self.LogWarning("Node failed to demote itself from master"
3870
                          " candidate status: %s" % msg)
3871
    else:
3872
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3873
      self.context.AddNode(new_node, self.proc.GetECId())
3874

    
3875

    
3876
class LUSetNodeParams(LogicalUnit):
3877
  """Modifies the parameters of a node.
3878

3879
  """
3880
  HPATH = "node-modify"
3881
  HTYPE = constants.HTYPE_NODE
3882
  _OP_PARAMS = [
3883
    _PNodeName,
3884
    ("master_candidate", None, _TMaybeBool),
3885
    ("offline", None, _TMaybeBool),
3886
    ("drained", None, _TMaybeBool),
3887
    ("auto_promote", False, _TBool),
3888
    _PForce,
3889
    ]
3890
  REQ_BGL = False
3891

    
3892
  def CheckArguments(self):
3893
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3894
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3895
    if all_mods.count(None) == 3:
3896
      raise errors.OpPrereqError("Please pass at least one modification",
3897
                                 errors.ECODE_INVAL)
3898
    if all_mods.count(True) > 1:
3899
      raise errors.OpPrereqError("Can't set the node into more than one"
3900
                                 " state at the same time",
3901
                                 errors.ECODE_INVAL)
3902

    
3903
    # Boolean value that tells us whether we're offlining or draining the node
3904
    self.offline_or_drain = (self.op.offline == True or
3905
                             self.op.drained == True)
3906
    self.deoffline_or_drain = (self.op.offline == False or
3907
                               self.op.drained == False)
3908
    self.might_demote = (self.op.master_candidate == False or
3909
                         self.offline_or_drain)
3910

    
3911
    self.lock_all = self.op.auto_promote and self.might_demote
3912

    
3913

    
3914
  def ExpandNames(self):
3915
    if self.lock_all:
3916
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3917
    else:
3918
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3919

    
3920
  def BuildHooksEnv(self):
3921
    """Build hooks env.
3922

3923
    This runs on the master node.
3924

3925
    """
3926
    env = {
3927
      "OP_TARGET": self.op.node_name,
3928
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3929
      "OFFLINE": str(self.op.offline),
3930
      "DRAINED": str(self.op.drained),
3931
      }
3932
    nl = [self.cfg.GetMasterNode(),
3933
          self.op.node_name]
3934
    return env, nl, nl
3935

    
3936
  def CheckPrereq(self):
3937
    """Check prerequisites.
3938

3939
    This only checks the instance list against the existing names.
3940

3941
    """
3942
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3943

    
3944
    if (self.op.master_candidate is not None or
3945
        self.op.drained is not None or
3946
        self.op.offline is not None):
3947
      # we can't change the master's node flags
3948
      if self.op.node_name == self.cfg.GetMasterNode():
3949
        raise errors.OpPrereqError("The master role can be changed"
3950
                                   " only via masterfailover",
3951
                                   errors.ECODE_INVAL)
3952

    
3953

    
3954
    if node.master_candidate and self.might_demote and not self.lock_all:
3955
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3956
      # check if after removing the current node, we're missing master
3957
      # candidates
3958
      (mc_remaining, mc_should, _) = \
3959
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3960
      if mc_remaining < mc_should:
3961
        raise errors.OpPrereqError("Not enough master candidates, please"
3962
                                   " pass auto_promote to allow promotion",
3963
                                   errors.ECODE_INVAL)
3964

    
3965
    if (self.op.master_candidate == True and
3966
        ((node.offline and not self.op.offline == False) or
3967
         (node.drained and not self.op.drained == False))):
3968
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3969
                                 " to master_candidate" % node.name,
3970
                                 errors.ECODE_INVAL)
3971

    
3972
    # If we're being deofflined/drained, we'll MC ourself if needed
3973
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3974
        self.op.master_candidate == True and not node.master_candidate):
3975
      self.op.master_candidate = _DecideSelfPromotion(self)
3976
      if self.op.master_candidate:
3977
        self.LogInfo("Autopromoting node to master candidate")
3978

    
3979
    return
3980

    
3981
  def Exec(self, feedback_fn):
3982
    """Modifies a node.
3983

3984
    """
3985
    node = self.node
3986

    
3987
    result = []
3988
    changed_mc = False
3989

    
3990
    if self.op.offline is not None:
3991
      node.offline = self.op.offline
3992
      result.append(("offline", str(self.op.offline)))
3993
      if self.op.offline == True:
3994
        if node.master_candidate:
3995
          node.master_candidate = False
3996
          changed_mc = True
3997
          result.append(("master_candidate", "auto-demotion due to offline"))
3998
        if node.drained:
3999
          node.drained = False
4000
          result.append(("drained", "clear drained status due to offline"))
4001

    
4002
    if self.op.master_candidate is not None:
4003
      node.master_candidate = self.op.master_candidate
4004
      changed_mc = True
4005
      result.append(("master_candidate", str(self.op.master_candidate)))
4006
      if self.op.master_candidate == False:
4007
        rrc = self.rpc.call_node_demote_from_mc(node.name)
4008
        msg = rrc.fail_msg
4009
        if msg:
4010
          self.LogWarning("Node failed to demote itself: %s" % msg)
4011

    
4012
    if self.op.drained is not None:
4013
      node.drained = self.op.drained
4014
      result.append(("drained", str(self.op.drained)))
4015
      if self.op.drained == True:
4016
        if node.master_candidate:
4017
          node.master_candidate = False
4018
          changed_mc = True
4019
          result.append(("master_candidate", "auto-demotion due to drain"))
4020
          rrc = self.rpc.call_node_demote_from_mc(node.name)
4021
          msg = rrc.fail_msg
4022
          if msg:
4023
            self.LogWarning("Node failed to demote itself: %s" % msg)
4024
        if node.offline:
4025
          node.offline = False
4026
          result.append(("offline", "clear offline status due to drain"))
4027

    
4028
    # we locked all nodes, we adjust the CP before updating this node
4029
    if self.lock_all:
4030
      _AdjustCandidatePool(self, [node.name])
4031

    
4032
    # this will trigger configuration file update, if needed
4033
    self.cfg.Update(node, feedback_fn)
4034

    
4035
    # this will trigger job queue propagation or cleanup
4036
    if changed_mc:
4037
      self.context.ReaddNode(node)
4038

    
4039
    return result
4040

    
4041

    
4042
class LUPowercycleNode(NoHooksLU):
4043
  """Powercycles a node.
4044

4045
  """
4046
  _OP_PARAMS = [
4047
    _PNodeName,
4048
    _PForce,
4049
    ]
4050
  REQ_BGL = False
4051

    
4052
  def CheckArguments(self):
4053
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4054
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4055
      raise errors.OpPrereqError("The node is the master and the force"
4056
                                 " parameter was not set",
4057
                                 errors.ECODE_INVAL)
4058

    
4059
  def ExpandNames(self):
4060
    """Locking for PowercycleNode.
4061

4062
    This is a last-resort option and shouldn't block on other
4063
    jobs. Therefore, we grab no locks.
4064

4065
    """
4066
    self.needed_locks = {}
4067

    
4068
  def Exec(self, feedback_fn):
4069
    """Reboots a node.
4070

4071