Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 297b0cd3

History | View | Annotate | Download (443.8 kB)

</
1
#
2
#
3

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

    
21

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

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

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

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

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

    
44
from ganeti import ssh
45
from ganeti import utils
46
from ganeti import errors
47
from ganeti import hypervisor
48
from ganeti import locking
49
from ganeti import constants
50
from ganeti import objects
51
from ganeti import serializer
52
from ganeti import ssconf
53
from ganeti import uidpool
54
from ganeti import compat
55
from ganeti import masterd
56
from ganeti import netutils
57
from ganeti import query
58
from ganeti import qlang
59
from ganeti import opcodes
60
from ganeti import ht
61

    
62
import ganeti.masterd.instance # pylint: disable-msg=W0611
63

    
64

    
65
def _SupportsOob(cfg, node):
66
  """Tells if node supports OOB.
67

68
  @type cfg: L{config.ConfigWriter}
69
  @param cfg: The cluster configuration
70
  @type node: L{objects.Node}
71
  @param node: The node
72
  @return: The OOB script if supported or an empty string otherwise
73

74
  """
75
  return cfg.GetNdParams(node)[constants.ND_OOB_PROGRAM]
76

    
77

    
78
class ResultWithJobs:
79
  """Data container for LU results with jobs.
80

81
  Instances of this class returned from L{LogicalUnit.Exec} will be recognized
82
  by L{mcpu.Processor._ProcessResult}. The latter will then submit the jobs
83
  contained in the C{jobs} attribute and include the job IDs in the opcode
84
  result.
85

86
  """
87
  def __init__(self, jobs, **kwargs):
88
    """Initializes this class.
89

90
    Additional return values can be specified as keyword arguments.
91

92
    @type jobs: list of lists of L{opcode.OpCode}
93
    @param jobs: A list of lists of opcode objects
94

95
    """
96
    self.jobs = jobs
97
    self.other = kwargs
98

    
99

    
100
class LogicalUnit(object):
101
  """Logical Unit base class.
102

103
  Subclasses must follow these rules:
104
    - implement ExpandNames
105
    - implement CheckPrereq (except when tasklets are used)
106
    - implement Exec (except when tasklets are used)
107
    - implement BuildHooksEnv
108
    - implement BuildHooksNodes
109
    - redefine HPATH and HTYPE
110
    - optionally redefine their run requirements:
111
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
112

113
  Note that all commands require root permissions.
114

115
  @ivar dry_run_result: the value (if any) that will be returned to the caller
116
      in dry-run mode (signalled by opcode dry_run parameter)
117

118
  """
119
  HPATH = None
120
  HTYPE = None
121
  REQ_BGL = True
122

    
123
  def __init__(self, processor, op, context, rpc):
124
    """Constructor for LogicalUnit.
125

126
    This needs to be overridden in derived classes in order to check op
127
    validity.
128

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

    
155
    # Tasklets
156
    self.tasklets = None
157

    
158
    # Validate opcode parameters and set defaults
159
    self.op.Validate(True)
160

    
161
    self.CheckArguments()
162

    
163
  def CheckArguments(self):
164
    """Check syntactic validity for the opcode arguments.
165

166
    This method is for doing a simple syntactic check and ensure
167
    validity of opcode parameters, without any cluster-related
168
    checks. While the same can be accomplished in ExpandNames and/or
169
    CheckPrereq, doing these separate is better because:
170

171
      - ExpandNames is left as as purely a lock-related function
172
      - CheckPrereq is run after we have acquired locks (and possible
173
        waited for them)
174

175
    The function is allowed to change the self.op attribute so that
176
    later methods can no longer worry about missing parameters.
177

178
    """
179
    pass
180

    
181
  def ExpandNames(self):
182
    """Expand names for this LU.
183

184
    This method is called before starting to execute the opcode, and it should
185
    update all the parameters of the opcode to their canonical form (e.g. a
186
    short node name must be fully expanded after this method has successfully
187
    completed). This way locking, hooks, logging, etc. can work correctly.
188

189
    LUs which implement this method must also populate the self.needed_locks
190
    member, as a dict with lock levels as keys, and a list of needed lock names
191
    as values. Rules:
192

193
      - use an empty dict if you don't need any lock
194
      - if you don't need any lock at a particular level omit that level
195
      - don't put anything for the BGL level
196
      - if you want all locks at a level use locking.ALL_SET as a value
197

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

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

206
    Examples::
207

208
      # Acquire all nodes and one instance
209
      self.needed_locks = {
210
        locking.LEVEL_NODE: locking.ALL_SET,
211
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
212
      }
213
      # Acquire just two nodes
214
      self.needed_locks = {
215
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
216
      }
217
      # Acquire no locks
218
      self.needed_locks = {} # No, you can't leave it to the default value None
219

220
    """
221
    # The implementation of this method is mandatory only if the new LU is
222
    # concurrent, so that old LUs don't need to be changed all at the same
223
    # time.
224
    if self.REQ_BGL:
225
      self.needed_locks = {} # Exclusive LUs don't need locks.
226
    else:
227
      raise NotImplementedError
228

    
229
  def DeclareLocks(self, level):
230
    """Declare LU locking needs for a level
231

232
    While most LUs can just declare their locking needs at ExpandNames time,
233
    sometimes there's the need to calculate some locks after having acquired
234
    the ones before. This function is called just before acquiring locks at a
235
    particular level, but after acquiring the ones at lower levels, and permits
236
    such calculations. It can be used to modify self.needed_locks, and by
237
    default it does nothing.
238

239
    This function is only called if you have something already set in
240
    self.needed_locks for the level.
241

242
    @param level: Locking level which is going to be locked
243
    @type level: member of ganeti.locking.LEVELS
244

245
    """
246

    
247
  def CheckPrereq(self):
248
    """Check prerequisites for this LU.
249

250
    This method should check that the prerequisites for the execution
251
    of this LU are fulfilled. It can do internode communication, but
252
    it should be idempotent - no cluster or system changes are
253
    allowed.
254

255
    The method should raise errors.OpPrereqError in case something is
256
    not fulfilled. Its return value is ignored.
257

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

261
    """
262
    if self.tasklets is not None:
263
      for (idx, tl) in enumerate(self.tasklets):
264
        logging.debug("Checking prerequisites for tasklet %s/%s",
265
                      idx + 1, len(self.tasklets))
266
        tl.CheckPrereq()
267
    else:
268
      pass
269

    
270
  def Exec(self, feedback_fn):
271
    """Execute the LU.
272

273
    This method should implement the actual work. It should raise
274
    errors.OpExecError for failures that are somewhat dealt with in
275
    code, or expected.
276

277
    """
278
    if self.tasklets is not None:
279
      for (idx, tl) in enumerate(self.tasklets):
280
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
281
        tl.Exec(feedback_fn)
282
    else:
283
      raise NotImplementedError
284

    
285
  def BuildHooksEnv(self):
286
    """Build hooks environment for this LU.
287

288
    @rtype: dict
289
    @return: Dictionary containing the environment that will be used for
290
      running the hooks for this LU. The keys of the dict must not be prefixed
291
      with "GANETI_"--that'll be added by the hooks runner. The hooks runner
292
      will extend the environment with additional variables. If no environment
293
      should be defined, an empty dictionary should be returned (not C{None}).
294
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
295
      will not be called.
296

297
    """
298
    raise NotImplementedError
299

    
300
  def BuildHooksNodes(self):
301
    """Build list of nodes to run LU's hooks.
302

303
    @rtype: tuple; (list, list)
304
    @return: Tuple containing a list of node names on which the hook
305
      should run before the execution and a list of node names on which the
306
      hook should run after the execution. No nodes should be returned as an
307
      empty list (and not None).
308
    @note: If the C{HPATH} attribute of the LU class is C{None}, this function
309
      will not be called.
310

311
    """
312
    raise NotImplementedError
313

    
314
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
315
    """Notify the LU about the results of its hooks.
316

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

323
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
324
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
325
    @param hook_results: the results of the multi-node hooks rpc call
326
    @param feedback_fn: function used send feedback back to the caller
327
    @param lu_result: the previous Exec result this LU had, or None
328
        in the PRE phase
329
    @return: the new Exec result, based on the previous result
330
        and hook results
331

332
    """
333
    # API must be kept, thus we ignore the unused argument and could
334
    # be a function warnings
335
    # pylint: disable-msg=W0613,R0201
336
    return lu_result
337

    
338
  def _ExpandAndLockInstance(self):
339
    """Helper function to expand and lock an instance.
340

341
    Many LUs that work on an instance take its name in self.op.instance_name
342
    and need to expand it and then declare the expanded name for locking. This
343
    function does it, and then updates self.op.instance_name to the expanded
344
    name. It also initializes needed_locks as a dict, if this hasn't been done
345
    before.
346

347
    """
348
    if self.needed_locks is None:
349
      self.needed_locks = {}
350
    else:
351
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
352
        "_ExpandAndLockInstance called with instance-level locks set"
353
    self.op.instance_name = _ExpandInstanceName(self.cfg,
354
                                                self.op.instance_name)
355
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
356

    
357
  def _LockInstancesNodes(self, primary_only=False):
358
    """Helper function to declare instances' nodes for locking.
359

360
    This function should be called after locking one or more instances to lock
361
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
362
    with all primary or secondary nodes for instances already locked and
363
    present in self.needed_locks[locking.LEVEL_INSTANCE].
364

365
    It should be called from DeclareLocks, and for safety only works if
366
    self.recalculate_locks[locking.LEVEL_NODE] is set.
367

368
    In the future it may grow parameters to just lock some instance's nodes, or
369
    to just lock primaries or secondary nodes, if needed.
370

371
    If should be called in DeclareLocks in a way similar to::
372

373
      if level == locking.LEVEL_NODE:
374
        self._LockInstancesNodes()
375

376
    @type primary_only: boolean
377
    @param primary_only: only lock primary nodes of locked instances
378

379
    """
380
    assert locking.LEVEL_NODE in self.recalculate_locks, \
381
      "_LockInstancesNodes helper function called with no nodes to recalculate"
382

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

    
385
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
386
    # future we might want to have different behaviors depending on the value
387
    # of self.recalculate_locks[locking.LEVEL_NODE]
388
    wanted_nodes = []
389
    for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
390
      instance = self.context.cfg.GetInstanceInfo(instance_name)
391
      wanted_nodes.append(instance.primary_node)
392
      if not primary_only:
393
        wanted_nodes.extend(instance.secondary_nodes)
394

    
395
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
396
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
397
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
398
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
399

    
400
    del self.recalculate_locks[locking.LEVEL_NODE]
401

    
402

    
403
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
404
  """Simple LU which runs no hooks.
405

406
  This LU is intended as a parent for other LogicalUnits which will
407
  run no hooks, in order to reduce duplicate code.
408

409
  """
410
  HPATH = None
411
  HTYPE = None
412

    
413
  def BuildHooksEnv(self):
414
    """Empty BuildHooksEnv for NoHooksLu.
415

416
    This just raises an error.
417

418
    """
419
    raise AssertionError("BuildHooksEnv called for NoHooksLUs")
420

    
421
  def BuildHooksNodes(self):
422
    """Empty BuildHooksNodes for NoHooksLU.
423

424
    """
425
    raise AssertionError("BuildHooksNodes called for NoHooksLU")
426

    
427

    
428
class Tasklet:
429
  """Tasklet base class.
430

431
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
432
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
433
  tasklets know nothing about locks.
434

435
  Subclasses must follow these rules:
436
    - Implement CheckPrereq
437
    - Implement Exec
438

439
  """
440
  def __init__(self, lu):
441
    self.lu = lu
442

    
443
    # Shortcuts
444
    self.cfg = lu.cfg
445
    self.rpc = lu.rpc
446

    
447
  def CheckPrereq(self):
448
    """Check prerequisites for this tasklets.
449

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

454
    The method should raise errors.OpPrereqError in case something is not
455
    fulfilled. Its return value is ignored.
456

457
    This method should also update all parameters to their canonical form if it
458
    hasn't been done before.
459

460
    """
461
    pass
462

    
463
  def Exec(self, feedback_fn):
464
    """Execute the tasklet.
465

466
    This method should implement the actual work. It should raise
467
    errors.OpExecError for failures that are somewhat dealt with in code, or
468
    expected.
469

470
    """
471
    raise NotImplementedError
472

    
473

    
474
class _QueryBase:
475
  """Base for query utility classes.
476

477
  """
478
  #: Attribute holding field definitions
479
  FIELDS = None
480

    
481
  def __init__(self, filter_, fields, use_locking):
482
    """Initializes this class.
483

484
    """
485
    self.use_locking = use_locking
486

    
487
    self.query = query.Query(self.FIELDS, fields, filter_=filter_,
488
                             namefield="name")
489
    self.requested_data = self.query.RequestedData()
490
    self.names = self.query.RequestedNames()
491

    
492
    # Sort only if no names were requested
493
    self.sort_by_name = not self.names
494

    
495
    self.do_locking = None
496
    self.wanted = None
497

    
498
  def _GetNames(self, lu, all_names, lock_level):
499
    """Helper function to determine names asked for in the query.
500

501
    """
502
    if self.do_locking:
503
      names = lu.glm.list_owned(lock_level)
504
    else:
505
      names = all_names
506

    
507
    if self.wanted == locking.ALL_SET:
508
      assert not self.names
509
      # caller didn't specify names, so ordering is not important
510
      return utils.NiceSort(names)
511

    
512
    # caller specified names and we must keep the same order
513
    assert self.names
514
    assert not self.do_locking or lu.glm.is_owned(lock_level)
515

    
516
    missing = set(self.wanted).difference(names)
517
    if missing:
518
      raise errors.OpExecError("Some items were removed before retrieving"
519
                               " their data: %s" % missing)
520

    
521
    # Return expanded names
522
    return self.wanted
523

    
524
  def ExpandNames(self, lu):
525
    """Expand names for this query.
526

527
    See L{LogicalUnit.ExpandNames}.
528

529
    """
530
    raise NotImplementedError()
531

    
532
  def DeclareLocks(self, lu, level):
533
    """Declare locks for this query.
534

535
    See L{LogicalUnit.DeclareLocks}.
536

537
    """
538
    raise NotImplementedError()
539

    
540
  def _GetQueryData(self, lu):
541
    """Collects all data for this query.
542

543
    @return: Query data object
544

545
    """
546
    raise NotImplementedError()
547

    
548
  def NewStyleQuery(self, lu):
549
    """Collect data and execute query.
550

551
    """
552
    return query.GetQueryResponse(self.query, self._GetQueryData(lu),
553
                                  sort_by_name=self.sort_by_name)
554

    
555
  def OldStyleQuery(self, lu):
556
    """Collect data and execute query.
557

558
    """
559
    return self.query.OldStyleQuery(self._GetQueryData(lu),
560
                                    sort_by_name=self.sort_by_name)
561

    
562

    
563
def _GetWantedNodes(lu, nodes):
564
  """Returns list of checked and expanded node names.
565

566
  @type lu: L{LogicalUnit}
567
  @param lu: the logical unit on whose behalf we execute
568
  @type nodes: list
569
  @param nodes: list of node names or None for all nodes
570
  @rtype: list
571
  @return: the list of nodes, sorted
572
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
573

574
  """
575
  if nodes:
576
    return [_ExpandNodeName(lu.cfg, name) for name in nodes]
577

    
578
  return utils.NiceSort(lu.cfg.GetNodeList())
579

    
580

    
581
def _GetWantedInstances(lu, instances):
582
  """Returns list of checked and expanded instance names.
583

584
  @type lu: L{LogicalUnit}
585
  @param lu: the logical unit on whose behalf we execute
586
  @type instances: list
587
  @param instances: list of instance names or None for all instances
588
  @rtype: list
589
  @return: the list of instances, sorted
590
  @raise errors.OpPrereqError: if the instances parameter is wrong type
591
  @raise errors.OpPrereqError: if any of the passed instances is not found
592

593
  """
594
  if instances:
595
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
596
  else:
597
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
598
  return wanted
599

    
600

    
601
def _GetUpdatedParams(old_params, update_dict,
602
                      use_default=True, use_none=False):
603
  """Return the new version of a parameter dictionary.
604

605
  @type old_params: dict
606
  @param old_params: old parameters
607
  @type update_dict: dict
608
  @param update_dict: dict containing new parameter values, or
609
      constants.VALUE_DEFAULT to reset the parameter to its default
610
      value
611
  @param use_default: boolean
612
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
613
      values as 'to be deleted' values
614
  @param use_none: boolean
615
  @type use_none: whether to recognise C{None} values as 'to be
616
      deleted' values
617
  @rtype: dict
618
  @return: the new parameter dictionary
619

620
  """
621
  params_copy = copy.deepcopy(old_params)
622
  for key, val in update_dict.iteritems():
623
    if ((use_default and val == constants.VALUE_DEFAULT) or
624
        (use_none and val is None)):
625
      try:
626
        del params_copy[key]
627
      except KeyError:
628
        pass
629
    else:
630
      params_copy[key] = val
631
  return params_copy
632

    
633

    
634
def _ReleaseLocks(lu, level, names=None, keep=None):
635
  """Releases locks owned by an LU.
636

637
  @type lu: L{LogicalUnit}
638
  @param level: Lock level
639
  @type names: list or None
640
  @param names: Names of locks to release
641
  @type keep: list or None
642
  @param keep: Names of locks to retain
643

644
  """
645
  assert not (keep is not None and names is not None), \
646
         "Only one of the 'names' and the 'keep' parameters can be given"
647

    
648
  if names is not None:
649
    should_release = names.__contains__
650
  elif keep:
651
    should_release = lambda name: name not in keep
652
  else:
653
    should_release = None
654

    
655
  if should_release:
656
    retain = []
657
    release = []
658

    
659
    # Determine which locks to release
660
    for name in lu.glm.list_owned(level):
661
      if should_release(name):
662
        release.append(name)
663
      else:
664
        retain.append(name)
665

    
666
    assert len(lu.glm.list_owned(level)) == (len(retain) + len(release))
667

    
668
    # Release just some locks
669
    lu.glm.release(level, names=release)
670

    
671
    assert frozenset(lu.glm.list_owned(level)) == frozenset(retain)
672
  else:
673
    # Release everything
674
    lu.glm.release(level)
675

    
676
    assert not lu.glm.is_owned(level), "No locks should be owned"
677

    
678

    
679
def _RunPostHook(lu, node_name):
680
  """Runs the post-hook for an opcode on a single node.
681

682
  """
683
  hm = lu.proc.hmclass(lu.rpc.call_hooks_runner, lu)
684
  try:
685
    hm.RunPhase(constants.HOOKS_PHASE_POST, nodes=[node_name])
686
  except:
687
    # pylint: disable-msg=W0702
688
    lu.LogWarning("Errors occurred running hooks on %s" % node_name)
689

    
690

    
691
def _CheckOutputFields(static, dynamic, selected):
692
  """Checks whether all selected fields are valid.
693

694
  @type static: L{utils.FieldSet}
695
  @param static: static fields set
696
  @type dynamic: L{utils.FieldSet}
697
  @param dynamic: dynamic fields set
698

699
  """
700
  f = utils.FieldSet()
701
  f.Extend(static)
702
  f.Extend(dynamic)
703

    
704
  delta = f.NonMatching(selected)
705
  if delta:
706
    raise errors.OpPrereqError("Unknown output fields selected: %s"
707
                               % ",".join(delta), errors.ECODE_INVAL)
708

    
709

    
710
def _CheckGlobalHvParams(params):
711
  """Validates that given hypervisor params are not global ones.
712

713
  This will ensure that instances don't get customised versions of
714
  global params.
715

716
  """
717
  used_globals = constants.HVC_GLOBALS.intersection(params)
718
  if used_globals:
719
    msg = ("The following hypervisor parameters are global and cannot"
720
           " be customized at instance level, please modify them at"
721
           " cluster level: %s" % utils.CommaJoin(used_globals))
722
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
723

    
724

    
725
def _CheckNodeOnline(lu, node, msg=None):
726
  """Ensure that a given node is online.
727

728
  @param lu: the LU on behalf of which we make the check
729
  @param node: the node to check
730
  @param msg: if passed, should be a message to replace the default one
731
  @raise errors.OpPrereqError: if the node is offline
732

733
  """
734
  if msg is None:
735
    msg = "Can't use offline node"
736
  if lu.cfg.GetNodeInfo(node).offline:
737
    raise errors.OpPrereqError("%s: %s" % (msg, node), errors.ECODE_STATE)
738

    
739

    
740
def _CheckNodeNotDrained(lu, node):
741
  """Ensure that a given node is not drained.
742

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

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

    
752

    
753
def _CheckNodeVmCapable(lu, node):
754
  """Ensure that a given node is vm capable.
755

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

760
  """
761
  if not lu.cfg.GetNodeInfo(node).vm_capable:
762
    raise errors.OpPrereqError("Can't use non-vm_capable node %s" % node,
763
                               errors.ECODE_STATE)
764

    
765

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

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

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

    
783

    
784
def _CheckNodeHasSecondaryIP(lu, node, secondary_ip, prereq):
785
  """Ensure that a node has the given secondary ip.
786

787
  @type lu: L{LogicalUnit}
788
  @param lu: the LU on behalf of which we make the check
789
  @type node: string
790
  @param node: the node to check
791
  @type secondary_ip: string
792
  @param secondary_ip: the ip to check
793
  @type prereq: boolean
794
  @param prereq: whether to throw a prerequisite or an execute error
795
  @raise errors.OpPrereqError: if the node doesn't have the ip, and prereq=True
796
  @raise errors.OpExecError: if the node doesn't have the ip, and prereq=False
797

798
  """
799
  result = lu.rpc.call_node_has_ip_address(node, secondary_ip)
800
  result.Raise("Failure checking secondary ip on node %s" % node,
801
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
802
  if not result.payload:
803
    msg = ("Node claims it doesn't have the secondary ip you gave (%s),"
804
           " please fix and re-run this command" % secondary_ip)
805
    if prereq:
806
      raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
807
    else:
808
      raise errors.OpExecError(msg)
809

    
810

    
811
def _GetClusterDomainSecret():
812
  """Reads the cluster domain secret.
813

814
  """
815
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
816
                               strict=True)
817

    
818

    
819
def _CheckInstanceDown(lu, instance, reason):
820
  """Ensure that an instance is not running."""
821
  if instance.admin_up:
822
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
823
                               (instance.name, reason), errors.ECODE_STATE)
824

    
825
  pnode = instance.primary_node
826
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
827
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
828
              prereq=True, ecode=errors.ECODE_ENVIRON)
829

    
830
  if instance.name in ins_l.payload:
831
    raise errors.OpPrereqError("Instance %s is running, %s" %
832
                               (instance.name, reason), errors.ECODE_STATE)
833

    
834

    
835
def _ExpandItemName(fn, name, kind):
836
  """Expand an item name.
837

838
  @param fn: the function to use for expansion
839
  @param name: requested item name
840
  @param kind: text description ('Node' or 'Instance')
841
  @return: the resolved (full) name
842
  @raise errors.OpPrereqError: if the item is not found
843

844
  """
845
  full_name = fn(name)
846
  if full_name is None:
847
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
848
                               errors.ECODE_NOENT)
849
  return full_name
850

    
851

    
852
def _ExpandNodeName(cfg, name):
853
  """Wrapper over L{_ExpandItemName} for nodes."""
854
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
855

    
856

    
857
def _ExpandInstanceName(cfg, name):
858
  """Wrapper over L{_ExpandItemName} for instance."""
859
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
860

    
861

    
862
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
863
                          memory, vcpus, nics, disk_template, disks,
864
                          bep, hvp, hypervisor_name):
865
  """Builds instance related env variables for hooks
866

867
  This builds the hook environment from individual variables.
868

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

899
  """
900
  if status:
901
    str_status = "up"
902
  else:
903
    str_status = "down"
904
  env = {
905
    "OP_TARGET": name,
906
    "INSTANCE_NAME": name,
907
    "INSTANCE_PRIMARY": primary_node,
908
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
909
    "INSTANCE_OS_TYPE": os_type,
910
    "INSTANCE_STATUS": str_status,
911
    "INSTANCE_MEMORY": memory,
912
    "INSTANCE_VCPUS": vcpus,
913
    "INSTANCE_DISK_TEMPLATE": disk_template,
914
    "INSTANCE_HYPERVISOR": hypervisor_name,
915
  }
916

    
917
  if nics:
918
    nic_count = len(nics)
919
    for idx, (ip, mac, mode, link) in enumerate(nics):
920
      if ip is None:
921
        ip = ""
922
      env["INSTANCE_NIC%d_IP" % idx] = ip
923
      env["INSTANCE_NIC%d_MAC" % idx] = mac
924
      env["INSTANCE_NIC%d_MODE" % idx] = mode
925
      env["INSTANCE_NIC%d_LINK" % idx] = link
926
      if mode == constants.NIC_MODE_BRIDGED:
927
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
928
  else:
929
    nic_count = 0
930

    
931
  env["INSTANCE_NIC_COUNT"] = nic_count
932

    
933
  if disks:
934
    disk_count = len(disks)
935
    for idx, (size, mode) in enumerate(disks):
936
      env["INSTANCE_DISK%d_SIZE" % idx] = size
937
      env["INSTANCE_DISK%d_MODE" % idx] = mode
938
  else:
939
    disk_count = 0
940

    
941
  env["INSTANCE_DISK_COUNT"] = disk_count
942

    
943
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
944
    for key, value in source.items():
945
      env["INSTANCE_%s_%s" % (kind, key)] = value
946

    
947
  return env
948

    
949

    
950
def _NICListToTuple(lu, nics):
951
  """Build a list of nic information tuples.
952

953
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
954
  value in LUInstanceQueryData.
955

956
  @type lu:  L{LogicalUnit}
957
  @param lu: the logical unit on whose behalf we execute
958
  @type nics: list of L{objects.NIC}
959
  @param nics: list of nics to convert to hooks tuples
960

961
  """
962
  hooks_nics = []
963
  cluster = lu.cfg.GetClusterInfo()
964
  for nic in nics:
965
    ip = nic.ip
966
    mac = nic.mac
967
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
968
    mode = filled_params[constants.NIC_MODE]
969
    link = filled_params[constants.NIC_LINK]
970
    hooks_nics.append((ip, mac, mode, link))
971
  return hooks_nics
972

    
973

    
974
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
975
  """Builds instance related env variables for hooks from an object.
976

977
  @type lu: L{LogicalUnit}
978
  @param lu: the logical unit on whose behalf we execute
979
  @type instance: L{objects.Instance}
980
  @param instance: the instance for which we should build the
981
      environment
982
  @type override: dict
983
  @param override: dictionary with key/values that will override
984
      our values
985
  @rtype: dict
986
  @return: the hook environment dictionary
987

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

    
1011

    
1012
def _AdjustCandidatePool(lu, exceptions):
1013
  """Adjust the candidate pool after node operations.
1014

1015
  """
1016
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1017
  if mod_list:
1018
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1019
               utils.CommaJoin(node.name for node in mod_list))
1020
    for name in mod_list:
1021
      lu.context.ReaddNode(name)
1022
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1023
  if mc_now > mc_max:
1024
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1025
               (mc_now, mc_max))
1026

    
1027

    
1028
def _DecideSelfPromotion(lu, exceptions=None):
1029
  """Decide whether I should promote myself as a master candidate.
1030

1031
  """
1032
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1033
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1034
  # the new node will increase mc_max with one, so:
1035
  mc_should = min(mc_should + 1, cp_size)
1036
  return mc_now < mc_should
1037

    
1038

    
1039
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1040
  """Check that the brigdes needed by a list of nics exist.
1041

1042
  """
1043
  cluster = lu.cfg.GetClusterInfo()
1044
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1045
  brlist = [params[constants.NIC_LINK] for params in paramslist
1046
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1047
  if brlist:
1048
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1049
    result.Raise("Error checking bridges on destination node '%s'" %
1050
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1051

    
1052

    
1053
def _CheckInstanceBridgesExist(lu, instance, node=None):
1054
  """Check that the brigdes needed by an instance exist.
1055

1056
  """
1057
  if node is None:
1058
    node = instance.primary_node
1059
  _CheckNicsBridgesExist(lu, instance.nics, node)
1060

    
1061

    
1062
def _CheckOSVariant(os_obj, name):
1063
  """Check whether an OS name conforms to the os variants specification.
1064

1065
  @type os_obj: L{objects.OS}
1066
  @param os_obj: OS object to check
1067
  @type name: string
1068
  @param name: OS name passed by the user, to check for validity
1069

1070
  """
1071
  if not os_obj.supported_variants:
1072
    return
1073
  variant = objects.OS.GetVariant(name)
1074
  if not variant:
1075
    raise errors.OpPrereqError("OS name must include a variant",
1076
                               errors.ECODE_INVAL)
1077

    
1078
  if variant not in os_obj.supported_variants:
1079
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1080

    
1081

    
1082
def _GetNodeInstancesInner(cfg, fn):
1083
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1084

    
1085

    
1086
def _GetNodeInstances(cfg, node_name):
1087
  """Returns a list of all primary and secondary instances on a node.
1088

1089
  """
1090

    
1091
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1092

    
1093

    
1094
def _GetNodePrimaryInstances(cfg, node_name):
1095
  """Returns primary instances on a node.
1096

1097
  """
1098
  return _GetNodeInstancesInner(cfg,
1099
                                lambda inst: node_name == inst.primary_node)
1100

    
1101

    
1102
def _GetNodeSecondaryInstances(cfg, node_name):
1103
  """Returns secondary instances on a node.
1104

1105
  """
1106
  return _GetNodeInstancesInner(cfg,
1107
                                lambda inst: node_name in inst.secondary_nodes)
1108

    
1109

    
1110
def _GetStorageTypeArgs(cfg, storage_type):
1111
  """Returns the arguments for a storage type.
1112

1113
  """
1114
  # Special case for file storage
1115
  if storage_type == constants.ST_FILE:
1116
    # storage.FileStorage wants a list of storage directories
1117
    return [[cfg.GetFileStorageDir(), cfg.GetSharedFileStorageDir()]]
1118

    
1119
  return []
1120

    
1121

    
1122
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1123
  faulty = []
1124

    
1125
  for dev in instance.disks:
1126
    cfg.SetDiskID(dev, node_name)
1127

    
1128
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1129
  result.Raise("Failed to get disk status from node %s" % node_name,
1130
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1131

    
1132
  for idx, bdev_status in enumerate(result.payload):
1133
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1134
      faulty.append(idx)
1135

    
1136
  return faulty
1137

    
1138

    
1139
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1140
  """Check the sanity of iallocator and node arguments and use the
1141
  cluster-wide iallocator if appropriate.
1142

1143
  Check that at most one of (iallocator, node) is specified. If none is
1144
  specified, then the LU's opcode's iallocator slot is filled with the
1145
  cluster-wide default iallocator.
1146

1147
  @type iallocator_slot: string
1148
  @param iallocator_slot: the name of the opcode iallocator slot
1149
  @type node_slot: string
1150
  @param node_slot: the name of the opcode target node slot
1151

1152
  """
1153
  node = getattr(lu.op, node_slot, None)
1154
  iallocator = getattr(lu.op, iallocator_slot, None)
1155

    
1156
  if node is not None and iallocator is not None:
1157
    raise errors.OpPrereqError("Do not specify both, iallocator and node",
1158
                               errors.ECODE_INVAL)
1159
  elif node is None and iallocator is None:
1160
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1161
    if default_iallocator:
1162
      setattr(lu.op, iallocator_slot, default_iallocator)
1163
    else:
1164
      raise errors.OpPrereqError("No iallocator or node given and no"
1165
                                 " cluster-wide default iallocator found;"
1166
                                 " please specify either an iallocator or a"
1167
                                 " node, or set a cluster-wide default"
1168
                                 " iallocator")
1169

    
1170

    
1171
class LUClusterPostInit(LogicalUnit):
1172
  """Logical unit for running hooks after cluster initialization.
1173

1174
  """
1175
  HPATH = "cluster-init"
1176
  HTYPE = constants.HTYPE_CLUSTER
1177

    
1178
  def BuildHooksEnv(self):
1179
    """Build hooks env.
1180

1181
    """
1182
    return {
1183
      "OP_TARGET": self.cfg.GetClusterName(),
1184
      }
1185

    
1186
  def BuildHooksNodes(self):
1187
    """Build hooks nodes.
1188

1189
    """
1190
    return ([], [self.cfg.GetMasterNode()])
1191

    
1192
  def Exec(self, feedback_fn):
1193
    """Nothing to do.
1194

1195
    """
1196
    return True
1197

    
1198

    
1199
class LUClusterDestroy(LogicalUnit):
1200
  """Logical unit for destroying the cluster.
1201

1202
  """
1203
  HPATH = "cluster-destroy"
1204
  HTYPE = constants.HTYPE_CLUSTER
1205

    
1206
  def BuildHooksEnv(self):
1207
    """Build hooks env.
1208

1209
    """
1210
    return {
1211
      "OP_TARGET": self.cfg.GetClusterName(),
1212
      }
1213

    
1214
  def BuildHooksNodes(self):
1215
    """Build hooks nodes.
1216

1217
    """
1218
    return ([], [])
1219

    
1220
  def CheckPrereq(self):
1221
    """Check prerequisites.
1222

1223
    This checks whether the cluster is empty.
1224

1225
    Any errors are signaled by raising errors.OpPrereqError.
1226

1227
    """
1228
    master = self.cfg.GetMasterNode()
1229

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

    
1241
  def Exec(self, feedback_fn):
1242
    """Destroys the cluster.
1243

1244
    """
1245
    master = self.cfg.GetMasterNode()
1246

    
1247
    # Run post hooks on master node before it's removed
1248
    _RunPostHook(self, master)
1249

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

    
1253
    return master
1254

    
1255

    
1256
def _VerifyCertificate(filename):
1257
  """Verifies a certificate for LUClusterVerifyConfig.
1258

1259
  @type filename: string
1260
  @param filename: Path to PEM file
1261

1262
  """
1263
  try:
1264
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1265
                                           utils.ReadFile(filename))
1266
  except Exception, err: # pylint: disable-msg=W0703
1267
    return (LUClusterVerifyConfig.ETYPE_ERROR,
1268
            "Failed to load X509 certificate %s: %s" % (filename, err))
1269

    
1270
  (errcode, msg) = \
1271
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1272
                                constants.SSL_CERT_EXPIRATION_ERROR)
1273

    
1274
  if msg:
1275
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1276
  else:
1277
    fnamemsg = None
1278

    
1279
  if errcode is None:
1280
    return (None, fnamemsg)
1281
  elif errcode == utils.CERT_WARNING:
1282
    return (LUClusterVerifyConfig.ETYPE_WARNING, fnamemsg)
1283
  elif errcode == utils.CERT_ERROR:
1284
    return (LUClusterVerifyConfig.ETYPE_ERROR, fnamemsg)
1285

    
1286
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1287

    
1288

    
1289
def _GetAllHypervisorParameters(cluster, instances):
1290
  """Compute the set of all hypervisor parameters.
1291

1292
  @type cluster: L{objects.Cluster}
1293
  @param cluster: the cluster object
1294
  @param instances: list of L{objects.Instance}
1295
  @param instances: additional instances from which to obtain parameters
1296
  @rtype: list of (origin, hypervisor, parameters)
1297
  @return: a list with all parameters found, indicating the hypervisor they
1298
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1299

1300
  """
1301
  hvp_data = []
1302

    
1303
  for hv_name in cluster.enabled_hypervisors:
1304
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1305

    
1306
  for os_name, os_hvp in cluster.os_hvp.items():
1307
    for hv_name, hv_params in os_hvp.items():
1308
      if hv_params:
1309
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1310
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1311

    
1312
  # TODO: collapse identical parameter values in a single one
1313
  for instance in instances:
1314
    if instance.hvparams:
1315
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1316
                       cluster.FillHV(instance)))
1317

    
1318
  return hvp_data
1319

    
1320

    
1321
class _VerifyErrors(object):
1322
  """Mix-in for cluster/group verify LUs.
1323

1324
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1325
  self.op and self._feedback_fn to be available.)
1326

1327
  """
1328
  TCLUSTER = "cluster"
1329
  TNODE = "node"
1330
  TINSTANCE = "instance"
1331

    
1332
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1333
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1334
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1335
  ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1336
  ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1337
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1338
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1339
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1340
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1341
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1342
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1343
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1344
  ENODEDRBD = (TNODE, "ENODEDRBD")
1345
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1346
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1347
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1348
  ENODEHV = (TNODE, "ENODEHV")
1349
  ENODELVM = (TNODE, "ENODELVM")
1350
  ENODEN1 = (TNODE, "ENODEN1")
1351
  ENODENET = (TNODE, "ENODENET")
1352
  ENODEOS = (TNODE, "ENODEOS")
1353
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1354
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1355
  ENODERPC = (TNODE, "ENODERPC")
1356
  ENODESSH = (TNODE, "ENODESSH")
1357
  ENODEVERSION = (TNODE, "ENODEVERSION")
1358
  ENODESETUP = (TNODE, "ENODESETUP")
1359
  ENODETIME = (TNODE, "ENODETIME")
1360
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1361

    
1362
  ETYPE_FIELD = "code"
1363
  ETYPE_ERROR = "ERROR"
1364
  ETYPE_WARNING = "WARNING"
1365

    
1366
  def _Error(self, ecode, item, msg, *args, **kwargs):
1367
    """Format an error message.
1368

1369
    Based on the opcode's error_codes parameter, either format a
1370
    parseable error code, or a simpler error string.
1371

1372
    This must be called only from Exec and functions called from Exec.
1373

1374
    """
1375
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1376
    itype, etxt = ecode
1377
    # first complete the msg
1378
    if args:
1379
      msg = msg % args
1380
    # then format the whole message
1381
    if self.op.error_codes: # This is a mix-in. pylint: disable-msg=E1101
1382
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1383
    else:
1384
      if item:
1385
        item = " " + item
1386
      else:
1387
        item = ""
1388
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1389
    # and finally report it via the feedback_fn
1390
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable-msg=E1101
1391

    
1392
  def _ErrorIf(self, cond, *args, **kwargs):
1393
    """Log an error message if the passed condition is True.
1394

1395
    """
1396
    cond = (bool(cond)
1397
            or self.op.debug_simulate_errors) # pylint: disable-msg=E1101
1398
    if cond:
1399
      self._Error(*args, **kwargs)
1400
    # do not mark the operation as failed for WARN cases only
1401
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1402
      self.bad = self.bad or cond
1403

    
1404

    
1405
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1406
  """Verifies the cluster config.
1407

1408
  """
1409
  REQ_BGL = False
1410

    
1411
  def _VerifyHVP(self, hvp_data):
1412
    """Verifies locally the syntax of the hypervisor parameters.
1413

1414
    """
1415
    for item, hv_name, hv_params in hvp_data:
1416
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1417
             (item, hv_name))
1418
      try:
1419
        hv_class = hypervisor.GetHypervisor(hv_name)
1420
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1421
        hv_class.CheckParameterSyntax(hv_params)
1422
      except errors.GenericError, err:
1423
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1424

    
1425
  def ExpandNames(self):
1426
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1427
    self.all_node_info = self.cfg.GetAllNodesInfo()
1428
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1429
    self.needed_locks = {}
1430

    
1431
  def Exec(self, feedback_fn):
1432
    """Verify integrity of cluster, performing various test on nodes.
1433

1434
    """
1435
    self.bad = False
1436
    self._feedback_fn = feedback_fn
1437

    
1438
    feedback_fn("* Verifying cluster config")
1439

    
1440
    for msg in self.cfg.VerifyConfig():
1441
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1442

    
1443
    feedback_fn("* Verifying cluster certificate files")
1444

    
1445
    for cert_filename in constants.ALL_CERT_FILES:
1446
      (errcode, msg) = _VerifyCertificate(cert_filename)
1447
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1448

    
1449
    feedback_fn("* Verifying hypervisor parameters")
1450

    
1451
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1452
                                                self.all_inst_info.values()))
1453

    
1454
    feedback_fn("* Verifying all nodes belong to an existing group")
1455

    
1456
    # We do this verification here because, should this bogus circumstance
1457
    # occur, it would never be catched by VerifyGroup, which only acts on
1458
    # nodes/instances reachable from existing node groups.
1459

    
1460
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1461
                         if node.group not in self.all_group_info)
1462

    
1463
    dangling_instances = {}
1464
    no_node_instances = []
1465

    
1466
    for inst in self.all_inst_info.values():
1467
      if inst.primary_node in dangling_nodes:
1468
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1469
      elif inst.primary_node not in self.all_node_info:
1470
        no_node_instances.append(inst.name)
1471

    
1472
    pretty_dangling = [
1473
        "%s (%s)" %
1474
        (node.name,
1475
         utils.CommaJoin(dangling_instances.get(node.name,
1476
                                                ["no instances"])))
1477
        for node in dangling_nodes]
1478

    
1479
    self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1480
                  "the following nodes (and their instances) belong to a non"
1481
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1482

    
1483
    self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1484
                  "the following instances have a non-existing primary-node:"
1485
                  " %s", utils.CommaJoin(no_node_instances))
1486

    
1487
    return (not self.bad, [g.name for g in self.all_group_info.values()])
1488

    
1489

    
1490
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1491
  """Verifies the status of a node group.
1492

1493
  """
1494
  HPATH = "cluster-verify"
1495
  HTYPE = constants.HTYPE_CLUSTER
1496
  REQ_BGL = False
1497

    
1498
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1499

    
1500
  class NodeImage(object):
1501
    """A class representing the logical and physical status of a node.
1502

1503
    @type name: string
1504
    @ivar name: the node name to which this object refers
1505
    @ivar volumes: a structure as returned from
1506
        L{ganeti.backend.GetVolumeList} (runtime)
1507
    @ivar instances: a list of running instances (runtime)
1508
    @ivar pinst: list of configured primary instances (config)
1509
    @ivar sinst: list of configured secondary instances (config)
1510
    @ivar sbp: dictionary of {primary-node: list of instances} for all
1511
        instances for which this node is secondary (config)
1512
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1513
    @ivar dfree: free disk, as reported by the node (runtime)
1514
    @ivar offline: the offline status (config)
1515
    @type rpc_fail: boolean
1516
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1517
        not whether the individual keys were correct) (runtime)
1518
    @type lvm_fail: boolean
1519
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1520
    @type hyp_fail: boolean
1521
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1522
    @type ghost: boolean
1523
    @ivar ghost: whether this is a known node or not (config)
1524
    @type os_fail: boolean
1525
    @ivar os_fail: whether the RPC call didn't return valid OS data
1526
    @type oslist: list
1527
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1528
    @type vm_capable: boolean
1529
    @ivar vm_capable: whether the node can host instances
1530

1531
    """
1532
    def __init__(self, offline=False, name=None, vm_capable=True):
1533
      self.name = name
1534
      self.volumes = {}
1535
      self.instances = []
1536
      self.pinst = []
1537
      self.sinst = []
1538
      self.sbp = {}
1539
      self.mfree = 0
1540
      self.dfree = 0
1541
      self.offline = offline
1542
      self.vm_capable = vm_capable
1543
      self.rpc_fail = False
1544
      self.lvm_fail = False
1545
      self.hyp_fail = False
1546
      self.ghost = False
1547
      self.os_fail = False
1548
      self.oslist = {}
1549

    
1550
  def ExpandNames(self):
1551
    # This raises errors.OpPrereqError on its own:
1552
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1553

    
1554
    all_node_info = self.cfg.GetAllNodesInfo()
1555
    all_inst_info = self.cfg.GetAllInstancesInfo()
1556

    
1557
    node_names = set(node.name
1558
                     for node in all_node_info.values()
1559
                     if node.group == self.group_uuid)
1560

    
1561
    inst_names = [inst.name
1562
                  for inst in all_inst_info.values()
1563
                  if inst.primary_node in node_names]
1564

    
1565
    # In Exec(), we warn about mirrored instances that have primary and
1566
    # secondary living in separate node groups. To fully verify that
1567
    # volumes for these instances are healthy, we will need to do an
1568
    # extra call to their secondaries. We ensure here those nodes will
1569
    # be locked.
1570
    for inst in inst_names:
1571
      if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1572
        node_names.update(all_inst_info[inst].secondary_nodes)
1573

    
1574
    self.needed_locks = {
1575
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1576
      locking.LEVEL_NODE: list(node_names),
1577
      locking.LEVEL_INSTANCE: inst_names,
1578
    }
1579

    
1580
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1581

    
1582
  def CheckPrereq(self):
1583
    self.all_node_info = self.cfg.GetAllNodesInfo()
1584
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1585

    
1586
    group_nodes = set(node.name
1587
                      for node in self.all_node_info.values()
1588
                      if node.group == self.group_uuid)
1589

    
1590
    group_instances = set(inst.name
1591
                          for inst in self.all_inst_info.values()
1592
                          if inst.primary_node in group_nodes)
1593

    
1594
    unlocked_nodes = \
1595
        group_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1596

    
1597
    unlocked_instances = \
1598
        group_instances.difference(self.glm.list_owned(locking.LEVEL_INSTANCE))
1599

    
1600
    if unlocked_nodes:
1601
      raise errors.OpPrereqError("missing lock for nodes: %s" %
1602
                                 utils.CommaJoin(unlocked_nodes))
1603

    
1604
    if unlocked_instances:
1605
      raise errors.OpPrereqError("missing lock for instances: %s" %
1606
                                 utils.CommaJoin(unlocked_instances))
1607

    
1608
    self.my_node_names = utils.NiceSort(group_nodes)
1609
    self.my_inst_names = utils.NiceSort(group_instances)
1610

    
1611
    self.my_node_info = dict((name, self.all_node_info[name])
1612
                             for name in self.my_node_names)
1613

    
1614
    self.my_inst_info = dict((name, self.all_inst_info[name])
1615
                             for name in self.my_inst_names)
1616

    
1617
    # We detect here the nodes that will need the extra RPC calls for verifying
1618
    # split LV volumes; they should be locked.
1619
    extra_lv_nodes = set()
1620

    
1621
    for inst in self.my_inst_info.values():
1622
      if inst.disk_template in constants.DTS_INT_MIRROR:
1623
        group = self.my_node_info[inst.primary_node].group
1624
        for nname in inst.secondary_nodes:
1625
          if self.all_node_info[nname].group != group:
1626
            extra_lv_nodes.add(nname)
1627

    
1628
    unlocked_lv_nodes = \
1629
        extra_lv_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1630

    
1631
    if unlocked_lv_nodes:
1632
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1633
                                 utils.CommaJoin(unlocked_lv_nodes))
1634
    self.extra_lv_nodes = list(extra_lv_nodes)
1635

    
1636
  def _VerifyNode(self, ninfo, nresult):
1637
    """Perform some basic validation on data returned from a node.
1638

1639
      - check the result data structure is well formed and has all the
1640
        mandatory fields
1641
      - check ganeti version
1642

1643
    @type ninfo: L{objects.Node}
1644
    @param ninfo: the node to check
1645
    @param nresult: the results from the node
1646
    @rtype: boolean
1647
    @return: whether overall this call was successful (and we can expect
1648
         reasonable values in the respose)
1649

1650
    """
1651
    node = ninfo.name
1652
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1653

    
1654
    # main result, nresult should be a non-empty dict
1655
    test = not nresult or not isinstance(nresult, dict)
1656
    _ErrorIf(test, self.ENODERPC, node,
1657
                  "unable to verify node: no data returned")
1658
    if test:
1659
      return False
1660

    
1661
    # compares ganeti version
1662
    local_version = constants.PROTOCOL_VERSION
1663
    remote_version = nresult.get("version", None)
1664
    test = not (remote_version and
1665
                isinstance(remote_version, (list, tuple)) and
1666
                len(remote_version) == 2)
1667
    _ErrorIf(test, self.ENODERPC, node,
1668
             "connection to node returned invalid data")
1669
    if test:
1670
      return False
1671

    
1672
    test = local_version != remote_version[0]
1673
    _ErrorIf(test, self.ENODEVERSION, node,
1674
             "incompatible protocol versions: master %s,"
1675
             " node %s", local_version, remote_version[0])
1676
    if test:
1677
      return False
1678

    
1679
    # node seems compatible, we can actually try to look into its results
1680

    
1681
    # full package version
1682
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1683
                  self.ENODEVERSION, node,
1684
                  "software version mismatch: master %s, node %s",
1685
                  constants.RELEASE_VERSION, remote_version[1],
1686
                  code=self.ETYPE_WARNING)
1687

    
1688
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1689
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1690
      for hv_name, hv_result in hyp_result.iteritems():
1691
        test = hv_result is not None
1692
        _ErrorIf(test, self.ENODEHV, node,
1693
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1694

    
1695
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1696
    if ninfo.vm_capable and isinstance(hvp_result, list):
1697
      for item, hv_name, hv_result in hvp_result:
1698
        _ErrorIf(True, self.ENODEHV, node,
1699
                 "hypervisor %s parameter verify failure (source %s): %s",
1700
                 hv_name, item, hv_result)
1701

    
1702
    test = nresult.get(constants.NV_NODESETUP,
1703
                       ["Missing NODESETUP results"])
1704
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1705
             "; ".join(test))
1706

    
1707
    return True
1708

    
1709
  def _VerifyNodeTime(self, ninfo, nresult,
1710
                      nvinfo_starttime, nvinfo_endtime):
1711
    """Check the node time.
1712

1713
    @type ninfo: L{objects.Node}
1714
    @param ninfo: the node to check
1715
    @param nresult: the remote results for the node
1716
    @param nvinfo_starttime: the start time of the RPC call
1717
    @param nvinfo_endtime: the end time of the RPC call
1718

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

    
1723
    ntime = nresult.get(constants.NV_TIME, None)
1724
    try:
1725
      ntime_merged = utils.MergeTime(ntime)
1726
    except (ValueError, TypeError):
1727
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1728
      return
1729

    
1730
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1731
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1732
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1733
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1734
    else:
1735
      ntime_diff = None
1736

    
1737
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1738
             "Node time diverges by at least %s from master node time",
1739
             ntime_diff)
1740

    
1741
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1742
    """Check the node LVM results.
1743

1744
    @type ninfo: L{objects.Node}
1745
    @param ninfo: the node to check
1746
    @param nresult: the remote results for the node
1747
    @param vg_name: the configured VG name
1748

1749
    """
1750
    if vg_name is None:
1751
      return
1752

    
1753
    node = ninfo.name
1754
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1755

    
1756
    # checks vg existence and size > 20G
1757
    vglist = nresult.get(constants.NV_VGLIST, None)
1758
    test = not vglist
1759
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1760
    if not test:
1761
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1762
                                            constants.MIN_VG_SIZE)
1763
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1764

    
1765
    # check pv names
1766
    pvlist = nresult.get(constants.NV_PVLIST, None)
1767
    test = pvlist is None
1768
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1769
    if not test:
1770
      # check that ':' is not present in PV names, since it's a
1771
      # special character for lvcreate (denotes the range of PEs to
1772
      # use on the PV)
1773
      for _, pvname, owner_vg in pvlist:
1774
        test = ":" in pvname
1775
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1776
                 " '%s' of VG '%s'", pvname, owner_vg)
1777

    
1778
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1779
    """Check the node bridges.
1780

1781
    @type ninfo: L{objects.Node}
1782
    @param ninfo: the node to check
1783
    @param nresult: the remote results for the node
1784
    @param bridges: the expected list of bridges
1785

1786
    """
1787
    if not bridges:
1788
      return
1789

    
1790
    node = ninfo.name
1791
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1792

    
1793
    missing = nresult.get(constants.NV_BRIDGES, None)
1794
    test = not isinstance(missing, list)
1795
    _ErrorIf(test, self.ENODENET, node,
1796
             "did not return valid bridge information")
1797
    if not test:
1798
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1799
               utils.CommaJoin(sorted(missing)))
1800

    
1801
  def _VerifyNodeNetwork(self, ninfo, nresult):
1802
    """Check the node network connectivity results.
1803

1804
    @type ninfo: L{objects.Node}
1805
    @param ninfo: the node to check
1806
    @param nresult: the remote results for the node
1807

1808
    """
1809
    node = ninfo.name
1810
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1811

    
1812
    test = constants.NV_NODELIST not in nresult
1813
    _ErrorIf(test, self.ENODESSH, node,
1814
             "node hasn't returned node ssh connectivity data")
1815
    if not test:
1816
      if nresult[constants.NV_NODELIST]:
1817
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1818
          _ErrorIf(True, self.ENODESSH, node,
1819
                   "ssh communication with node '%s': %s", a_node, a_msg)
1820

    
1821
    test = constants.NV_NODENETTEST not in nresult
1822
    _ErrorIf(test, self.ENODENET, node,
1823
             "node hasn't returned node tcp connectivity data")
1824
    if not test:
1825
      if nresult[constants.NV_NODENETTEST]:
1826
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1827
        for anode in nlist:
1828
          _ErrorIf(True, self.ENODENET, node,
1829
                   "tcp communication with node '%s': %s",
1830
                   anode, nresult[constants.NV_NODENETTEST][anode])
1831

    
1832
    test = constants.NV_MASTERIP not in nresult
1833
    _ErrorIf(test, self.ENODENET, node,
1834
             "node hasn't returned node master IP reachability data")
1835
    if not test:
1836
      if not nresult[constants.NV_MASTERIP]:
1837
        if node == self.master_node:
1838
          msg = "the master node cannot reach the master IP (not configured?)"
1839
        else:
1840
          msg = "cannot reach the master IP"
1841
        _ErrorIf(True, self.ENODENET, node, msg)
1842

    
1843
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1844
                      diskstatus):
1845
    """Verify an instance.
1846

1847
    This function checks to see if the required block devices are
1848
    available on the instance's node.
1849

1850
    """
1851
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1852
    node_current = instanceconfig.primary_node
1853

    
1854
    node_vol_should = {}
1855
    instanceconfig.MapLVsByNode(node_vol_should)
1856

    
1857
    for node in node_vol_should:
1858
      n_img = node_image[node]
1859
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1860
        # ignore missing volumes on offline or broken nodes
1861
        continue
1862
      for volume in node_vol_should[node]:
1863
        test = volume not in n_img.volumes
1864
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1865
                 "volume %s missing on node %s", volume, node)
1866

    
1867
    if instanceconfig.admin_up:
1868
      pri_img = node_image[node_current]
1869
      test = instance not in pri_img.instances and not pri_img.offline
1870
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1871
               "instance not running on its primary node %s",
1872
               node_current)
1873

    
1874
    diskdata = [(nname, success, status, idx)
1875
                for (nname, disks) in diskstatus.items()
1876
                for idx, (success, status) in enumerate(disks)]
1877

    
1878
    for nname, success, bdev_status, idx in diskdata:
1879
      # the 'ghost node' construction in Exec() ensures that we have a
1880
      # node here
1881
      snode = node_image[nname]
1882
      bad_snode = snode.ghost or snode.offline
1883
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1884
               self.EINSTANCEFAULTYDISK, instance,
1885
               "couldn't retrieve status for disk/%s on %s: %s",
1886
               idx, nname, bdev_status)
1887
      _ErrorIf((instanceconfig.admin_up and success and
1888
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1889
               self.EINSTANCEFAULTYDISK, instance,
1890
               "disk/%s on %s is faulty", idx, nname)
1891

    
1892
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1893
    """Verify if there are any unknown volumes in the cluster.
1894

1895
    The .os, .swap and backup volumes are ignored. All other volumes are
1896
    reported as unknown.
1897

1898
    @type reserved: L{ganeti.utils.FieldSet}
1899
    @param reserved: a FieldSet of reserved volume names
1900

1901
    """
1902
    for node, n_img in node_image.items():
1903
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1904
        # skip non-healthy nodes
1905
        continue
1906
      for volume in n_img.volumes:
1907
        test = ((node not in node_vol_should or
1908
                volume not in node_vol_should[node]) and
1909
                not reserved.Matches(volume))
1910
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1911
                      "volume %s is unknown", volume)
1912

    
1913
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1914
    """Verify N+1 Memory Resilience.
1915

1916
    Check that if one single node dies we can still start all the
1917
    instances it was primary for.
1918

1919
    """
1920
    cluster_info = self.cfg.GetClusterInfo()
1921
    for node, n_img in node_image.items():
1922
      # This code checks that every node which is now listed as
1923
      # secondary has enough memory to host all instances it is
1924
      # supposed to should a single other node in the cluster fail.
1925
      # FIXME: not ready for failover to an arbitrary node
1926
      # FIXME: does not support file-backed instances
1927
      # WARNING: we currently take into account down instances as well
1928
      # as up ones, considering that even if they're down someone
1929
      # might want to start them even in the event of a node failure.
1930
      if n_img.offline:
1931
        # we're skipping offline nodes from the N+1 warning, since
1932
        # most likely we don't have good memory infromation from them;
1933
        # we already list instances living on such nodes, and that's
1934
        # enough warning
1935
        continue
1936
      for prinode, instances in n_img.sbp.items():
1937
        needed_mem = 0
1938
        for instance in instances:
1939
          bep = cluster_info.FillBE(instance_cfg[instance])
1940
          if bep[constants.BE_AUTO_BALANCE]:
1941
            needed_mem += bep[constants.BE_MEMORY]
1942
        test = n_img.mfree < needed_mem
1943
        self._ErrorIf(test, self.ENODEN1, node,
1944
                      "not enough memory to accomodate instance failovers"
1945
                      " should node %s fail (%dMiB needed, %dMiB available)",
1946
                      prinode, needed_mem, n_img.mfree)
1947

    
1948
  @classmethod
1949
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1950
                   (files_all, files_all_opt, files_mc, files_vm)):
1951
    """Verifies file checksums collected from all nodes.
1952

1953
    @param errorif: Callback for reporting errors
1954
    @param nodeinfo: List of L{objects.Node} objects
1955
    @param master_node: Name of master node
1956
    @param all_nvinfo: RPC results
1957

1958
    """
1959
    node_names = frozenset(node.name for node in nodeinfo)
1960

    
1961
    assert master_node in node_names
1962
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1963
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1964
           "Found file listed in more than one file list"
1965

    
1966
    # Define functions determining which nodes to consider for a file
1967
    file2nodefn = dict([(filename, fn)
1968
      for (files, fn) in [(files_all, None),
1969
                          (files_all_opt, None),
1970
                          (files_mc, lambda node: (node.master_candidate or
1971
                                                   node.name == master_node)),
1972
                          (files_vm, lambda node: node.vm_capable)]
1973
      for filename in files])
1974

    
1975
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1976

    
1977
    for node in nodeinfo:
1978
      nresult = all_nvinfo[node.name]
1979

    
1980
      if nresult.fail_msg or not nresult.payload:
1981
        node_files = None
1982
      else:
1983
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1984

    
1985
      test = not (node_files and isinstance(node_files, dict))
1986
      errorif(test, cls.ENODEFILECHECK, node.name,
1987
              "Node did not return file checksum data")
1988
      if test:
1989
        continue
1990

    
1991
      for (filename, checksum) in node_files.items():
1992
        # Check if the file should be considered for a node
1993
        fn = file2nodefn[filename]
1994
        if fn is None or fn(node):
1995
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1996

    
1997
    for (filename, checksums) in fileinfo.items():
1998
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
1999

    
2000
      # Nodes having the file
2001
      with_file = frozenset(node_name
2002
                            for nodes in fileinfo[filename].values()
2003
                            for node_name in nodes)
2004

    
2005
      # Nodes missing file
2006
      missing_file = node_names - with_file
2007

    
2008
      if filename in files_all_opt:
2009
        # All or no nodes
2010
        errorif(missing_file and missing_file != node_names,
2011
                cls.ECLUSTERFILECHECK, None,
2012
                "File %s is optional, but it must exist on all or no nodes (not"
2013
                " found on %s)",
2014
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2015
      else:
2016
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
2017
                "File %s is missing from node(s) %s", filename,
2018
                utils.CommaJoin(utils.NiceSort(missing_file)))
2019

    
2020
      # See if there are multiple versions of the file
2021
      test = len(checksums) > 1
2022
      if test:
2023
        variants = ["variant %s on %s" %
2024
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2025
                    for (idx, (checksum, nodes)) in
2026
                      enumerate(sorted(checksums.items()))]
2027
      else:
2028
        variants = []
2029

    
2030
      errorif(test, cls.ECLUSTERFILECHECK, None,
2031
              "File %s found with %s different checksums (%s)",
2032
              filename, len(checksums), "; ".join(variants))
2033

    
2034
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2035
                      drbd_map):
2036
    """Verifies and the node DRBD status.
2037

2038
    @type ninfo: L{objects.Node}
2039
    @param ninfo: the node to check
2040
    @param nresult: the remote results for the node
2041
    @param instanceinfo: the dict of instances
2042
    @param drbd_helper: the configured DRBD usermode helper
2043
    @param drbd_map: the DRBD map as returned by
2044
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2045

2046
    """
2047
    node = ninfo.name
2048
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2049

    
2050
    if drbd_helper:
2051
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2052
      test = (helper_result == None)
2053
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
2054
               "no drbd usermode helper returned")
2055
      if helper_result:
2056
        status, payload = helper_result
2057
        test = not status
2058
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2059
                 "drbd usermode helper check unsuccessful: %s", payload)
2060
        test = status and (payload != drbd_helper)
2061
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2062
                 "wrong drbd usermode helper: %s", payload)
2063

    
2064
    # compute the DRBD minors
2065
    node_drbd = {}
2066
    for minor, instance in drbd_map[node].items():
2067
      test = instance not in instanceinfo
2068
      _ErrorIf(test, self.ECLUSTERCFG, None,
2069
               "ghost instance '%s' in temporary DRBD map", instance)
2070
        # ghost instance should not be running, but otherwise we
2071
        # don't give double warnings (both ghost instance and
2072
        # unallocated minor in use)
2073
      if test:
2074
        node_drbd[minor] = (instance, False)
2075
      else:
2076
        instance = instanceinfo[instance]
2077
        node_drbd[minor] = (instance.name, instance.admin_up)
2078

    
2079
    # and now check them
2080
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2081
    test = not isinstance(used_minors, (tuple, list))
2082
    _ErrorIf(test, self.ENODEDRBD, node,
2083
             "cannot parse drbd status file: %s", str(used_minors))
2084
    if test:
2085
      # we cannot check drbd status
2086
      return
2087

    
2088
    for minor, (iname, must_exist) in node_drbd.items():
2089
      test = minor not in used_minors and must_exist
2090
      _ErrorIf(test, self.ENODEDRBD, node,
2091
               "drbd minor %d of instance %s is not active", minor, iname)
2092
    for minor in used_minors:
2093
      test = minor not in node_drbd
2094
      _ErrorIf(test, self.ENODEDRBD, node,
2095
               "unallocated drbd minor %d is in use", minor)
2096

    
2097
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2098
    """Builds the node OS structures.
2099

2100
    @type ninfo: L{objects.Node}
2101
    @param ninfo: the node to check
2102
    @param nresult: the remote results for the node
2103
    @param nimg: the node image object
2104

2105
    """
2106
    node = ninfo.name
2107
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2108

    
2109
    remote_os = nresult.get(constants.NV_OSLIST, None)
2110
    test = (not isinstance(remote_os, list) or
2111
            not compat.all(isinstance(v, list) and len(v) == 7
2112
                           for v in remote_os))
2113

    
2114
    _ErrorIf(test, self.ENODEOS, node,
2115
             "node hasn't returned valid OS data")
2116

    
2117
    nimg.os_fail = test
2118

    
2119
    if test:
2120
      return
2121

    
2122
    os_dict = {}
2123

    
2124
    for (name, os_path, status, diagnose,
2125
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2126

    
2127
      if name not in os_dict:
2128
        os_dict[name] = []
2129

    
2130
      # parameters is a list of lists instead of list of tuples due to
2131
      # JSON lacking a real tuple type, fix it:
2132
      parameters = [tuple(v) for v in parameters]
2133
      os_dict[name].append((os_path, status, diagnose,
2134
                            set(variants), set(parameters), set(api_ver)))
2135

    
2136
    nimg.oslist = os_dict
2137

    
2138
  def _VerifyNodeOS(self, ninfo, nimg, base):
2139
    """Verifies the node OS list.
2140

2141
    @type ninfo: L{objects.Node}
2142
    @param ninfo: the node to check
2143
    @param nimg: the node image object
2144
    @param base: the 'template' node we match against (e.g. from the master)
2145

2146
    """
2147
    node = ninfo.name
2148
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2149

    
2150
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2151

    
2152
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
2153
    for os_name, os_data in nimg.oslist.items():
2154
      assert os_data, "Empty OS status for OS %s?!" % os_name
2155
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
2156
      _ErrorIf(not f_status, self.ENODEOS, node,
2157
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
2158
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
2159
               "OS '%s' has multiple entries (first one shadows the rest): %s",
2160
               os_name, utils.CommaJoin([v[0] for v in os_data]))
2161
      # this will catched in backend too
2162
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
2163
               and not f_var, self.ENODEOS, node,
2164
               "OS %s with API at least %d does not declare any variant",
2165
               os_name, constants.OS_API_V15)
2166
      # comparisons with the 'base' image
2167
      test = os_name not in base.oslist
2168
      _ErrorIf(test, self.ENODEOS, node,
2169
               "Extra OS %s not present on reference node (%s)",
2170
               os_name, base.name)
2171
      if test:
2172
        continue
2173
      assert base.oslist[os_name], "Base node has empty OS status?"
2174
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
2175
      if not b_status:
2176
        # base OS is invalid, skipping
2177
        continue
2178
      for kind, a, b in [("API version", f_api, b_api),
2179
                         ("variants list", f_var, b_var),
2180
                         ("parameters", beautify_params(f_param),
2181
                          beautify_params(b_param))]:
2182
        _ErrorIf(a != b, self.ENODEOS, node,
2183
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2184
                 kind, os_name, base.name,
2185
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2186

    
2187
    # check any missing OSes
2188
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2189
    _ErrorIf(missing, self.ENODEOS, node,
2190
             "OSes present on reference node %s but missing on this node: %s",
2191
             base.name, utils.CommaJoin(missing))
2192

    
2193
  def _VerifyOob(self, ninfo, nresult):
2194
    """Verifies out of band functionality of a node.
2195

2196
    @type ninfo: L{objects.Node}
2197
    @param ninfo: the node to check
2198
    @param nresult: the remote results for the node
2199

2200
    """
2201
    node = ninfo.name
2202
    # We just have to verify the paths on master and/or master candidates
2203
    # as the oob helper is invoked on the master
2204
    if ((ninfo.master_candidate or ninfo.master_capable) and
2205
        constants.NV_OOB_PATHS in nresult):
2206
      for path_result in nresult[constants.NV_OOB_PATHS]:
2207
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2208

    
2209
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2210
    """Verifies and updates the node volume data.
2211

2212
    This function will update a L{NodeImage}'s internal structures
2213
    with data from the remote call.
2214

2215
    @type ninfo: L{objects.Node}
2216
    @param ninfo: the node to check
2217
    @param nresult: the remote results for the node
2218
    @param nimg: the node image object
2219
    @param vg_name: the configured VG name
2220

2221
    """
2222
    node = ninfo.name
2223
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2224

    
2225
    nimg.lvm_fail = True
2226
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2227
    if vg_name is None:
2228
      pass
2229
    elif isinstance(lvdata, basestring):
2230
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2231
               utils.SafeEncode(lvdata))
2232
    elif not isinstance(lvdata, dict):
2233
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2234
    else:
2235
      nimg.volumes = lvdata
2236
      nimg.lvm_fail = False
2237

    
2238
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2239
    """Verifies and updates the node instance list.
2240

2241
    If the listing was successful, then updates this node's instance
2242
    list. Otherwise, it marks the RPC call as failed for the instance
2243
    list key.
2244

2245
    @type ninfo: L{objects.Node}
2246
    @param ninfo: the node to check
2247
    @param nresult: the remote results for the node
2248
    @param nimg: the node image object
2249

2250
    """
2251
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2252
    test = not isinstance(idata, list)
2253
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2254
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2255
    if test:
2256
      nimg.hyp_fail = True
2257
    else:
2258
      nimg.instances = idata
2259

    
2260
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2261
    """Verifies and computes a node information map
2262

2263
    @type ninfo: L{objects.Node}
2264
    @param ninfo: the node to check
2265
    @param nresult: the remote results for the node
2266
    @param nimg: the node image object
2267
    @param vg_name: the configured VG name
2268

2269
    """
2270
    node = ninfo.name
2271
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2272

    
2273
    # try to read free memory (from the hypervisor)
2274
    hv_info = nresult.get(constants.NV_HVINFO, None)
2275
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2276
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2277
    if not test:
2278
      try:
2279
        nimg.mfree = int(hv_info["memory_free"])
2280
      except (ValueError, TypeError):
2281
        _ErrorIf(True, self.ENODERPC, node,
2282
                 "node returned invalid nodeinfo, check hypervisor")
2283

    
2284
    # FIXME: devise a free space model for file based instances as well
2285
    if vg_name is not None:
2286
      test = (constants.NV_VGLIST not in nresult or
2287
              vg_name not in nresult[constants.NV_VGLIST])
2288
      _ErrorIf(test, self.ENODELVM, node,
2289
               "node didn't return data for the volume group '%s'"
2290
               " - it is either missing or broken", vg_name)
2291
      if not test:
2292
        try:
2293
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2294
        except (ValueError, TypeError):
2295
          _ErrorIf(True, self.ENODERPC, node,
2296
                   "node returned invalid LVM info, check LVM status")
2297

    
2298
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2299
    """Gets per-disk status information for all instances.
2300

2301
    @type nodelist: list of strings
2302
    @param nodelist: Node names
2303
    @type node_image: dict of (name, L{objects.Node})
2304
    @param node_image: Node objects
2305
    @type instanceinfo: dict of (name, L{objects.Instance})
2306
    @param instanceinfo: Instance objects
2307
    @rtype: {instance: {node: [(succes, payload)]}}
2308
    @return: a dictionary of per-instance dictionaries with nodes as
2309
        keys and disk information as values; the disk information is a
2310
        list of tuples (success, payload)
2311

2312
    """
2313
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2314

    
2315
    node_disks = {}
2316
    node_disks_devonly = {}
2317
    diskless_instances = set()
2318
    diskless = constants.DT_DISKLESS
2319

    
2320
    for nname in nodelist:
2321
      node_instances = list(itertools.chain(node_image[nname].pinst,
2322
                                            node_image[nname].sinst))
2323
      diskless_instances.update(inst for inst in node_instances
2324
                                if instanceinfo[inst].disk_template == diskless)
2325
      disks = [(inst, disk)
2326
               for inst in node_instances
2327
               for disk in instanceinfo[inst].disks]
2328

    
2329
      if not disks:
2330
        # No need to collect data
2331
        continue
2332

    
2333
      node_disks[nname] = disks
2334

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

    
2339
      for dev in devonly:
2340
        self.cfg.SetDiskID(dev, nname)
2341

    
2342
      node_disks_devonly[nname] = devonly
2343

    
2344
    assert len(node_disks) == len(node_disks_devonly)
2345

    
2346
    # Collect data from all nodes with disks
2347
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2348
                                                          node_disks_devonly)
2349

    
2350
    assert len(result) == len(node_disks)
2351

    
2352
    instdisk = {}
2353

    
2354
    for (nname, nres) in result.items():
2355
      disks = node_disks[nname]
2356

    
2357
      if nres.offline:
2358
        # No data from this node
2359
        data = len(disks) * [(False, "node offline")]
2360
      else:
2361
        msg = nres.fail_msg
2362
        _ErrorIf(msg, self.ENODERPC, nname,
2363
                 "while getting disk information: %s", msg)
2364
        if msg:
2365
          # No data from this node
2366
          data = len(disks) * [(False, msg)]
2367
        else:
2368
          data = []
2369
          for idx, i in enumerate(nres.payload):
2370
            if isinstance(i, (tuple, list)) and len(i) == 2:
2371
              data.append(i)
2372
            else:
2373
              logging.warning("Invalid result from node %s, entry %d: %s",
2374
                              nname, idx, i)
2375
              data.append((False, "Invalid result from the remote node"))
2376

    
2377
      for ((inst, _), status) in zip(disks, data):
2378
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2379

    
2380
    # Add empty entries for diskless instances.
2381
    for inst in diskless_instances:
2382
      assert inst not in instdisk
2383
      instdisk[inst] = {}
2384

    
2385
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2386
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2387
                      compat.all(isinstance(s, (tuple, list)) and
2388
                                 len(s) == 2 for s in statuses)
2389
                      for inst, nnames in instdisk.items()
2390
                      for nname, statuses in nnames.items())
2391
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2392

    
2393
    return instdisk
2394

    
2395
  def BuildHooksEnv(self):
2396
    """Build hooks env.
2397

2398
    Cluster-Verify hooks just ran in the post phase and their failure makes
2399
    the output be logged in the verify output and the verification to fail.
2400

2401
    """
2402
    env = {
2403
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2404
      }
2405

    
2406
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2407
               for node in self.my_node_info.values())
2408

    
2409
    return env
2410

    
2411
  def BuildHooksNodes(self):
2412
    """Build hooks nodes.
2413

2414
    """
2415
    assert self.my_node_names, ("Node list not gathered,"
2416
      " has CheckPrereq been executed?")
2417
    return ([], self.my_node_names)
2418

    
2419
  def Exec(self, feedback_fn):
2420
    """Verify integrity of the node group, performing various test on nodes.
2421

2422
    """
2423
    # This method has too many local variables. pylint: disable-msg=R0914
2424
    self.bad = False
2425
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2426
    verbose = self.op.verbose
2427
    self._feedback_fn = feedback_fn
2428

    
2429
    vg_name = self.cfg.GetVGName()
2430
    drbd_helper = self.cfg.GetDRBDHelper()
2431
    cluster = self.cfg.GetClusterInfo()
2432
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2433
    hypervisors = cluster.enabled_hypervisors
2434
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2435

    
2436
    i_non_redundant = [] # Non redundant instances
2437
    i_non_a_balanced = [] # Non auto-balanced instances
2438
    n_offline = 0 # Count of offline nodes
2439
    n_drained = 0 # Count of nodes being drained
2440
    node_vol_should = {}
2441

    
2442
    # FIXME: verify OS list
2443

    
2444
    # File verification
2445
    filemap = _ComputeAncillaryFiles(cluster, False)
2446

    
2447
    # do local checksums
2448
    master_node = self.master_node = self.cfg.GetMasterNode()
2449
    master_ip = self.cfg.GetMasterIP()
2450

    
2451
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2452

    
2453
    # We will make nodes contact all nodes in their group, and one node from
2454
    # every other group.
2455
    # TODO: should it be a *random* node, different every time?
2456
    online_nodes = [node.name for node in node_data_list if not node.offline]
2457
    other_group_nodes = {}
2458

    
2459
    for name in sorted(self.all_node_info):
2460
      node = self.all_node_info[name]
2461
      if (node.group not in other_group_nodes
2462
          and node.group != self.group_uuid
2463
          and not node.offline):
2464
        other_group_nodes[node.group] = node.name
2465

    
2466
    node_verify_param = {
2467
      constants.NV_FILELIST:
2468
        utils.UniqueSequence(filename
2469
                             for files in filemap
2470
                             for filename in files),
2471
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2472
      constants.NV_HYPERVISOR: hypervisors,
2473
      constants.NV_HVPARAMS:
2474
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2475
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2476
                                 for node in node_data_list
2477
                                 if not node.offline],
2478
      constants.NV_INSTANCELIST: hypervisors,
2479
      constants.NV_VERSION: None,
2480
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2481
      constants.NV_NODESETUP: None,
2482
      constants.NV_TIME: None,
2483
      constants.NV_MASTERIP: (master_node, master_ip),
2484
      constants.NV_OSLIST: None,
2485
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2486
      }
2487

    
2488
    if vg_name is not None:
2489
      node_verify_param[constants.NV_VGLIST] = None
2490
      node_verify_param[constants.NV_LVLIST] = vg_name
2491
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2492
      node_verify_param[constants.NV_DRBDLIST] = None
2493

    
2494
    if drbd_helper:
2495
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2496

    
2497
    # bridge checks
2498
    # FIXME: this needs to be changed per node-group, not cluster-wide
2499
    bridges = set()
2500
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2501
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2502
      bridges.add(default_nicpp[constants.NIC_LINK])
2503
    for instance in self.my_inst_info.values():
2504
      for nic in instance.nics:
2505
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2506
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2507
          bridges.add(full_nic[constants.NIC_LINK])
2508

    
2509
    if bridges:
2510
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2511

    
2512
    # Build our expected cluster state
2513
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2514
                                                 name=node.name,
2515
                                                 vm_capable=node.vm_capable))
2516
                      for node in node_data_list)
2517

    
2518
    # Gather OOB paths
2519
    oob_paths = []
2520
    for node in self.all_node_info.values():
2521
      path = _SupportsOob(self.cfg, node)
2522
      if path and path not in oob_paths:
2523
        oob_paths.append(path)
2524

    
2525
    if oob_paths:
2526
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2527

    
2528
    for instance in self.my_inst_names:
2529
      inst_config = self.my_inst_info[instance]
2530

    
2531
      for nname in inst_config.all_nodes:
2532
        if nname not in node_image:
2533
          gnode = self.NodeImage(name=nname)
2534
          gnode.ghost = (nname not in self.all_node_info)
2535
          node_image[nname] = gnode
2536

    
2537
      inst_config.MapLVsByNode(node_vol_should)
2538

    
2539
      pnode = inst_config.primary_node
2540
      node_image[pnode].pinst.append(instance)
2541

    
2542
      for snode in inst_config.secondary_nodes:
2543
        nimg = node_image[snode]
2544
        nimg.sinst.append(instance)
2545
        if pnode not in nimg.sbp:
2546
          nimg.sbp[pnode] = []
2547
        nimg.sbp[pnode].append(instance)
2548

    
2549
    # At this point, we have the in-memory data structures complete,
2550
    # except for the runtime information, which we'll gather next
2551

    
2552
    # Due to the way our RPC system works, exact response times cannot be
2553
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2554
    # time before and after executing the request, we can at least have a time
2555
    # window.
2556
    nvinfo_starttime = time.time()
2557
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2558
                                           node_verify_param,
2559
                                           self.cfg.GetClusterName())
2560
    if self.extra_lv_nodes and vg_name is not None:
2561
      extra_lv_nvinfo = \
2562
          self.rpc.call_node_verify(self.extra_lv_nodes,
2563
                                    {constants.NV_LVLIST: vg_name},
2564
                                    self.cfg.GetClusterName())
2565
    else:
2566
      extra_lv_nvinfo = {}
2567
    nvinfo_endtime = time.time()
2568

    
2569
    all_drbd_map = self.cfg.ComputeDRBDMap()
2570

    
2571
    feedback_fn("* Gathering disk information (%s nodes)" %
2572
                len(self.my_node_names))
2573
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2574
                                     self.my_inst_info)
2575

    
2576
    feedback_fn("* Verifying configuration file consistency")
2577

    
2578
    # If not all nodes are being checked, we need to make sure the master node
2579
    # and a non-checked vm_capable node are in the list.
2580
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2581
    if absent_nodes:
2582
      vf_nvinfo = all_nvinfo.copy()
2583
      vf_node_info = list(self.my_node_info.values())
2584
      additional_nodes = []
2585
      if master_node not in self.my_node_info:
2586
        additional_nodes.append(master_node)
2587
        vf_node_info.append(self.all_node_info[master_node])
2588
      # Add the first vm_capable node we find which is not included
2589
      for node in absent_nodes:
2590
        nodeinfo = self.all_node_info[node]
2591
        if nodeinfo.vm_capable and not nodeinfo.offline:
2592
          additional_nodes.append(node)
2593
          vf_node_info.append(self.all_node_info[node])
2594
          break
2595
      key = constants.NV_FILELIST
2596
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2597
                                                 {key: node_verify_param[key]},
2598
                                                 self.cfg.GetClusterName()))
2599
    else:
2600
      vf_nvinfo = all_nvinfo
2601
      vf_node_info = self.my_node_info.values()
2602

    
2603
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2604

    
2605
    feedback_fn("* Verifying node status")
2606

    
2607
    refos_img = None
2608

    
2609
    for node_i in node_data_list:
2610
      node = node_i.name
2611
      nimg = node_image[node]
2612

    
2613
      if node_i.offline:
2614
        if verbose:
2615
          feedback_fn("* Skipping offline node %s" % (node,))
2616
        n_offline += 1
2617
        continue
2618

    
2619
      if node == master_node:
2620
        ntype = "master"
2621
      elif node_i.master_candidate:
2622
        ntype = "master candidate"
2623
      elif node_i.drained:
2624
        ntype = "drained"
2625
        n_drained += 1
2626
      else:
2627
        ntype = "regular"
2628
      if verbose:
2629
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2630

    
2631
      msg = all_nvinfo[node].fail_msg
2632
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2633
      if msg:
2634
        nimg.rpc_fail = True
2635
        continue
2636

    
2637
      nresult = all_nvinfo[node].payload
2638

    
2639
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2640
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2641
      self._VerifyNodeNetwork(node_i, nresult)
2642
      self._VerifyOob(node_i, nresult)
2643

    
2644
      if nimg.vm_capable:
2645
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2646
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2647
                             all_drbd_map)
2648

    
2649
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2650
        self._UpdateNodeInstances(node_i, nresult, nimg)
2651
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2652
        self._UpdateNodeOS(node_i, nresult, nimg)
2653

    
2654
        if not nimg.os_fail:
2655
          if refos_img is None:
2656
            refos_img = nimg
2657
          self._VerifyNodeOS(node_i, nimg, refos_img)
2658
        self._VerifyNodeBridges(node_i, nresult, bridges)
2659

    
2660
        # Check whether all running instancies are primary for the node. (This
2661
        # can no longer be done from _VerifyInstance below, since some of the
2662
        # wrong instances could be from other node groups.)
2663
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2664

    
2665
        for inst in non_primary_inst:
2666
          test = inst in self.all_inst_info
2667
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2668
                   "instance should not run on node %s", node_i.name)
2669
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2670
                   "node is running unknown instance %s", inst)
2671

    
2672
    for node, result in extra_lv_nvinfo.items():
2673
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2674
                              node_image[node], vg_name)
2675

    
2676
    feedback_fn("* Verifying instance status")
2677
    for instance in self.my_inst_names:
2678
      if verbose:
2679
        feedback_fn("* Verifying instance %s" % instance)
2680
      inst_config = self.my_inst_info[instance]
2681
      self._VerifyInstance(instance, inst_config, node_image,
2682
                           instdisk[instance])
2683
      inst_nodes_offline = []
2684

    
2685
      pnode = inst_config.primary_node
2686
      pnode_img = node_image[pnode]
2687
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2688
               self.ENODERPC, pnode, "instance %s, connection to"
2689
               " primary node failed", instance)
2690

    
2691
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2692
               self.EINSTANCEBADNODE, instance,
2693
               "instance is marked as running and lives on offline node %s",
2694
               inst_config.primary_node)
2695

    
2696
      # If the instance is non-redundant we cannot survive losing its primary
2697
      # node, so we are not N+1 compliant. On the other hand we have no disk
2698
      # templates with more than one secondary so that situation is not well
2699
      # supported either.
2700
      # FIXME: does not support file-backed instances
2701
      if not inst_config.secondary_nodes:
2702
        i_non_redundant.append(instance)
2703

    
2704
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2705
               instance, "instance has multiple secondary nodes: %s",
2706
               utils.CommaJoin(inst_config.secondary_nodes),
2707
               code=self.ETYPE_WARNING)
2708

    
2709
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2710
        pnode = inst_config.primary_node
2711
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2712
        instance_groups = {}
2713

    
2714
        for node in instance_nodes:
2715
          instance_groups.setdefault(self.all_node_info[node].group,
2716
                                     []).append(node)
2717

    
2718
        pretty_list = [
2719
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2720
          # Sort so that we always list the primary node first.
2721
          for group, nodes in sorted(instance_groups.items(),
2722
                                     key=lambda (_, nodes): pnode in nodes,
2723
                                     reverse=True)]
2724

    
2725
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2726
                      instance, "instance has primary and secondary nodes in"
2727
                      " different groups: %s", utils.CommaJoin(pretty_list),
2728
                      code=self.ETYPE_WARNING)
2729

    
2730
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2731
        i_non_a_balanced.append(instance)
2732

    
2733
      for snode in inst_config.secondary_nodes:
2734
        s_img = node_image[snode]
2735
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2736
                 "instance %s, connection to secondary node failed", instance)
2737

    
2738
        if s_img.offline:
2739
          inst_nodes_offline.append(snode)
2740

    
2741
      # warn that the instance lives on offline nodes
2742
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2743
               "instance has offline secondary node(s) %s",
2744
               utils.CommaJoin(inst_nodes_offline))
2745
      # ... or ghost/non-vm_capable nodes
2746
      for node in inst_config.all_nodes:
2747
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2748
                 "instance lives on ghost node %s", node)
2749
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2750
                 instance, "instance lives on non-vm_capable node %s", node)
2751

    
2752
    feedback_fn("* Verifying orphan volumes")
2753
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2754

    
2755
    # We will get spurious "unknown volume" warnings if any node of this group
2756
    # is secondary for an instance whose primary is in another group. To avoid
2757
    # them, we find these instances and add their volumes to node_vol_should.
2758
    for inst in self.all_inst_info.values():
2759
      for secondary in inst.secondary_nodes:
2760
        if (secondary in self.my_node_info
2761
            and inst.name not in self.my_inst_info):
2762
          inst.MapLVsByNode(node_vol_should)
2763
          break
2764

    
2765
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2766

    
2767
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2768
      feedback_fn("* Verifying N+1 Memory redundancy")
2769
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2770

    
2771
    feedback_fn("* Other Notes")
2772
    if i_non_redundant:
2773
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2774
                  % len(i_non_redundant))
2775

    
2776
    if i_non_a_balanced:
2777
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2778
                  % len(i_non_a_balanced))
2779

    
2780
    if n_offline:
2781
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2782

    
2783
    if n_drained:
2784
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2785

    
2786
    return not self.bad
2787

    
2788
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2789
    """Analyze the post-hooks' result
2790

2791
    This method analyses the hook result, handles it, and sends some
2792
    nicely-formatted feedback back to the user.
2793

2794
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2795
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2796
    @param hooks_results: the results of the multi-node hooks rpc call
2797
    @param feedback_fn: function used send feedback back to the caller
2798
    @param lu_result: previous Exec result
2799
    @return: the new Exec result, based on the previous result
2800
        and hook results
2801

2802
    """
2803
    # We only really run POST phase hooks, and are only interested in
2804
    # their results
2805
    if phase == constants.HOOKS_PHASE_POST:
2806
      # Used to change hooks' output to proper indentation
2807
      feedback_fn("* Hooks Results")
2808
      assert hooks_results, "invalid result from hooks"
2809

    
2810
      for node_name in hooks_results:
2811
        res = hooks_results[node_name]
2812
        msg = res.fail_msg
2813
        test = msg and not res.offline
2814
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2815
                      "Communication failure in hooks execution: %s", msg)
2816
        if res.offline or msg:
2817
          # No need to investigate payload if node is offline or gave an error.
2818
          # override manually lu_result here as _ErrorIf only
2819
          # overrides self.bad
2820
          lu_result = 1
2821
          continue
2822
        for script, hkr, output in res.payload:
2823
          test = hkr == constants.HKR_FAIL
2824
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2825
                        "Script %s failed, output:", script)
2826
          if test:
2827
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2828
            feedback_fn("%s" % output)
2829
            lu_result = 0
2830

    
2831
      return lu_result
2832

    
2833

    
2834
class LUClusterVerifyDisks(NoHooksLU):
2835
  """Verifies the cluster disks status.
2836

2837
  """
2838
  REQ_BGL = False
2839

    
2840
  def ExpandNames(self):
2841
    self.needed_locks = {
2842
      locking.LEVEL_NODE: locking.ALL_SET,
2843
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2844
    }
2845
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2846

    
2847
  def Exec(self, feedback_fn):
2848
    """Verify integrity of cluster disks.
2849

2850
    @rtype: tuple of three items
2851
    @return: a tuple of (dict of node-to-node_error, list of instances
2852
        which need activate-disks, dict of instance: (node, volume) for
2853
        missing volumes
2854

2855
    """
2856
    result = res_nodes, res_instances, res_missing = {}, [], {}
2857

    
2858
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2859
    instances = self.cfg.GetAllInstancesInfo().values()
2860

    
2861
    nv_dict = {}
2862
    for inst in instances:
2863
      inst_lvs = {}
2864
      if not inst.admin_up:
2865
        continue
2866
      inst.MapLVsByNode(inst_lvs)
2867
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2868
      for node, vol_list in inst_lvs.iteritems():
2869
        for vol in vol_list:
2870
          nv_dict[(node, vol)] = inst
2871

    
2872
    if not nv_dict:
2873
      return result
2874

    
2875
    node_lvs = self.rpc.call_lv_list(nodes, [])
2876
    for node, node_res in node_lvs.items():
2877
      if node_res.offline:
2878
        continue
2879
      msg = node_res.fail_msg
2880
      if msg:
2881
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2882
        res_nodes[node] = msg
2883
        continue
2884

    
2885
      lvs = node_res.payload
2886
      for lv_name, (_, _, lv_online) in lvs.items():
2887
        inst = nv_dict.pop((node, lv_name), None)
2888
        if (not lv_online and inst is not None
2889
            and inst.name not in res_instances):
2890
          res_instances.append(inst.name)
2891

    
2892
    # any leftover items in nv_dict are missing LVs, let's arrange the
2893
    # data better
2894
    for key, inst in nv_dict.iteritems():
2895
      if inst.name not in res_missing:
2896
        res_missing[inst.name] = []
2897
      res_missing[inst.name].append(key)
2898

    
2899
    return result
2900

    
2901

    
2902
class LUClusterRepairDiskSizes(NoHooksLU):
2903
  """Verifies the cluster disks sizes.
2904

2905
  """
2906
  REQ_BGL = False
2907

    
2908
  def ExpandNames(self):
2909
    if self.op.instances:
2910
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2911
      self.needed_locks = {
2912
        locking.LEVEL_NODE: [],
2913
        locking.LEVEL_INSTANCE: self.wanted_names,
2914
        }
2915
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2916
    else:
2917
      self.wanted_names = None
2918
      self.needed_locks = {
2919
        locking.LEVEL_NODE: locking.ALL_SET,
2920
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2921
        }
2922
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2923

    
2924
  def DeclareLocks(self, level):
2925
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2926
      self._LockInstancesNodes(primary_only=True)
2927

    
2928
  def CheckPrereq(self):
2929
    """Check prerequisites.
2930

2931
    This only checks the optional instance list against the existing names.
2932

2933
    """
2934
    if self.wanted_names is None:
2935
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2936

    
2937
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2938
                             in self.wanted_names]
2939

    
2940
  def _EnsureChildSizes(self, disk):
2941
    """Ensure children of the disk have the needed disk size.
2942

2943
    This is valid mainly for DRBD8 and fixes an issue where the
2944
    children have smaller disk size.
2945

2946
    @param disk: an L{ganeti.objects.Disk} object
2947

2948
    """
2949
    if disk.dev_type == constants.LD_DRBD8:
2950
      assert disk.children, "Empty children for DRBD8?"
2951
      fchild = disk.children[0]
2952
      mismatch = fchild.size < disk.size
2953
      if mismatch:
2954
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2955
                     fchild.size, disk.size)
2956
        fchild.size = disk.size
2957

    
2958
      # and we recurse on this child only, not on the metadev
2959
      return self._EnsureChildSizes(fchild) or mismatch
2960
    else:
2961
      return False
2962

    
2963
  def Exec(self, feedback_fn):
2964
    """Verify the size of cluster disks.
2965

2966
    """
2967
    # TODO: check child disks too
2968
    # TODO: check differences in size between primary/secondary nodes
2969
    per_node_disks = {}
2970
    for instance in self.wanted_instances:
2971
      pnode = instance.primary_node
2972
      if pnode not in per_node_disks:
2973
        per_node_disks[pnode] = []
2974
      for idx, disk in enumerate(instance.disks):
2975
        per_node_disks[pnode].append((instance, idx, disk))
2976

    
2977
    changed = []
2978
    for node, dskl in per_node_disks.items():
2979
      newl = [v[2].Copy() for v in dskl]
2980
      for dsk in newl:
2981
        self.cfg.SetDiskID(dsk, node)
2982
      result = self.rpc.call_blockdev_getsize(node, newl)
2983
      if result.fail_msg:
2984
        self.LogWarning("Failure in blockdev_getsize call to node"
2985
                        " %s, ignoring", node)
2986
        continue
2987
      if len(result.payload) != len(dskl):
2988
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2989
                        " result.payload=%s", node, len(dskl), result.payload)
2990
        self.LogWarning("Invalid result from node %s, ignoring node results",
2991
                        node)
2992
        continue
2993
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2994
        if size is None:
2995
          self.LogWarning("Disk %d of instance %s did not return size"
2996
                          " information, ignoring", idx, instance.name)
2997
          continue
2998
        if not isinstance(size, (int, long)):
2999
          self.LogWarning("Disk %d of instance %s did not return valid"
3000
                          " size information, ignoring", idx, instance.name)
3001
          continue
3002
        size = size >> 20
3003
        if size != disk.size:
3004
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3005
                       " correcting: recorded %d, actual %d", idx,
3006
                       instance.name, disk.size, size)
3007
          disk.size = size
3008
          self.cfg.Update(instance, feedback_fn)
3009
          changed.append((instance.name, idx, size))
3010
        if self._EnsureChildSizes(disk):
3011
          self.cfg.Update(instance, feedback_fn)
3012
          changed.append((instance.name, idx, disk.size))
3013
    return changed
3014

    
3015

    
3016
class LUClusterRename(LogicalUnit):
3017
  """Rename the cluster.
3018

3019
  """
3020
  HPATH = "cluster-rename"
3021
  HTYPE = constants.HTYPE_CLUSTER
3022

    
3023
  def BuildHooksEnv(self):
3024
    """Build hooks env.
3025

3026
    """
3027
    return {
3028
      "OP_TARGET": self.cfg.GetClusterName(),
3029
      "NEW_NAME": self.op.name,
3030
      }
3031

    
3032
  def BuildHooksNodes(self):
3033
    """Build hooks nodes.
3034

3035
    """
3036
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3037

    
3038
  def CheckPrereq(self):
3039
    """Verify that the passed name is a valid one.
3040

3041
    """
3042
    hostname = netutils.GetHostname(name=self.op.name,
3043
                                    family=self.cfg.GetPrimaryIPFamily())
3044

    
3045
    new_name = hostname.name
3046
    self.ip = new_ip = hostname.ip
3047
    old_name = self.cfg.GetClusterName()
3048
    old_ip = self.cfg.GetMasterIP()
3049
    if new_name == old_name and new_ip == old_ip:
3050
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3051
                                 " cluster has changed",
3052
                                 errors.ECODE_INVAL)
3053
    if new_ip != old_ip:
3054
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3055
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3056
                                   " reachable on the network" %
3057
                                   new_ip, errors.ECODE_NOTUNIQUE)
3058

    
3059
    self.op.name = new_name
3060

    
3061
  def Exec(self, feedback_fn):
3062
    """Rename the cluster.
3063

3064
    """
3065
    clustername = self.op.name
3066
    ip = self.ip
3067

    
3068
    # shutdown the master IP
3069
    master = self.cfg.GetMasterNode()
3070
    result = self.rpc.call_node_stop_master(master, False)
3071
    result.Raise("Could not disable the master role")
3072

    
3073
    try:
3074
      cluster = self.cfg.GetClusterInfo()
3075
      cluster.cluster_name = clustername
3076
      cluster.master_ip = ip
3077
      self.cfg.Update(cluster, feedback_fn)
3078

    
3079
      # update the known hosts file
3080
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3081
      node_list = self.cfg.GetOnlineNodeList()
3082
      try:
3083
        node_list.remove(master)
3084
      except ValueError:
3085
        pass
3086
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3087
    finally:
3088
      result = self.rpc.call_node_start_master(master, False, False)
3089
      msg = result.fail_msg
3090
      if msg:
3091
        self.LogWarning("Could not re-enable the master role on"
3092
                        " the master, please restart manually: %s", msg)
3093

    
3094
    return clustername
3095

    
3096

    
3097
class LUClusterSetParams(LogicalUnit):
3098
  """Change the parameters of the cluster.
3099

3100
  """
3101
  HPATH = "cluster-modify"
3102
  HTYPE = constants.HTYPE_CLUSTER
3103
  REQ_BGL = False
3104

    
3105
  def CheckArguments(self):
3106
    """Check parameters
3107

3108
    """
3109
    if self.op.uid_pool:
3110
      uidpool.CheckUidPool(self.op.uid_pool)
3111

    
3112
    if self.op.add_uids:
3113
      uidpool.CheckUidPool(self.op.add_uids)
3114

    
3115
    if self.op.remove_uids:
3116
      uidpool.CheckUidPool(self.op.remove_uids)
3117

    
3118
  def ExpandNames(self):
3119
    # FIXME: in the future maybe other cluster params won't require checking on
3120
    # all nodes to be modified.
3121
    self.needed_locks = {
3122
      locking.LEVEL_NODE: locking.ALL_SET,
3123
    }
3124
    self.share_locks[locking.LEVEL_NODE] = 1
3125

    
3126
  def BuildHooksEnv(self):
3127
    """Build hooks env.
3128

3129
    """
3130
    return {
3131
      "OP_TARGET": self.cfg.GetClusterName(),
3132
      "NEW_VG_NAME": self.op.vg_name,
3133
      }
3134

    
3135
  def BuildHooksNodes(self):
3136
    """Build hooks nodes.
3137

3138
    """
3139
    mn = self.cfg.GetMasterNode()
3140
    return ([mn], [mn])
3141

    
3142
  def CheckPrereq(self):
3143
    """Check prerequisites.
3144

3145
    This checks whether the given params don't conflict and
3146
    if the given volume group is valid.
3147

3148
    """
3149
    if self.op.vg_name is not None and not self.op.vg_name:
3150
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3151
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3152
                                   " instances exist", errors.ECODE_INVAL)
3153

    
3154
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3155
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3156
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3157
                                   " drbd-based instances exist",
3158
                                   errors.ECODE_INVAL)
3159

    
3160
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
3161

    
3162
    # if vg_name not None, checks given volume group on all nodes
3163
    if self.op.vg_name:
3164
      vglist = self.rpc.call_vg_list(node_list)
3165
      for node in node_list:
3166
        msg = vglist[node].fail_msg
3167
        if msg:
3168
          # ignoring down node
3169
          self.LogWarning("Error while gathering data on node %s"
3170
                          " (ignoring node): %s", node, msg)
3171
          continue
3172
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3173
                                              self.op.vg_name,
3174
                                              constants.MIN_VG_SIZE)
3175
        if vgstatus:
3176
          raise errors.OpPrereqError("Error on node '%s': %s" %
3177
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3178

    
3179
    if self.op.drbd_helper:
3180
      # checks given drbd helper on all nodes
3181
      helpers = self.rpc.call_drbd_helper(node_list)
3182
      for node in node_list:
3183
        ninfo = self.cfg.GetNodeInfo(node)
3184
        if ninfo.offline:
3185
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3186
          continue
3187
        msg = helpers[node].fail_msg
3188
        if msg:
3189
          raise errors.OpPrereqError("Error checking drbd helper on node"
3190
                                     " '%s': %s" % (node, msg),
3191
                                     errors.ECODE_ENVIRON)
3192
        node_helper = helpers[node].payload
3193
        if node_helper != self.op.drbd_helper:
3194
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3195
                                     (node, node_helper), errors.ECODE_ENVIRON)
3196

    
3197
    self.cluster = cluster = self.cfg.GetClusterInfo()
3198
    # validate params changes
3199
    if self.op.beparams:
3200
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3201
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3202

    
3203
    if self.op.ndparams:
3204
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3205
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3206

    
3207
      # TODO: we need a more general way to handle resetting
3208
      # cluster-level parameters to default values
3209
      if self.new_ndparams["oob_program"] == "":
3210
        self.new_ndparams["oob_program"] = \
3211
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3212

    
3213
    if self.op.nicparams:
3214
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3215
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3216
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3217
      nic_errors = []
3218

    
3219
      # check all instances for consistency
3220
      for instance in self.cfg.GetAllInstancesInfo().values():
3221
        for nic_idx, nic in enumerate(instance.nics):
3222
          params_copy = copy.deepcopy(nic.nicparams)
3223
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3224

    
3225
          # check parameter syntax
3226
          try:
3227
            objects.NIC.CheckParameterSyntax(params_filled)
3228
          except errors.ConfigurationError, err:
3229
            nic_errors.append("Instance %s, nic/%d: %s" %
3230
                              (instance.name, nic_idx, err))
3231

    
3232
          # if we're moving instances to routed, check that they have an ip
3233
          target_mode = params_filled[constants.NIC_MODE]
3234
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3235
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3236
                              " address" % (instance.name, nic_idx))
3237
      if nic_errors:
3238
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3239
                                   "\n".join(nic_errors))
3240

    
3241
    # hypervisor list/parameters
3242
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3243
    if self.op.hvparams:
3244
      for hv_name, hv_dict in self.op.hvparams.items():
3245
        if hv_name not in self.new_hvparams:
3246
          self.new_hvparams[hv_name] = hv_dict
3247
        else:
3248
          self.new_hvparams[hv_name].update(hv_dict)
3249

    
3250
    # os hypervisor parameters
3251
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3252
    if self.op.os_hvp:
3253
      for os_name, hvs in self.op.os_hvp.items():
3254
        if os_name not in self.new_os_hvp:
3255
          self.new_os_hvp[os_name] = hvs
3256
        else:
3257
          for hv_name, hv_dict in hvs.items():
3258
            if hv_name not in self.new_os_hvp[os_name]:
3259
              self.new_os_hvp[os_name][hv_name] = hv_dict
3260
            else:
3261
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3262

    
3263
    # os parameters
3264
    self.new_osp = objects.FillDict(cluster.osparams, {})
3265
    if self.op.osparams:
3266
      for os_name, osp in self.op.osparams.items():
3267
        if os_name not in self.new_osp:
3268
          self.new_osp[os_name] = {}
3269

    
3270
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3271
                                                  use_none=True)
3272

    
3273
        if not self.new_osp[os_name]:
3274
          # we removed all parameters
3275
          del self.new_osp[os_name]
3276
        else:
3277
          # check the parameter validity (remote check)
3278
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3279
                         os_name, self.new_osp[os_name])
3280

    
3281
    # changes to the hypervisor list
3282
    if self.op.enabled_hypervisors is not None:
3283
      self.hv_list = self.op.enabled_hypervisors
3284
      for hv in self.hv_list:
3285
        # if the hypervisor doesn't already exist in the cluster
3286
        # hvparams, we initialize it to empty, and then (in both
3287
        # cases) we make sure to fill the defaults, as we might not
3288
        # have a complete defaults list if the hypervisor wasn't
3289
        # enabled before
3290
        if hv not in new_hvp:
3291
          new_hvp[hv] = {}
3292
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3293
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3294
    else:
3295
      self.hv_list = cluster.enabled_hypervisors
3296

    
3297
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3298
      # either the enabled list has changed, or the parameters have, validate
3299
      for hv_name, hv_params in self.new_hvparams.items():
3300
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3301
            (self.op.enabled_hypervisors and
3302
             hv_name in self.op.enabled_hypervisors)):
3303
          # either this is a new hypervisor, or its parameters have changed
3304
          hv_class = hypervisor.GetHypervisor(hv_name)
3305
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3306
          hv_class.CheckParameterSyntax(hv_params)
3307
          _CheckHVParams(self, node_list, hv_name, hv_params)
3308

    
3309
    if self.op.os_hvp:
3310
      # no need to check any newly-enabled hypervisors, since the
3311
      # defaults have already been checked in the above code-block
3312
      for os_name, os_hvp in self.new_os_hvp.items():
3313
        for hv_name, hv_params in os_hvp.items():
3314
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3315
          # we need to fill in the new os_hvp on top of the actual hv_p
3316
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3317
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3318
          hv_class = hypervisor.GetHypervisor(hv_name)
3319
          hv_class.CheckParameterSyntax(new_osp)
3320
          _CheckHVParams(self, node_list, hv_name, new_osp)
3321

    
3322
    if self.op.default_iallocator:
3323
      alloc_script = utils.FindFile(self.op.default_iallocator,
3324
                                    constants.IALLOCATOR_SEARCH_PATH,
3325
                                    os.path.isfile)
3326
      if alloc_script is None:
3327
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3328
                                   " specified" % self.op.default_iallocator,
3329
                                   errors.ECODE_INVAL)
3330

    
3331
  def Exec(self, feedback_fn):
3332
    """Change the parameters of the cluster.
3333

3334
    """
3335
    if self.op.vg_name is not None:
3336
      new_volume = self.op.vg_name
3337
      if not new_volume:
3338
        new_volume = None
3339
      if new_volume != self.cfg.GetVGName():
3340
        self.cfg.SetVGName(new_volume)
3341
      else:
3342
        feedback_fn("Cluster LVM configuration already in desired"
3343
                    " state, not changing")
3344
    if self.op.drbd_helper is not None:
3345
      new_helper = self.op.drbd_helper
3346
      if not new_helper:
3347
        new_helper = None
3348
      if new_helper != self.cfg.GetDRBDHelper():
3349
        self.cfg.SetDRBDHelper(new_helper)
3350
      else:
3351
        feedback_fn("Cluster DRBD helper already in desired state,"
3352
                    " not changing")
3353
    if self.op.hvparams:
3354
      self.cluster.hvparams = self.new_hvparams
3355
    if self.op.os_hvp:
3356
      self.cluster.os_hvp = self.new_os_hvp
3357
    if self.op.enabled_hypervisors is not None:
3358
      self.cluster.hvparams = self.new_hvparams
3359
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3360
    if self.op.beparams:
3361
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3362
    if self.op.nicparams:
3363
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3364
    if self.op.osparams:
3365
      self.cluster.osparams = self.new_osp
3366
    if self.op.ndparams:
3367
      self.cluster.ndparams = self.new_ndparams
3368

    
3369
    if self.op.candidate_pool_size is not None:
3370
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3371
      # we need to update the pool size here, otherwise the save will fail
3372
      _AdjustCandidatePool(self, [])
3373

    
3374
    if self.op.maintain_node_health is not None:
3375
      self.cluster.maintain_node_health = self.op.maintain_node_health
3376

    
3377
    if self.op.prealloc_wipe_disks is not None:
3378
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3379

    
3380
    if self.op.add_uids is not None:
3381
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3382

    
3383
    if self.op.remove_uids is not None:
3384
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3385

    
3386
    if self.op.uid_pool is not None:
3387
      self.cluster.uid_pool = self.op.uid_pool
3388

    
3389
    if self.op.default_iallocator is not None:
3390
      self.cluster.default_iallocator = self.op.default_iallocator
3391

    
3392
    if self.op.reserved_lvs is not None:
3393
      self.cluster.reserved_lvs = self.op.reserved_lvs
3394

    
3395
    def helper_os(aname, mods, desc):
3396
      desc += " OS list"
3397
      lst = getattr(self.cluster, aname)
3398
      for key, val in mods:
3399
        if key == constants.DDM_ADD:
3400
          if val in lst:
3401
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3402
          else:
3403
            lst.append(val)
3404
        elif key == constants.DDM_REMOVE:
3405
          if val in lst:
3406
            lst.remove(val)
3407
          else:
3408
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3409
        else:
3410
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3411

    
3412
    if self.op.hidden_os:
3413
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3414

    
3415
    if self.op.blacklisted_os:
3416
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3417

    
3418
    if self.op.master_netdev:
3419
      master = self.cfg.GetMasterNode()
3420
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3421
                  self.cluster.master_netdev)
3422
      result = self.rpc.call_node_stop_master(master, False)
3423
      result.Raise("Could not disable the master ip")
3424
      feedback_fn("Changing master_netdev from %s to %s" %
3425
                  (self.cluster.master_netdev, self.op.master_netdev))
3426
      self.cluster.master_netdev = self.op.master_netdev
3427

    
3428
    self.cfg.Update(self.cluster, feedback_fn)
3429

    
3430
    if self.op.master_netdev:
3431
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3432
                  self.op.master_netdev)
3433
      result = self.rpc.call_node_start_master(master, False, False)
3434
      if result.fail_msg:
3435
        self.LogWarning("Could not re-enable the master ip on"
3436
                        " the master, please restart manually: %s",
3437
                        result.fail_msg)
3438

    
3439

    
3440
def _UploadHelper(lu, nodes, fname):
3441
  """Helper for uploading a file and showing warnings.
3442

3443
  """
3444
  if os.path.exists(fname):
3445
    result = lu.rpc.call_upload_file(nodes, fname)
3446
    for to_node, to_result in result.items():
3447
      msg = to_result.fail_msg
3448
      if msg:
3449
        msg = ("Copy of file %s to node %s failed: %s" %
3450
               (fname, to_node, msg))
3451
        lu.proc.LogWarning(msg)
3452

    
3453

    
3454
def _ComputeAncillaryFiles(cluster, redist):
3455
  """Compute files external to Ganeti which need to be consistent.
3456

3457
  @type redist: boolean
3458
  @param redist: Whether to include files which need to be redistributed
3459

3460
  """
3461
  # Compute files for all nodes
3462
  files_all = set([
3463
    constants.SSH_KNOWN_HOSTS_FILE,
3464
    constants.CONFD_HMAC_KEY,
3465
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3466
    ])
3467

    
3468
  if not redist:
3469
    files_all.update(constants.ALL_CERT_FILES)
3470
    files_all.update(ssconf.SimpleStore().GetFileList())
3471

    
3472
  if cluster.modify_etc_hosts:
3473
    files_all.add(constants.ETC_HOSTS)
3474

    
3475
  # Files which must either exist on all nodes or on none
3476
  files_all_opt = set([
3477
    constants.RAPI_USERS_FILE,
3478
    ])
3479

    
3480
  # Files which should only be on master candidates
3481
  files_mc = set()
3482
  if not redist:
3483
    files_mc.add(constants.CLUSTER_CONF_FILE)
3484

    
3485
  # Files which should only be on VM-capable nodes
3486
  files_vm = set(filename
3487
    for hv_name in cluster.enabled_hypervisors
3488
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3489

    
3490
  # Filenames must be unique
3491
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3492
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3493
         "Found file listed in more than one file list"
3494

    
3495
  return (files_all, files_all_opt, files_mc, files_vm)
3496

    
3497

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

3501
  ConfigWriter takes care of distributing the config and ssconf files, but
3502
  there are more files which should be distributed to all nodes. This function
3503
  makes sure those are copied.
3504

3505
  @param lu: calling logical unit
3506
  @param additional_nodes: list of nodes not in the config to distribute to
3507
  @type additional_vm: boolean
3508
  @param additional_vm: whether the additional nodes are vm-capable or not
3509

3510
  """
3511
  # Gather target nodes
3512
  cluster = lu.cfg.GetClusterInfo()
3513
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3514

    
3515
  online_nodes = lu.cfg.GetOnlineNodeList()
3516
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3517

    
3518
  if additional_nodes is not None:
3519
    online_nodes.extend(additional_nodes)
3520
    if additional_vm:
3521
      vm_nodes.extend(additional_nodes)
3522

    
3523
  # Never distribute to master node
3524
  for nodelist in [online_nodes, vm_nodes]:
3525
    if master_info.name in nodelist:
3526
      nodelist.remove(master_info.name)
3527

    
3528
  # Gather file lists
3529
  (files_all, files_all_opt, files_mc, files_vm) = \
3530
    _ComputeAncillaryFiles(cluster, True)
3531

    
3532
  # Never re-distribute configuration file from here
3533
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3534
              constants.CLUSTER_CONF_FILE in files_vm)
3535
  assert not files_mc, "Master candidates not handled in this function"
3536

    
3537
  filemap = [
3538
    (online_nodes, files_all),
3539
    (online_nodes, files_all_opt),
3540
    (vm_nodes, files_vm),
3541
    ]
3542

    
3543
  # Upload the files
3544
  for (node_list, files) in filemap:
3545
    for fname in files:
3546
      _UploadHelper(lu, node_list, fname)
3547

    
3548

    
3549
class LUClusterRedistConf(NoHooksLU):
3550
  """Force the redistribution of cluster configuration.
3551

3552
  This is a very simple LU.
3553

3554
  """
3555
  REQ_BGL = False
3556

    
3557
  def ExpandNames(self):
3558
    self.needed_locks = {
3559
      locking.LEVEL_NODE: locking.ALL_SET,
3560
    }
3561
    self.share_locks[locking.LEVEL_NODE] = 1
3562

    
3563
  def Exec(self, feedback_fn):
3564
    """Redistribute the configuration.
3565

3566
    """
3567
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3568
    _RedistributeAncillaryFiles(self)
3569

    
3570

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

3574
  """
3575
  if not instance.disks or disks is not None and not disks:
3576
    return True
3577

    
3578
  disks = _ExpandCheckDisks(instance, disks)
3579

    
3580
  if not oneshot:
3581
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3582

    
3583
  node = instance.primary_node
3584

    
3585
  for dev in disks:
3586
    lu.cfg.SetDiskID(dev, node)
3587

    
3588
  # TODO: Convert to utils.Retry
3589

    
3590
  retries = 0
3591
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3592
  while True:
3593
    max_time = 0
3594
    done = True
3595
    cumul_degraded = False
3596
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3597
    msg = rstats.fail_msg
3598
    if msg:
3599
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3600
      retries += 1
3601
      if retries >= 10:
3602
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3603
                                 " aborting." % node)
3604
      time.sleep(6)
3605
      continue
3606
    rstats = rstats.payload
3607
    retries = 0
3608
    for i, mstat in enumerate(rstats):
3609
      if mstat is None:
3610
        lu.LogWarning("Can't compute data for node %s/%s",
3611
                           node, disks[i].iv_name)
3612
        continue
3613

    
3614
      cumul_degraded = (cumul_degraded or
3615
                        (mstat.is_degraded and mstat.sync_percent is None))
3616
      if mstat.sync_percent is not None:
3617
        done = False
3618
        if mstat.estimated_time is not None:
3619
          rem_time = ("%s remaining (estimated)" %
3620
                      utils.FormatSeconds(mstat.estimated_time))
3621
          max_time = mstat.estimated_time
3622
        else:
3623
          rem_time = "no time estimate"
3624
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3625
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3626

    
3627
    # if we're done but degraded, let's do a few small retries, to
3628
    # make sure we see a stable and not transient situation; therefore
3629
    # we force restart of the loop
3630
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3631
      logging.info("Degraded disks found, %d retries left", degr_retries)
3632
      degr_retries -= 1
3633
      time.sleep(1)
3634
      continue
3635

    
3636
    if done or oneshot:
3637
      break
3638

    
3639
    time.sleep(min(60, max_time))
3640

    
3641
  if done:
3642
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3643
  return not cumul_degraded
3644

    
3645

    
3646
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3647
  """Check that mirrors are not degraded.
3648

3649
  The ldisk parameter, if True, will change the test from the
3650
  is_degraded attribute (which represents overall non-ok status for
3651
  the device(s)) to the ldisk (representing the local storage status).
3652

3653
  """
3654
  lu.cfg.SetDiskID(dev, node)
3655

    
3656
  result = True
3657

    
3658
  if on_primary or dev.AssembleOnSecondary():
3659
    rstats = lu.rpc.call_blockdev_find(node, dev)
3660
    msg = rstats.fail_msg
3661
    if msg:
3662
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3663
      result = False
3664
    elif not rstats.payload:
3665
      lu.LogWarning("Can't find disk on node %s", node)
3666
      result = False
3667
    else:
3668
      if ldisk:
3669
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3670
      else:
3671
        result = result and not rstats.payload.is_degraded
3672

    
3673
  if dev.children:
3674
    for child in dev.children:
3675
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3676

    
3677
  return result
3678

    
3679

    
3680
class LUOobCommand(NoHooksLU):
3681
  """Logical unit for OOB handling.
3682

3683
  """
3684
  REG_BGL = False
3685
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3686

    
3687
  def ExpandNames(self):
3688
    """Gather locks we need.
3689

3690
    """
3691
    if self.op.node_names:
3692
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3693
      lock_names = self.op.node_names
3694
    else:
3695
      lock_names = locking.ALL_SET
3696

    
3697
    self.needed_locks = {
3698
      locking.LEVEL_NODE: lock_names,
3699
      }
3700

    
3701
  def CheckPrereq(self):
3702
    """Check prerequisites.
3703

3704
    This checks:
3705
     - the node exists in the configuration
3706
     - OOB is supported
3707

3708
    Any errors are signaled by raising errors.OpPrereqError.
3709

3710
    """
3711
    self.nodes = []
3712
    self.master_node = self.cfg.GetMasterNode()
3713

    
3714
    assert self.op.power_delay >= 0.0
3715

    
3716
    if self.op.node_names:
3717
      if (self.op.command in self._SKIP_MASTER and
3718
          self.master_node in self.op.node_names):
3719
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3720
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3721

    
3722
        if master_oob_handler:
3723
          additional_text = ("run '%s %s %s' if you want to operate on the"
3724
                             " master regardless") % (master_oob_handler,
3725
                                                      self.op.command,
3726
                                                      self.master_node)
3727
        else:
3728
          additional_text = "it does not support out-of-band operations"
3729

    
3730
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3731
                                    " allowed for %s; %s") %
3732
                                   (self.master_node, self.op.command,
3733
                                    additional_text), errors.ECODE_INVAL)
3734
    else:
3735
      self.op.node_names = self.cfg.GetNodeList()
3736
      if self.op.command in self._SKIP_MASTER:
3737
        self.op.node_names.remove(self.master_node)
3738

    
3739
    if self.op.command in self._SKIP_MASTER:
3740
      assert self.master_node not in self.op.node_names
3741

    
3742
    for node_name in self.op.node_names:
3743
      node = self.cfg.GetNodeInfo(node_name)
3744

    
3745
      if node is None:
3746
        raise errors.OpPrereqError("Node %s not found" % node_name,
3747
                                   errors.ECODE_NOENT)
3748
      else:
3749
        self.nodes.append(node)
3750

    
3751
      if (not self.op.ignore_status and
3752
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3753
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3754
                                    " not marked offline") % node_name,
3755
                                   errors.ECODE_STATE)
3756

    
3757
  def Exec(self, feedback_fn):
3758
    """Execute OOB and return result if we expect any.
3759

3760
    """
3761
    master_node = self.master_node
3762
    ret = []
3763

    
3764
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3765
                                              key=lambda node: node.name)):
3766
      node_entry = [(constants.RS_NORMAL, node.name)]
3767
      ret.append(node_entry)
3768

    
3769
      oob_program = _SupportsOob(self.cfg, node)
3770

    
3771
      if not oob_program:
3772
        node_entry.append((constants.RS_UNAVAIL, None))
3773
        continue
3774

    
3775
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3776
                   self.op.command, oob_program, node.name)
3777
      result = self.rpc.call_run_oob(master_node, oob_program,
3778
                                     self.op.command, node.name,
3779
                                     self.op.timeout)
3780

    
3781
      if result.fail_msg:
3782
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3783
                        node.name, result.fail_msg)
3784
        node_entry.append((constants.RS_NODATA, None))
3785
      else:
3786
        try:
3787
          self._CheckPayload(result)
3788
        except errors.OpExecError, err:
3789
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3790
                          node.name, err)
3791
          node_entry.append((constants.RS_NODATA, None))
3792
        else:
3793
          if self.op.command == constants.OOB_HEALTH:
3794
            # For health we should log important events
3795
            for item, status in result.payload:
3796
              if status in [constants.OOB_STATUS_WARNING,
3797
                            constants.OOB_STATUS_CRITICAL]:
3798
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3799
                                item, node.name, status)
3800

    
3801
          if self.op.command == constants.OOB_POWER_ON:
3802
            node.powered = True
3803
          elif self.op.command == constants.OOB_POWER_OFF:
3804
            node.powered = False
3805
          elif self.op.command == constants.OOB_POWER_STATUS:
3806
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3807
            if powered != node.powered:
3808
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3809
                               " match actual power state (%s)"), node.powered,
3810
                              node.name, powered)
3811

    
3812
          # For configuration changing commands we should update the node
3813
          if self.op.command in (constants.OOB_POWER_ON,
3814
                                 constants.OOB_POWER_OFF):
3815
            self.cfg.Update(node, feedback_fn)
3816

    
3817
          node_entry.append((constants.RS_NORMAL, result.payload))
3818

    
3819
          if (self.op.command == constants.OOB_POWER_ON and
3820
              idx < len(self.nodes) - 1):
3821
            time.sleep(self.op.power_delay)
3822

    
3823
    return ret
3824

    
3825
  def _CheckPayload(self, result):
3826
    """Checks if the payload is valid.
3827

3828
    @param result: RPC result
3829
    @raises errors.OpExecError: If payload is not valid
3830

3831
    """
3832
    errs = []
3833
    if self.op.command == constants.OOB_HEALTH:
3834
      if not isinstance(result.payload, list):
3835
        errs.append("command 'health' is expected to return a list but got %s" %
3836
                    type(result.payload))
3837
      else:
3838
        for item, status in result.payload:
3839
          if status not in constants.OOB_STATUSES:
3840
            errs.append("health item '%s' has invalid status '%s'" %
3841
                        (item, status))
3842

    
3843
    if self.op.command == constants.OOB_POWER_STATUS:
3844
      if not isinstance(result.payload, dict):
3845
        errs.append("power-status is expected to return a dict but got %s" %
3846
                    type(result.payload))
3847

    
3848
    if self.op.command in [
3849
        constants.OOB_POWER_ON,
3850
        constants.OOB_POWER_OFF,
3851
        constants.OOB_POWER_CYCLE,
3852
        ]:
3853
      if result.payload is not None:
3854
        errs.append("%s is expected to not return payload but got '%s'" %
3855
                    (self.op.command, result.payload))
3856

    
3857
    if errs:
3858
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3859
                               utils.CommaJoin(errs))
3860

    
3861
class _OsQuery(_QueryBase):
3862
  FIELDS = query.OS_FIELDS
3863

    
3864
  def ExpandNames(self, lu):
3865
    # Lock all nodes in shared mode
3866
    # Temporary removal of locks, should be reverted later
3867
    # TODO: reintroduce locks when they are lighter-weight
3868
    lu.needed_locks = {}
3869
    #self.share_locks[locking.LEVEL_NODE] = 1
3870
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3871

    
3872
    # The following variables interact with _QueryBase._GetNames
3873
    if self.names:
3874
      self.wanted = self.names
3875
    else:
3876
      self.wanted = locking.ALL_SET
3877

    
3878
    self.do_locking = self.use_locking
3879

    
3880
  def DeclareLocks(self, lu, level):
3881
    pass
3882

    
3883
  @staticmethod
3884
  def _DiagnoseByOS(rlist):
3885
    """Remaps a per-node return list into an a per-os per-node dictionary
3886

3887
    @param rlist: a map with node names as keys and OS objects as values
3888

3889
    @rtype: dict
3890
    @return: a dictionary with osnames as keys and as value another
3891
        map, with nodes as keys and tuples of (path, status, diagnose,
3892
        variants, parameters, api_versions) as values, eg::
3893

3894
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3895
                                     (/srv/..., False, "invalid api")],
3896
                           "node2": [(/srv/..., True, "", [], [])]}
3897
          }
3898

3899
    """
3900
    all_os = {}
3901
    # we build here the list of nodes that didn't fail the RPC (at RPC
3902
    # level), so that nodes with a non-responding node daemon don't
3903
    # make all OSes invalid
3904
    good_nodes = [node_name for node_name in rlist
3905
                  if not rlist[node_name].fail_msg]
3906
    for node_name, nr in rlist.items():
3907
      if nr.fail_msg or not nr.payload:
3908
        continue
3909
      for (name, path, status, diagnose, variants,
3910
           params, api_versions) in nr.payload:
3911
        if name not in all_os:
3912
          # build a list of nodes for this os containing empty lists
3913
          # for each node in node_list
3914
          all_os[name] = {}
3915
          for nname in good_nodes:
3916
            all_os[name][nname] = []
3917
        # convert params from [name, help] to (name, help)
3918
        params = [tuple(v) for v in params]
3919
        all_os[name][node_name].append((path, status, diagnose,
3920
                                        variants, params, api_versions))
3921
    return all_os
3922

    
3923
  def _GetQueryData(self, lu):
3924
    """Computes the list of nodes and their attributes.
3925

3926
    """
3927
    # Locking is not used
3928
    assert not (compat.any(lu.glm.is_owned(level)
3929
                           for level in locking.LEVELS
3930
                           if level != locking.LEVEL_CLUSTER) or
3931
                self.do_locking or self.use_locking)
3932

    
3933
    valid_nodes = [node.name
3934
                   for node in lu.cfg.GetAllNodesInfo().values()
3935
                   if not node.offline and node.vm_capable]
3936
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3937
    cluster = lu.cfg.GetClusterInfo()
3938

    
3939
    data = {}
3940

    
3941
    for (os_name, os_data) in pol.items():
3942
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3943
                          hidden=(os_name in cluster.hidden_os),
3944
                          blacklisted=(os_name in cluster.blacklisted_os))
3945

    
3946
      variants = set()
3947
      parameters = set()
3948
      api_versions = set()
3949

    
3950
      for idx, osl in enumerate(os_data.values()):
3951
        info.valid = bool(info.valid and osl and osl[0][1])
3952
        if not info.valid:
3953
          break
3954

    
3955
        (node_variants, node_params, node_api) = osl[0][3:6]
3956
        if idx == 0:
3957
          # First entry
3958
          variants.update(node_variants)
3959
          parameters.update(node_params)
3960
          api_versions.update(node_api)
3961
        else:
3962
          # Filter out inconsistent values
3963
          variants.intersection_update(node_variants)
3964
          parameters.intersection_update(node_params)
3965
          api_versions.intersection_update(node_api)
3966

    
3967
      info.variants = list(variants)
3968
      info.parameters = list(parameters)
3969
      info.api_versions = list(api_versions)
3970

    
3971
      data[os_name] = info
3972

    
3973
    # Prepare data in requested order
3974
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3975
            if name in data]
3976

    
3977

    
3978
class LUOsDiagnose(NoHooksLU):
3979
  """Logical unit for OS diagnose/query.
3980

3981
  """
3982
  REQ_BGL = False
3983

    
3984
  @staticmethod
3985
  def _BuildFilter(fields, names):
3986
    """Builds a filter for querying OSes.
3987

3988
    """
3989
    name_filter = qlang.MakeSimpleFilter("name", names)
3990

    
3991
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3992
    # respective field is not requested
3993
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3994
                     for fname in ["hidden", "blacklisted"]
3995
                     if fname not in fields]
3996
    if "valid" not in fields:
3997
      status_filter.append([qlang.OP_TRUE, "valid"])
3998

    
3999
    if status_filter:
4000
      status_filter.insert(0, qlang.OP_AND)
4001
    else:
4002
      status_filter = None
4003

    
4004
    if name_filter and status_filter:
4005
      return [qlang.OP_AND, name_filter, status_filter]
4006
    elif name_filter:
4007
      return name_filter
4008
    else:
4009
      return status_filter
4010

    
4011
  def CheckArguments(self):
4012
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4013
                       self.op.output_fields, False)
4014

    
4015
  def ExpandNames(self):
4016
    self.oq.ExpandNames(self)
4017

    
4018
  def Exec(self, feedback_fn):
4019
    return self.oq.OldStyleQuery(self)
4020

    
4021

    
4022
class LUNodeRemove(LogicalUnit):
4023
  """Logical unit for removing a node.
4024

4025
  """
4026
  HPATH = "node-remove"
4027
  HTYPE = constants.HTYPE_NODE
4028

    
4029
  def BuildHooksEnv(self):
4030
    """Build hooks env.
4031

4032
    This doesn't run on the target node in the pre phase as a failed
4033
    node would then be impossible to remove.
4034

4035
    """
4036
    return {
4037
      "OP_TARGET": self.op.node_name,
4038
      "NODE_NAME": self.op.node_name,
4039
      }
4040

    
4041
  def BuildHooksNodes(self):
4042
    """Build hooks nodes.
4043

4044
    """
4045
    all_nodes = self.cfg.GetNodeList()
4046
    try:
4047
      all_nodes.remove(self.op.node_name)
4048
    except ValueError:
4049
      logging.warning("Node '%s', which is about to be removed, was not found"
4050
                      " in the list of all nodes", self.op.node_name)
4051
    return (all_nodes, all_nodes)
4052

    
4053
  def CheckPrereq(self):
4054
    """Check prerequisites.
4055

4056
    This checks:
4057
     - the node exists in the configuration
4058
     - it does not have primary or secondary instances
4059
     - it's not the master
4060

4061
    Any errors are signaled by raising errors.OpPrereqError.
4062

4063
    """
4064
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4065
    node = self.cfg.GetNodeInfo(self.op.node_name)
4066
    assert node is not None
4067

    
4068
    instance_list = self.cfg.GetInstanceList()
4069

    
4070
    masternode = self.cfg.GetMasterNode()
4071
    if node.name == masternode:
4072
      raise errors.OpPrereqError("Node is the master node, failover to another"
4073
                                 " node is required", errors.ECODE_INVAL)
4074

    
4075
    for instance_name in instance_list:
4076
      instance = self.cfg.GetInstanceInfo(instance_name)
4077
      if node.name in instance.all_nodes:
4078
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4079
                                   " please remove first" % instance_name,
4080
                                   errors.ECODE_INVAL)
4081
    self.op.node_name = node.name
4082
    self.node = node
4083

    
4084
  def Exec(self, feedback_fn):
4085
    """Removes the node from the cluster.
4086

4087
    """
4088
    node = self.node
4089
    logging.info("Stopping the node daemon and removing configs from node %s",
4090
                 node.name)