Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ c711d09e

History | View | Annotate | Download (434.7 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 LUClusterVerify.
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 (LUClusterVerify.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 (LUClusterVerify.ETYPE_WARNING, fnamemsg)
1283
  elif errcode == utils.CERT_ERROR:
1284
    return (LUClusterVerify.ETYPE_ERROR, fnamemsg)
1285

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

    
1288

    
1289
class LUClusterVerify(LogicalUnit):
1290
  """Verifies the cluster status.
1291

1292
  """
1293
  HPATH = "cluster-verify"
1294
  HTYPE = constants.HTYPE_CLUSTER
1295
  REQ_BGL = False
1296

    
1297
  TCLUSTER = "cluster"
1298
  TNODE = "node"
1299
  TINSTANCE = "instance"
1300

    
1301
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1302
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1303
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1304
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1305
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1306
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1307
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1308
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1309
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1310
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1311
  ENODEDRBD = (TNODE, "ENODEDRBD")
1312
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1313
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1314
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1315
  ENODEHV = (TNODE, "ENODEHV")
1316
  ENODELVM = (TNODE, "ENODELVM")
1317
  ENODEN1 = (TNODE, "ENODEN1")
1318
  ENODENET = (TNODE, "ENODENET")
1319
  ENODEOS = (TNODE, "ENODEOS")
1320
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1321
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1322
  ENODERPC = (TNODE, "ENODERPC")
1323
  ENODESSH = (TNODE, "ENODESSH")
1324
  ENODEVERSION = (TNODE, "ENODEVERSION")
1325
  ENODESETUP = (TNODE, "ENODESETUP")
1326
  ENODETIME = (TNODE, "ENODETIME")
1327
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1328

    
1329
  ETYPE_FIELD = "code"
1330
  ETYPE_ERROR = "ERROR"
1331
  ETYPE_WARNING = "WARNING"
1332

    
1333
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1334

    
1335
  class NodeImage(object):
1336
    """A class representing the logical and physical status of a node.
1337

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

1366
    """
1367
    def __init__(self, offline=False, name=None, vm_capable=True):
1368
      self.name = name
1369
      self.volumes = {}
1370
      self.instances = []
1371
      self.pinst = []
1372
      self.sinst = []
1373
      self.sbp = {}
1374
      self.mfree = 0
1375
      self.dfree = 0
1376
      self.offline = offline
1377
      self.vm_capable = vm_capable
1378
      self.rpc_fail = False
1379
      self.lvm_fail = False
1380
      self.hyp_fail = False
1381
      self.ghost = False
1382
      self.os_fail = False
1383
      self.oslist = {}
1384

    
1385
  def ExpandNames(self):
1386
    self.needed_locks = {
1387
      locking.LEVEL_NODE: locking.ALL_SET,
1388
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1389
    }
1390
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1391

    
1392
  def CheckPrereq(self):
1393
    self.all_node_info = self.cfg.GetAllNodesInfo()
1394
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1395
    self.my_node_names = utils.NiceSort(list(self.all_node_info))
1396
    self.my_node_info = self.all_node_info
1397
    self.my_inst_names = utils.NiceSort(list(self.all_inst_info))
1398
    self.my_inst_info = self.all_inst_info
1399

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

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

1406
    This must be called only from Exec and functions called from Exec.
1407

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

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

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

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

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

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

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

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

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

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

    
1480
    # node seems compatible, we can actually try to look into its results
1481

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

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

    
1496
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1497
    if ninfo.vm_capable and isinstance(hvp_result, list):
1498
      for item, hv_name, hv_result in hvp_result:
1499
        _ErrorIf(True, self.ENODEHV, node,
1500
                 "hypervisor %s parameter verify failure (source %s): %s",
1501
                 hv_name, item, hv_result)
1502

    
1503
    test = nresult.get(constants.NV_NODESETUP,
1504
                       ["Missing NODESETUP results"])
1505
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1506
             "; ".join(test))
1507

    
1508
    return True
1509

    
1510
  def _VerifyNodeTime(self, ninfo, nresult,
1511
                      nvinfo_starttime, nvinfo_endtime):
1512
    """Check the node time.
1513

1514
    @type ninfo: L{objects.Node}
1515
    @param ninfo: the node to check
1516
    @param nresult: the remote results for the node
1517
    @param nvinfo_starttime: the start time of the RPC call
1518
    @param nvinfo_endtime: the end time of the RPC call
1519

1520
    """
1521
    node = ninfo.name
1522
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1523

    
1524
    ntime = nresult.get(constants.NV_TIME, None)
1525
    try:
1526
      ntime_merged = utils.MergeTime(ntime)
1527
    except (ValueError, TypeError):
1528
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1529
      return
1530

    
1531
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1532
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1533
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1534
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1535
    else:
1536
      ntime_diff = None
1537

    
1538
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1539
             "Node time diverges by at least %s from master node time",
1540
             ntime_diff)
1541

    
1542
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1543
    """Check the node LVM results.
1544

1545
    @type ninfo: L{objects.Node}
1546
    @param ninfo: the node to check
1547
    @param nresult: the remote results for the node
1548
    @param vg_name: the configured VG name
1549

1550
    """
1551
    if vg_name is None:
1552
      return
1553

    
1554
    node = ninfo.name
1555
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1556

    
1557
    # checks vg existence and size > 20G
1558
    vglist = nresult.get(constants.NV_VGLIST, None)
1559
    test = not vglist
1560
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1561
    if not test:
1562
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1563
                                            constants.MIN_VG_SIZE)
1564
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1565

    
1566
    # check pv names
1567
    pvlist = nresult.get(constants.NV_PVLIST, None)
1568
    test = pvlist is None
1569
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1570
    if not test:
1571
      # check that ':' is not present in PV names, since it's a
1572
      # special character for lvcreate (denotes the range of PEs to
1573
      # use on the PV)
1574
      for _, pvname, owner_vg in pvlist:
1575
        test = ":" in pvname
1576
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1577
                 " '%s' of VG '%s'", pvname, owner_vg)
1578

    
1579
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1580
    """Check the node bridges.
1581

1582
    @type ninfo: L{objects.Node}
1583
    @param ninfo: the node to check
1584
    @param nresult: the remote results for the node
1585
    @param bridges: the expected list of bridges
1586

1587
    """
1588
    if not bridges:
1589
      return
1590

    
1591
    node = ninfo.name
1592
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1593

    
1594
    missing = nresult.get(constants.NV_BRIDGES, None)
1595
    test = not isinstance(missing, list)
1596
    _ErrorIf(test, self.ENODENET, node,
1597
             "did not return valid bridge information")
1598
    if not test:
1599
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1600
               utils.CommaJoin(sorted(missing)))
1601

    
1602
  def _VerifyNodeNetwork(self, ninfo, nresult):
1603
    """Check the node network connectivity results.
1604

1605
    @type ninfo: L{objects.Node}
1606
    @param ninfo: the node to check
1607
    @param nresult: the remote results for the node
1608

1609
    """
1610
    node = ninfo.name
1611
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1612

    
1613
    test = constants.NV_NODELIST not in nresult
1614
    _ErrorIf(test, self.ENODESSH, node,
1615
             "node hasn't returned node ssh connectivity data")
1616
    if not test:
1617
      if nresult[constants.NV_NODELIST]:
1618
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1619
          _ErrorIf(True, self.ENODESSH, node,
1620
                   "ssh communication with node '%s': %s", a_node, a_msg)
1621

    
1622
    test = constants.NV_NODENETTEST not in nresult
1623
    _ErrorIf(test, self.ENODENET, node,
1624
             "node hasn't returned node tcp connectivity data")
1625
    if not test:
1626
      if nresult[constants.NV_NODENETTEST]:
1627
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1628
        for anode in nlist:
1629
          _ErrorIf(True, self.ENODENET, node,
1630
                   "tcp communication with node '%s': %s",
1631
                   anode, nresult[constants.NV_NODENETTEST][anode])
1632

    
1633
    test = constants.NV_MASTERIP not in nresult
1634
    _ErrorIf(test, self.ENODENET, node,
1635
             "node hasn't returned node master IP reachability data")
1636
    if not test:
1637
      if not nresult[constants.NV_MASTERIP]:
1638
        if node == self.master_node:
1639
          msg = "the master node cannot reach the master IP (not configured?)"
1640
        else:
1641
          msg = "cannot reach the master IP"
1642
        _ErrorIf(True, self.ENODENET, node, msg)
1643

    
1644
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1645
                      diskstatus):
1646
    """Verify an instance.
1647

1648
    This function checks to see if the required block devices are
1649
    available on the instance's node.
1650

1651
    """
1652
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1653
    node_current = instanceconfig.primary_node
1654

    
1655
    node_vol_should = {}
1656
    instanceconfig.MapLVsByNode(node_vol_should)
1657

    
1658
    for node in node_vol_should:
1659
      n_img = node_image[node]
1660
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1661
        # ignore missing volumes on offline or broken nodes
1662
        continue
1663
      for volume in node_vol_should[node]:
1664
        test = volume not in n_img.volumes
1665
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1666
                 "volume %s missing on node %s", volume, node)
1667

    
1668
    if instanceconfig.admin_up:
1669
      pri_img = node_image[node_current]
1670
      test = instance not in pri_img.instances and not pri_img.offline
1671
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1672
               "instance not running on its primary node %s",
1673
               node_current)
1674

    
1675
    for node, n_img in node_image.items():
1676
      if node != node_current:
1677
        test = instance in n_img.instances
1678
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1679
                 "instance should not run on node %s", node)
1680

    
1681
    diskdata = [(nname, success, status, idx)
1682
                for (nname, disks) in diskstatus.items()
1683
                for idx, (success, status) in enumerate(disks)]
1684

    
1685
    for nname, success, bdev_status, idx in diskdata:
1686
      # the 'ghost node' construction in Exec() ensures that we have a
1687
      # node here
1688
      snode = node_image[nname]
1689
      bad_snode = snode.ghost or snode.offline
1690
      _ErrorIf(instanceconfig.admin_up and not success and not bad_snode,
1691
               self.EINSTANCEFAULTYDISK, instance,
1692
               "couldn't retrieve status for disk/%s on %s: %s",
1693
               idx, nname, bdev_status)
1694
      _ErrorIf((instanceconfig.admin_up and success and
1695
                bdev_status.ldisk_status == constants.LDS_FAULTY),
1696
               self.EINSTANCEFAULTYDISK, instance,
1697
               "disk/%s on %s is faulty", idx, nname)
1698

    
1699
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1700
    """Verify if there are any unknown volumes in the cluster.
1701

1702
    The .os, .swap and backup volumes are ignored. All other volumes are
1703
    reported as unknown.
1704

1705
    @type reserved: L{ganeti.utils.FieldSet}
1706
    @param reserved: a FieldSet of reserved volume names
1707

1708
    """
1709
    for node, n_img in node_image.items():
1710
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1711
        # skip non-healthy nodes
1712
        continue
1713
      for volume in n_img.volumes:
1714
        test = ((node not in node_vol_should or
1715
                volume not in node_vol_should[node]) and
1716
                not reserved.Matches(volume))
1717
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1718
                      "volume %s is unknown", volume)
1719

    
1720
  def _VerifyOrphanInstances(self, instancelist, node_image):
1721
    """Verify the list of running instances.
1722

1723
    This checks what instances are running but unknown to the cluster.
1724

1725
    """
1726
    for node, n_img in node_image.items():
1727
      for o_inst in n_img.instances:
1728
        test = o_inst not in instancelist
1729
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1730
                      "instance %s on node %s should not exist", o_inst, node)
1731

    
1732
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1733
    """Verify N+1 Memory Resilience.
1734

1735
    Check that if one single node dies we can still start all the
1736
    instances it was primary for.
1737

1738
    """
1739
    cluster_info = self.cfg.GetClusterInfo()
1740
    for node, n_img in node_image.items():
1741
      # This code checks that every node which is now listed as
1742
      # secondary has enough memory to host all instances it is
1743
      # supposed to should a single other node in the cluster fail.
1744
      # FIXME: not ready for failover to an arbitrary node
1745
      # FIXME: does not support file-backed instances
1746
      # WARNING: we currently take into account down instances as well
1747
      # as up ones, considering that even if they're down someone
1748
      # might want to start them even in the event of a node failure.
1749
      if n_img.offline:
1750
        # we're skipping offline nodes from the N+1 warning, since
1751
        # most likely we don't have good memory infromation from them;
1752
        # we already list instances living on such nodes, and that's
1753
        # enough warning
1754
        continue
1755
      for prinode, instances in n_img.sbp.items():
1756
        needed_mem = 0
1757
        for instance in instances:
1758
          bep = cluster_info.FillBE(instance_cfg[instance])
1759
          if bep[constants.BE_AUTO_BALANCE]:
1760
            needed_mem += bep[constants.BE_MEMORY]
1761
        test = n_img.mfree < needed_mem
1762
        self._ErrorIf(test, self.ENODEN1, node,
1763
                      "not enough memory to accomodate instance failovers"
1764
                      " should node %s fail (%dMiB needed, %dMiB available)",
1765
                      prinode, needed_mem, n_img.mfree)
1766

    
1767
  @classmethod
1768
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1769
                   (files_all, files_all_opt, files_mc, files_vm)):
1770
    """Verifies file checksums collected from all nodes.
1771

1772
    @param errorif: Callback for reporting errors
1773
    @param nodeinfo: List of L{objects.Node} objects
1774
    @param master_node: Name of master node
1775
    @param all_nvinfo: RPC results
1776

1777
    """
1778
    node_names = frozenset(node.name for node in nodeinfo)
1779

    
1780
    assert master_node in node_names
1781
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1782
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1783
           "Found file listed in more than one file list"
1784

    
1785
    # Define functions determining which nodes to consider for a file
1786
    file2nodefn = dict([(filename, fn)
1787
      for (files, fn) in [(files_all, None),
1788
                          (files_all_opt, None),
1789
                          (files_mc, lambda node: (node.master_candidate or
1790
                                                   node.name == master_node)),
1791
                          (files_vm, lambda node: node.vm_capable)]
1792
      for filename in files])
1793

    
1794
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1795

    
1796
    for node in nodeinfo:
1797
      nresult = all_nvinfo[node.name]
1798

    
1799
      if nresult.fail_msg or not nresult.payload:
1800
        node_files = None
1801
      else:
1802
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1803

    
1804
      test = not (node_files and isinstance(node_files, dict))
1805
      errorif(test, cls.ENODEFILECHECK, node.name,
1806
              "Node did not return file checksum data")
1807
      if test:
1808
        continue
1809

    
1810
      for (filename, checksum) in node_files.items():
1811
        # Check if the file should be considered for a node
1812
        fn = file2nodefn[filename]
1813
        if fn is None or fn(node):
1814
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1815

    
1816
    for (filename, checksums) in fileinfo.items():
1817
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
1818

    
1819
      # Nodes having the file
1820
      with_file = frozenset(node_name
1821
                            for nodes in fileinfo[filename].values()
1822
                            for node_name in nodes)
1823

    
1824
      # Nodes missing file
1825
      missing_file = node_names - with_file
1826

    
1827
      if filename in files_all_opt:
1828
        # All or no nodes
1829
        errorif(missing_file and missing_file != node_names,
1830
                cls.ECLUSTERFILECHECK, None,
1831
                "File %s is optional, but it must exist on all or no nodes (not"
1832
                " found on %s)",
1833
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
1834
      else:
1835
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
1836
                "File %s is missing from node(s) %s", filename,
1837
                utils.CommaJoin(utils.NiceSort(missing_file)))
1838

    
1839
      # See if there are multiple versions of the file
1840
      test = len(checksums) > 1
1841
      if test:
1842
        variants = ["variant %s on %s" %
1843
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
1844
                    for (idx, (checksum, nodes)) in
1845
                      enumerate(sorted(checksums.items()))]
1846
      else:
1847
        variants = []
1848

    
1849
      errorif(test, cls.ECLUSTERFILECHECK, None,
1850
              "File %s found with %s different checksums (%s)",
1851
              filename, len(checksums), "; ".join(variants))
1852

    
1853
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1854
                      drbd_map):
1855
    """Verifies and the node DRBD status.
1856

1857
    @type ninfo: L{objects.Node}
1858
    @param ninfo: the node to check
1859
    @param nresult: the remote results for the node
1860
    @param instanceinfo: the dict of instances
1861
    @param drbd_helper: the configured DRBD usermode helper
1862
    @param drbd_map: the DRBD map as returned by
1863
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1864

1865
    """
1866
    node = ninfo.name
1867
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1868

    
1869
    if drbd_helper:
1870
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1871
      test = (helper_result == None)
1872
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1873
               "no drbd usermode helper returned")
1874
      if helper_result:
1875
        status, payload = helper_result
1876
        test = not status
1877
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1878
                 "drbd usermode helper check unsuccessful: %s", payload)
1879
        test = status and (payload != drbd_helper)
1880
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1881
                 "wrong drbd usermode helper: %s", payload)
1882

    
1883
    # compute the DRBD minors
1884
    node_drbd = {}
1885
    for minor, instance in drbd_map[node].items():
1886
      test = instance not in instanceinfo
1887
      _ErrorIf(test, self.ECLUSTERCFG, None,
1888
               "ghost instance '%s' in temporary DRBD map", instance)
1889
        # ghost instance should not be running, but otherwise we
1890
        # don't give double warnings (both ghost instance and
1891
        # unallocated minor in use)
1892
      if test:
1893
        node_drbd[minor] = (instance, False)
1894
      else:
1895
        instance = instanceinfo[instance]
1896
        node_drbd[minor] = (instance.name, instance.admin_up)
1897

    
1898
    # and now check them
1899
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1900
    test = not isinstance(used_minors, (tuple, list))
1901
    _ErrorIf(test, self.ENODEDRBD, node,
1902
             "cannot parse drbd status file: %s", str(used_minors))
1903
    if test:
1904
      # we cannot check drbd status
1905
      return
1906

    
1907
    for minor, (iname, must_exist) in node_drbd.items():
1908
      test = minor not in used_minors and must_exist
1909
      _ErrorIf(test, self.ENODEDRBD, node,
1910
               "drbd minor %d of instance %s is not active", minor, iname)
1911
    for minor in used_minors:
1912
      test = minor not in node_drbd
1913
      _ErrorIf(test, self.ENODEDRBD, node,
1914
               "unallocated drbd minor %d is in use", minor)
1915

    
1916
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1917
    """Builds the node OS structures.
1918

1919
    @type ninfo: L{objects.Node}
1920
    @param ninfo: the node to check
1921
    @param nresult: the remote results for the node
1922
    @param nimg: the node image object
1923

1924
    """
1925
    node = ninfo.name
1926
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1927

    
1928
    remote_os = nresult.get(constants.NV_OSLIST, None)
1929
    test = (not isinstance(remote_os, list) or
1930
            not compat.all(isinstance(v, list) and len(v) == 7
1931
                           for v in remote_os))
1932

    
1933
    _ErrorIf(test, self.ENODEOS, node,
1934
             "node hasn't returned valid OS data")
1935

    
1936
    nimg.os_fail = test
1937

    
1938
    if test:
1939
      return
1940

    
1941
    os_dict = {}
1942

    
1943
    for (name, os_path, status, diagnose,
1944
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1945

    
1946
      if name not in os_dict:
1947
        os_dict[name] = []
1948

    
1949
      # parameters is a list of lists instead of list of tuples due to
1950
      # JSON lacking a real tuple type, fix it:
1951
      parameters = [tuple(v) for v in parameters]
1952
      os_dict[name].append((os_path, status, diagnose,
1953
                            set(variants), set(parameters), set(api_ver)))
1954

    
1955
    nimg.oslist = os_dict
1956

    
1957
  def _VerifyNodeOS(self, ninfo, nimg, base):
1958
    """Verifies the node OS list.
1959

1960
    @type ninfo: L{objects.Node}
1961
    @param ninfo: the node to check
1962
    @param nimg: the node image object
1963
    @param base: the 'template' node we match against (e.g. from the master)
1964

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

    
1969
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1970

    
1971
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
1972
    for os_name, os_data in nimg.oslist.items():
1973
      assert os_data, "Empty OS status for OS %s?!" % os_name
1974
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1975
      _ErrorIf(not f_status, self.ENODEOS, node,
1976
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1977
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1978
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1979
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1980
      # this will catched in backend too
1981
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1982
               and not f_var, self.ENODEOS, node,
1983
               "OS %s with API at least %d does not declare any variant",
1984
               os_name, constants.OS_API_V15)
1985
      # comparisons with the 'base' image
1986
      test = os_name not in base.oslist
1987
      _ErrorIf(test, self.ENODEOS, node,
1988
               "Extra OS %s not present on reference node (%s)",
1989
               os_name, base.name)
1990
      if test:
1991
        continue
1992
      assert base.oslist[os_name], "Base node has empty OS status?"
1993
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1994
      if not b_status:
1995
        # base OS is invalid, skipping
1996
        continue
1997
      for kind, a, b in [("API version", f_api, b_api),
1998
                         ("variants list", f_var, b_var),
1999
                         ("parameters", beautify_params(f_param),
2000
                          beautify_params(b_param))]:
2001
        _ErrorIf(a != b, self.ENODEOS, node,
2002
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
2003
                 kind, os_name, base.name,
2004
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
2005

    
2006
    # check any missing OSes
2007
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2008
    _ErrorIf(missing, self.ENODEOS, node,
2009
             "OSes present on reference node %s but missing on this node: %s",
2010
             base.name, utils.CommaJoin(missing))
2011

    
2012
  def _VerifyOob(self, ninfo, nresult):
2013
    """Verifies out of band functionality of a node.
2014

2015
    @type ninfo: L{objects.Node}
2016
    @param ninfo: the node to check
2017
    @param nresult: the remote results for the node
2018

2019
    """
2020
    node = ninfo.name
2021
    # We just have to verify the paths on master and/or master candidates
2022
    # as the oob helper is invoked on the master
2023
    if ((ninfo.master_candidate or ninfo.master_capable) and
2024
        constants.NV_OOB_PATHS in nresult):
2025
      for path_result in nresult[constants.NV_OOB_PATHS]:
2026
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2027

    
2028
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2029
    """Verifies and updates the node volume data.
2030

2031
    This function will update a L{NodeImage}'s internal structures
2032
    with data from the remote call.
2033

2034
    @type ninfo: L{objects.Node}
2035
    @param ninfo: the node to check
2036
    @param nresult: the remote results for the node
2037
    @param nimg: the node image object
2038
    @param vg_name: the configured VG name
2039

2040
    """
2041
    node = ninfo.name
2042
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2043

    
2044
    nimg.lvm_fail = True
2045
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2046
    if vg_name is None:
2047
      pass
2048
    elif isinstance(lvdata, basestring):
2049
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2050
               utils.SafeEncode(lvdata))
2051
    elif not isinstance(lvdata, dict):
2052
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2053
    else:
2054
      nimg.volumes = lvdata
2055
      nimg.lvm_fail = False
2056

    
2057
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2058
    """Verifies and updates the node instance list.
2059

2060
    If the listing was successful, then updates this node's instance
2061
    list. Otherwise, it marks the RPC call as failed for the instance
2062
    list key.
2063

2064
    @type ninfo: L{objects.Node}
2065
    @param ninfo: the node to check
2066
    @param nresult: the remote results for the node
2067
    @param nimg: the node image object
2068

2069
    """
2070
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2071
    test = not isinstance(idata, list)
2072
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2073
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2074
    if test:
2075
      nimg.hyp_fail = True
2076
    else:
2077
      nimg.instances = idata
2078

    
2079
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2080
    """Verifies and computes a node information map
2081

2082
    @type ninfo: L{objects.Node}
2083
    @param ninfo: the node to check
2084
    @param nresult: the remote results for the node
2085
    @param nimg: the node image object
2086
    @param vg_name: the configured VG name
2087

2088
    """
2089
    node = ninfo.name
2090
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2091

    
2092
    # try to read free memory (from the hypervisor)
2093
    hv_info = nresult.get(constants.NV_HVINFO, None)
2094
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2095
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2096
    if not test:
2097
      try:
2098
        nimg.mfree = int(hv_info["memory_free"])
2099
      except (ValueError, TypeError):
2100
        _ErrorIf(True, self.ENODERPC, node,
2101
                 "node returned invalid nodeinfo, check hypervisor")
2102

    
2103
    # FIXME: devise a free space model for file based instances as well
2104
    if vg_name is not None:
2105
      test = (constants.NV_VGLIST not in nresult or
2106
              vg_name not in nresult[constants.NV_VGLIST])
2107
      _ErrorIf(test, self.ENODELVM, node,
2108
               "node didn't return data for the volume group '%s'"
2109
               " - it is either missing or broken", vg_name)
2110
      if not test:
2111
        try:
2112
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2113
        except (ValueError, TypeError):
2114
          _ErrorIf(True, self.ENODERPC, node,
2115
                   "node returned invalid LVM info, check LVM status")
2116

    
2117
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2118
    """Gets per-disk status information for all instances.
2119

2120
    @type nodelist: list of strings
2121
    @param nodelist: Node names
2122
    @type node_image: dict of (name, L{objects.Node})
2123
    @param node_image: Node objects
2124
    @type instanceinfo: dict of (name, L{objects.Instance})
2125
    @param instanceinfo: Instance objects
2126
    @rtype: {instance: {node: [(succes, payload)]}}
2127
    @return: a dictionary of per-instance dictionaries with nodes as
2128
        keys and disk information as values; the disk information is a
2129
        list of tuples (success, payload)
2130

2131
    """
2132
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2133

    
2134
    node_disks = {}
2135
    node_disks_devonly = {}
2136
    diskless_instances = set()
2137
    diskless = constants.DT_DISKLESS
2138

    
2139
    for nname in nodelist:
2140
      node_instances = list(itertools.chain(node_image[nname].pinst,
2141
                                            node_image[nname].sinst))
2142
      diskless_instances.update(inst for inst in node_instances
2143
                                if instanceinfo[inst].disk_template == diskless)
2144
      disks = [(inst, disk)
2145
               for inst in node_instances
2146
               for disk in instanceinfo[inst].disks]
2147

    
2148
      if not disks:
2149
        # No need to collect data
2150
        continue
2151

    
2152
      node_disks[nname] = disks
2153

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

    
2158
      for dev in devonly:
2159
        self.cfg.SetDiskID(dev, nname)
2160

    
2161
      node_disks_devonly[nname] = devonly
2162

    
2163
    assert len(node_disks) == len(node_disks_devonly)
2164

    
2165
    # Collect data from all nodes with disks
2166
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2167
                                                          node_disks_devonly)
2168

    
2169
    assert len(result) == len(node_disks)
2170

    
2171
    instdisk = {}
2172

    
2173
    for (nname, nres) in result.items():
2174
      disks = node_disks[nname]
2175

    
2176
      if nres.offline:
2177
        # No data from this node
2178
        data = len(disks) * [(False, "node offline")]
2179
      else:
2180
        msg = nres.fail_msg
2181
        _ErrorIf(msg, self.ENODERPC, nname,
2182
                 "while getting disk information: %s", msg)
2183
        if msg:
2184
          # No data from this node
2185
          data = len(disks) * [(False, msg)]
2186
        else:
2187
          data = []
2188
          for idx, i in enumerate(nres.payload):
2189
            if isinstance(i, (tuple, list)) and len(i) == 2:
2190
              data.append(i)
2191
            else:
2192
              logging.warning("Invalid result from node %s, entry %d: %s",
2193
                              nname, idx, i)
2194
              data.append((False, "Invalid result from the remote node"))
2195

    
2196
      for ((inst, _), status) in zip(disks, data):
2197
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2198

    
2199
    # Add empty entries for diskless instances.
2200
    for inst in diskless_instances:
2201
      assert inst not in instdisk
2202
      instdisk[inst] = {}
2203

    
2204
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2205
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2206
                      compat.all(isinstance(s, (tuple, list)) and
2207
                                 len(s) == 2 for s in statuses)
2208
                      for inst, nnames in instdisk.items()
2209
                      for nname, statuses in nnames.items())
2210
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2211

    
2212
    return instdisk
2213

    
2214
  def _VerifyHVP(self, hvp_data):
2215
    """Verifies locally the syntax of the hypervisor parameters.
2216

2217
    """
2218
    for item, hv_name, hv_params in hvp_data:
2219
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2220
             (item, hv_name))
2221
      try:
2222
        hv_class = hypervisor.GetHypervisor(hv_name)
2223
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2224
        hv_class.CheckParameterSyntax(hv_params)
2225
      except errors.GenericError, err:
2226
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2227

    
2228
  def BuildHooksEnv(self):
2229
    """Build hooks env.
2230

2231
    Cluster-Verify hooks just ran in the post phase and their failure makes
2232
    the output be logged in the verify output and the verification to fail.
2233

2234
    """
2235
    env = {
2236
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2237
      }
2238

    
2239
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2240
               for node in self.my_node_info.values())
2241

    
2242
    return env
2243

    
2244
  def BuildHooksNodes(self):
2245
    """Build hooks nodes.
2246

2247
    """
2248
    assert self.my_node_names, ("Node list not gathered,"
2249
      " has CheckPrereq been executed?")
2250
    return ([], self.my_node_names)
2251

    
2252
  def Exec(self, feedback_fn):
2253
    """Verify integrity of cluster, performing various test on nodes.
2254

2255
    """
2256
    # This method has too many local variables. pylint: disable-msg=R0914
2257
    self.bad = False
2258
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2259
    verbose = self.op.verbose
2260
    self._feedback_fn = feedback_fn
2261
    feedback_fn("* Verifying global settings")
2262
    for msg in self.cfg.VerifyConfig():
2263
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2264

    
2265
    # Check the cluster certificates
2266
    for cert_filename in constants.ALL_CERT_FILES:
2267
      (errcode, msg) = _VerifyCertificate(cert_filename)
2268
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2269

    
2270
    vg_name = self.cfg.GetVGName()
2271
    drbd_helper = self.cfg.GetDRBDHelper()
2272
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2273
    cluster = self.cfg.GetClusterInfo()
2274
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2275
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2276

    
2277
    i_non_redundant = [] # Non redundant instances
2278
    i_non_a_balanced = [] # Non auto-balanced instances
2279
    n_offline = 0 # Count of offline nodes
2280
    n_drained = 0 # Count of nodes being drained
2281
    node_vol_should = {}
2282

    
2283
    # FIXME: verify OS list
2284

    
2285
    # File verification
2286
    filemap = _ComputeAncillaryFiles(cluster, False)
2287

    
2288
    # do local checksums
2289
    master_node = self.master_node = self.cfg.GetMasterNode()
2290
    master_ip = self.cfg.GetMasterIP()
2291

    
2292
    # Compute the set of hypervisor parameters
2293
    hvp_data = []
2294
    for hv_name in hypervisors:
2295
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2296
    for os_name, os_hvp in cluster.os_hvp.items():
2297
      for hv_name, hv_params in os_hvp.items():
2298
        if not hv_params:
2299
          continue
2300
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2301
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2302
    # TODO: collapse identical parameter values in a single one
2303
    for instance in self.my_inst_info.values():
2304
      if not instance.hvparams:
2305
        continue
2306
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2307
                       cluster.FillHV(instance)))
2308
    # and verify them locally
2309
    self._VerifyHVP(hvp_data)
2310

    
2311
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2312
    node_verify_param = {
2313
      constants.NV_FILELIST:
2314
        utils.UniqueSequence(filename
2315
                             for files in filemap
2316
                             for filename in files),
2317
      constants.NV_NODELIST: [node.name for node in node_data_list
2318
                              if not node.offline],
2319
      constants.NV_HYPERVISOR: hypervisors,
2320
      constants.NV_HVPARAMS: hvp_data,
2321
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2322
                                 for node in node_data_list
2323
                                 if not node.offline],
2324
      constants.NV_INSTANCELIST: hypervisors,
2325
      constants.NV_VERSION: None,
2326
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2327
      constants.NV_NODESETUP: None,
2328
      constants.NV_TIME: None,
2329
      constants.NV_MASTERIP: (master_node, master_ip),
2330
      constants.NV_OSLIST: None,
2331
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2332
      }
2333

    
2334
    if vg_name is not None:
2335
      node_verify_param[constants.NV_VGLIST] = None
2336
      node_verify_param[constants.NV_LVLIST] = vg_name
2337
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2338
      node_verify_param[constants.NV_DRBDLIST] = None
2339

    
2340
    if drbd_helper:
2341
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2342

    
2343
    # bridge checks
2344
    # FIXME: this needs to be changed per node-group, not cluster-wide
2345
    bridges = set()
2346
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2347
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2348
      bridges.add(default_nicpp[constants.NIC_LINK])
2349
    for instance in instanceinfo.values():
2350
      for nic in instance.nics:
2351
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2352
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2353
          bridges.add(full_nic[constants.NIC_LINK])
2354

    
2355
    if bridges:
2356
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2357

    
2358
    # Build our expected cluster state
2359
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2360
                                                 name=node.name,
2361
                                                 vm_capable=node.vm_capable))
2362
                      for node in node_data_list)
2363

    
2364
    # Gather OOB paths
2365
    oob_paths = []
2366
    for node in node_data_list:
2367
      path = _SupportsOob(self.cfg, node)
2368
      if path and path not in oob_paths:
2369
        oob_paths.append(path)
2370

    
2371
    if oob_paths:
2372
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2373

    
2374
    for instance in self.my_inst_names:
2375
      inst_config = self.my_inst_info[instance]
2376

    
2377
      for nname in inst_config.all_nodes:
2378
        if nname not in node_image:
2379
          # ghost node
2380
          gnode = self.NodeImage(name=nname)
2381
          gnode.ghost = True
2382
          node_image[nname] = gnode
2383

    
2384
      inst_config.MapLVsByNode(node_vol_should)
2385

    
2386
      pnode = inst_config.primary_node
2387
      node_image[pnode].pinst.append(instance)
2388

    
2389
      for snode in inst_config.secondary_nodes:
2390
        nimg = node_image[snode]
2391
        nimg.sinst.append(instance)
2392
        if pnode not in nimg.sbp:
2393
          nimg.sbp[pnode] = []
2394
        nimg.sbp[pnode].append(instance)
2395

    
2396
    # At this point, we have the in-memory data structures complete,
2397
    # except for the runtime information, which we'll gather next
2398

    
2399
    # Due to the way our RPC system works, exact response times cannot be
2400
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2401
    # time before and after executing the request, we can at least have a time
2402
    # window.
2403
    nvinfo_starttime = time.time()
2404
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2405
                                           node_verify_param,
2406
                                           self.cfg.GetClusterName())
2407
    nvinfo_endtime = time.time()
2408

    
2409
    all_drbd_map = self.cfg.ComputeDRBDMap()
2410

    
2411
    feedback_fn("* Gathering disk information (%s nodes)" %
2412
                len(self.my_node_names))
2413
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2414
                                     self.my_inst_info)
2415

    
2416
    feedback_fn("* Verifying configuration file consistency")
2417
    self._VerifyFiles(_ErrorIf, self.my_node_info.values(), master_node,
2418
                      all_nvinfo, filemap)
2419

    
2420
    feedback_fn("* Verifying node status")
2421

    
2422
    refos_img = None
2423

    
2424
    for node_i in node_data_list:
2425
      node = node_i.name
2426
      nimg = node_image[node]
2427

    
2428
      if node_i.offline:
2429
        if verbose:
2430
          feedback_fn("* Skipping offline node %s" % (node,))
2431
        n_offline += 1
2432
        continue
2433

    
2434
      if node == master_node:
2435
        ntype = "master"
2436
      elif node_i.master_candidate:
2437
        ntype = "master candidate"
2438
      elif node_i.drained:
2439
        ntype = "drained"
2440
        n_drained += 1
2441
      else:
2442
        ntype = "regular"
2443
      if verbose:
2444
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2445

    
2446
      msg = all_nvinfo[node].fail_msg
2447
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2448
      if msg:
2449
        nimg.rpc_fail = True
2450
        continue
2451

    
2452
      nresult = all_nvinfo[node].payload
2453

    
2454
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2455
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2456
      self._VerifyNodeNetwork(node_i, nresult)
2457
      self._VerifyOob(node_i, nresult)
2458

    
2459
      if nimg.vm_capable:
2460
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2461
        self._VerifyNodeDrbd(node_i, nresult, self.my_inst_info, drbd_helper,
2462
                             all_drbd_map)
2463

    
2464
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2465
        self._UpdateNodeInstances(node_i, nresult, nimg)
2466
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2467
        self._UpdateNodeOS(node_i, nresult, nimg)
2468
        if not nimg.os_fail:
2469
          if refos_img is None:
2470
            refos_img = nimg
2471
          self._VerifyNodeOS(node_i, nimg, refos_img)
2472
        self._VerifyNodeBridges(node_i, nresult, bridges)
2473

    
2474
    feedback_fn("* Verifying instance status")
2475
    for instance in self.my_inst_names:
2476
      if verbose:
2477
        feedback_fn("* Verifying instance %s" % instance)
2478
      inst_config = self.my_inst_info[instance]
2479
      self._VerifyInstance(instance, inst_config, node_image,
2480
                           instdisk[instance])
2481
      inst_nodes_offline = []
2482

    
2483
      pnode = inst_config.primary_node
2484
      pnode_img = node_image[pnode]
2485
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2486
               self.ENODERPC, pnode, "instance %s, connection to"
2487
               " primary node failed", instance)
2488

    
2489
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2490
               self.EINSTANCEBADNODE, instance,
2491
               "instance is marked as running and lives on offline node %s",
2492
               inst_config.primary_node)
2493

    
2494
      # If the instance is non-redundant we cannot survive losing its primary
2495
      # node, so we are not N+1 compliant. On the other hand we have no disk
2496
      # templates with more than one secondary so that situation is not well
2497
      # supported either.
2498
      # FIXME: does not support file-backed instances
2499
      if not inst_config.secondary_nodes:
2500
        i_non_redundant.append(instance)
2501

    
2502
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2503
               instance, "instance has multiple secondary nodes: %s",
2504
               utils.CommaJoin(inst_config.secondary_nodes),
2505
               code=self.ETYPE_WARNING)
2506

    
2507
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2508
        pnode = inst_config.primary_node
2509
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2510
        instance_groups = {}
2511

    
2512
        for node in instance_nodes:
2513
          instance_groups.setdefault(self.my_node_info[node].group,
2514
                                     []).append(node)
2515

    
2516
        pretty_list = [
2517
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2518
          # Sort so that we always list the primary node first.
2519
          for group, nodes in sorted(instance_groups.items(),
2520
                                     key=lambda (_, nodes): pnode in nodes,
2521
                                     reverse=True)]
2522

    
2523
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2524
                      instance, "instance has primary and secondary nodes in"
2525
                      " different groups: %s", utils.CommaJoin(pretty_list),
2526
                      code=self.ETYPE_WARNING)
2527

    
2528
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2529
        i_non_a_balanced.append(instance)
2530

    
2531
      for snode in inst_config.secondary_nodes:
2532
        s_img = node_image[snode]
2533
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2534
                 "instance %s, connection to secondary node failed", instance)
2535

    
2536
        if s_img.offline:
2537
          inst_nodes_offline.append(snode)
2538

    
2539
      # warn that the instance lives on offline nodes
2540
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2541
               "instance has offline secondary node(s) %s",
2542
               utils.CommaJoin(inst_nodes_offline))
2543
      # ... or ghost/non-vm_capable nodes
2544
      for node in inst_config.all_nodes:
2545
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2546
                 "instance lives on ghost node %s", node)
2547
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2548
                 instance, "instance lives on non-vm_capable node %s", node)
2549

    
2550
    feedback_fn("* Verifying orphan volumes")
2551
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2552
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2553

    
2554
    feedback_fn("* Verifying orphan instances")
2555
    self._VerifyOrphanInstances(self.my_inst_names, node_image)
2556

    
2557
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2558
      feedback_fn("* Verifying N+1 Memory redundancy")
2559
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2560

    
2561
    feedback_fn("* Other Notes")
2562
    if i_non_redundant:
2563
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2564
                  % len(i_non_redundant))
2565

    
2566
    if i_non_a_balanced:
2567
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2568
                  % len(i_non_a_balanced))
2569

    
2570
    if n_offline:
2571
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2572

    
2573
    if n_drained:
2574
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2575

    
2576
    return not self.bad
2577

    
2578
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2579
    """Analyze the post-hooks' result
2580

2581
    This method analyses the hook result, handles it, and sends some
2582
    nicely-formatted feedback back to the user.
2583

2584
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2585
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2586
    @param hooks_results: the results of the multi-node hooks rpc call
2587
    @param feedback_fn: function used send feedback back to the caller
2588
    @param lu_result: previous Exec result
2589
    @return: the new Exec result, based on the previous result
2590
        and hook results
2591

2592
    """
2593
    # We only really run POST phase hooks, and are only interested in
2594
    # their results
2595
    if phase == constants.HOOKS_PHASE_POST:
2596
      # Used to change hooks' output to proper indentation
2597
      feedback_fn("* Hooks Results")
2598
      assert hooks_results, "invalid result from hooks"
2599

    
2600
      for node_name in hooks_results:
2601
        res = hooks_results[node_name]
2602
        msg = res.fail_msg
2603
        test = msg and not res.offline
2604
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2605
                      "Communication failure in hooks execution: %s", msg)
2606
        if res.offline or msg:
2607
          # No need to investigate payload if node is offline or gave an error.
2608
          # override manually lu_result here as _ErrorIf only
2609
          # overrides self.bad
2610
          lu_result = 1
2611
          continue
2612
        for script, hkr, output in res.payload:
2613
          test = hkr == constants.HKR_FAIL
2614
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2615
                        "Script %s failed, output:", script)
2616
          if test:
2617
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2618
            feedback_fn("%s" % output)
2619
            lu_result = 0
2620

    
2621
      return lu_result
2622

    
2623

    
2624
class LUClusterVerifyDisks(NoHooksLU):
2625
  """Verifies the cluster disks status.
2626

2627
  """
2628
  REQ_BGL = False
2629

    
2630
  def ExpandNames(self):
2631
    self.needed_locks = {
2632
      locking.LEVEL_NODE: locking.ALL_SET,
2633
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2634
    }
2635
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2636

    
2637
  def Exec(self, feedback_fn):
2638
    """Verify integrity of cluster disks.
2639

2640
    @rtype: tuple of three items
2641
    @return: a tuple of (dict of node-to-node_error, list of instances
2642
        which need activate-disks, dict of instance: (node, volume) for
2643
        missing volumes
2644

2645
    """
2646
    result = res_nodes, res_instances, res_missing = {}, [], {}
2647

    
2648
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2649
    instances = self.cfg.GetAllInstancesInfo().values()
2650

    
2651
    nv_dict = {}
2652
    for inst in instances:
2653
      inst_lvs = {}
2654
      if not inst.admin_up:
2655
        continue
2656
      inst.MapLVsByNode(inst_lvs)
2657
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2658
      for node, vol_list in inst_lvs.iteritems():
2659
        for vol in vol_list:
2660
          nv_dict[(node, vol)] = inst
2661

    
2662
    if not nv_dict:
2663
      return result
2664

    
2665
    node_lvs = self.rpc.call_lv_list(nodes, [])
2666
    for node, node_res in node_lvs.items():
2667
      if node_res.offline:
2668
        continue
2669
      msg = node_res.fail_msg
2670
      if msg:
2671
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2672
        res_nodes[node] = msg
2673
        continue
2674

    
2675
      lvs = node_res.payload
2676
      for lv_name, (_, _, lv_online) in lvs.items():
2677
        inst = nv_dict.pop((node, lv_name), None)
2678
        if (not lv_online and inst is not None
2679
            and inst.name not in res_instances):
2680
          res_instances.append(inst.name)
2681

    
2682
    # any leftover items in nv_dict are missing LVs, let's arrange the
2683
    # data better
2684
    for key, inst in nv_dict.iteritems():
2685
      if inst.name not in res_missing:
2686
        res_missing[inst.name] = []
2687
      res_missing[inst.name].append(key)
2688

    
2689
    return result
2690

    
2691

    
2692
class LUClusterRepairDiskSizes(NoHooksLU):
2693
  """Verifies the cluster disks sizes.
2694

2695
  """
2696
  REQ_BGL = False
2697

    
2698
  def ExpandNames(self):
2699
    if self.op.instances:
2700
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2701
      self.needed_locks = {
2702
        locking.LEVEL_NODE: [],
2703
        locking.LEVEL_INSTANCE: self.wanted_names,
2704
        }
2705
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2706
    else:
2707
      self.wanted_names = None
2708
      self.needed_locks = {
2709
        locking.LEVEL_NODE: locking.ALL_SET,
2710
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2711
        }
2712
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2713

    
2714
  def DeclareLocks(self, level):
2715
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2716
      self._LockInstancesNodes(primary_only=True)
2717

    
2718
  def CheckPrereq(self):
2719
    """Check prerequisites.
2720

2721
    This only checks the optional instance list against the existing names.
2722

2723
    """
2724
    if self.wanted_names is None:
2725
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2726

    
2727
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2728
                             in self.wanted_names]
2729

    
2730
  def _EnsureChildSizes(self, disk):
2731
    """Ensure children of the disk have the needed disk size.
2732

2733
    This is valid mainly for DRBD8 and fixes an issue where the
2734
    children have smaller disk size.
2735

2736
    @param disk: an L{ganeti.objects.Disk} object
2737

2738
    """
2739
    if disk.dev_type == constants.LD_DRBD8:
2740
      assert disk.children, "Empty children for DRBD8?"
2741
      fchild = disk.children[0]
2742
      mismatch = fchild.size < disk.size
2743
      if mismatch:
2744
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2745
                     fchild.size, disk.size)
2746
        fchild.size = disk.size
2747

    
2748
      # and we recurse on this child only, not on the metadev
2749
      return self._EnsureChildSizes(fchild) or mismatch
2750
    else:
2751
      return False
2752

    
2753
  def Exec(self, feedback_fn):
2754
    """Verify the size of cluster disks.
2755

2756
    """
2757
    # TODO: check child disks too
2758
    # TODO: check differences in size between primary/secondary nodes
2759
    per_node_disks = {}
2760
    for instance in self.wanted_instances:
2761
      pnode = instance.primary_node
2762
      if pnode not in per_node_disks:
2763
        per_node_disks[pnode] = []
2764
      for idx, disk in enumerate(instance.disks):
2765
        per_node_disks[pnode].append((instance, idx, disk))
2766

    
2767
    changed = []
2768
    for node, dskl in per_node_disks.items():
2769
      newl = [v[2].Copy() for v in dskl]
2770
      for dsk in newl:
2771
        self.cfg.SetDiskID(dsk, node)
2772
      result = self.rpc.call_blockdev_getsize(node, newl)
2773
      if result.fail_msg:
2774
        self.LogWarning("Failure in blockdev_getsize call to node"
2775
                        " %s, ignoring", node)
2776
        continue
2777
      if len(result.payload) != len(dskl):
2778
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2779
                        " result.payload=%s", node, len(dskl), result.payload)
2780
        self.LogWarning("Invalid result from node %s, ignoring node results",
2781
                        node)
2782
        continue
2783
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2784
        if size is None:
2785
          self.LogWarning("Disk %d of instance %s did not return size"
2786
                          " information, ignoring", idx, instance.name)
2787
          continue
2788
        if not isinstance(size, (int, long)):
2789
          self.LogWarning("Disk %d of instance %s did not return valid"
2790
                          " size information, ignoring", idx, instance.name)
2791
          continue
2792
        size = size >> 20
2793
        if size != disk.size:
2794
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2795
                       " correcting: recorded %d, actual %d", idx,
2796
                       instance.name, disk.size, size)
2797
          disk.size = size
2798
          self.cfg.Update(instance, feedback_fn)
2799
          changed.append((instance.name, idx, size))
2800
        if self._EnsureChildSizes(disk):
2801
          self.cfg.Update(instance, feedback_fn)
2802
          changed.append((instance.name, idx, disk.size))
2803
    return changed
2804

    
2805

    
2806
class LUClusterRename(LogicalUnit):
2807
  """Rename the cluster.
2808

2809
  """
2810
  HPATH = "cluster-rename"
2811
  HTYPE = constants.HTYPE_CLUSTER
2812

    
2813
  def BuildHooksEnv(self):
2814
    """Build hooks env.
2815

2816
    """
2817
    return {
2818
      "OP_TARGET": self.cfg.GetClusterName(),
2819
      "NEW_NAME": self.op.name,
2820
      }
2821

    
2822
  def BuildHooksNodes(self):
2823
    """Build hooks nodes.
2824

2825
    """
2826
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
2827

    
2828
  def CheckPrereq(self):
2829
    """Verify that the passed name is a valid one.
2830

2831
    """
2832
    hostname = netutils.GetHostname(name=self.op.name,
2833
                                    family=self.cfg.GetPrimaryIPFamily())
2834

    
2835
    new_name = hostname.name
2836
    self.ip = new_ip = hostname.ip
2837
    old_name = self.cfg.GetClusterName()
2838
    old_ip = self.cfg.GetMasterIP()
2839
    if new_name == old_name and new_ip == old_ip:
2840
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2841
                                 " cluster has changed",
2842
                                 errors.ECODE_INVAL)
2843
    if new_ip != old_ip:
2844
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2845
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2846
                                   " reachable on the network" %
2847
                                   new_ip, errors.ECODE_NOTUNIQUE)
2848

    
2849
    self.op.name = new_name
2850

    
2851
  def Exec(self, feedback_fn):
2852
    """Rename the cluster.
2853

2854
    """
2855
    clustername = self.op.name
2856
    ip = self.ip
2857

    
2858
    # shutdown the master IP
2859
    master = self.cfg.GetMasterNode()
2860
    result = self.rpc.call_node_stop_master(master, False)
2861
    result.Raise("Could not disable the master role")
2862

    
2863
    try:
2864
      cluster = self.cfg.GetClusterInfo()
2865
      cluster.cluster_name = clustername
2866
      cluster.master_ip = ip
2867
      self.cfg.Update(cluster, feedback_fn)
2868

    
2869
      # update the known hosts file
2870
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2871
      node_list = self.cfg.GetOnlineNodeList()
2872
      try:
2873
        node_list.remove(master)
2874
      except ValueError:
2875
        pass
2876
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2877
    finally:
2878
      result = self.rpc.call_node_start_master(master, False, False)
2879
      msg = result.fail_msg
2880
      if msg:
2881
        self.LogWarning("Could not re-enable the master role on"
2882
                        " the master, please restart manually: %s", msg)
2883

    
2884
    return clustername
2885

    
2886

    
2887
class LUClusterSetParams(LogicalUnit):
2888
  """Change the parameters of the cluster.
2889

2890
  """
2891
  HPATH = "cluster-modify"
2892
  HTYPE = constants.HTYPE_CLUSTER
2893
  REQ_BGL = False
2894

    
2895
  def CheckArguments(self):
2896
    """Check parameters
2897

2898
    """
2899
    if self.op.uid_pool:
2900
      uidpool.CheckUidPool(self.op.uid_pool)
2901

    
2902
    if self.op.add_uids:
2903
      uidpool.CheckUidPool(self.op.add_uids)
2904

    
2905
    if self.op.remove_uids:
2906
      uidpool.CheckUidPool(self.op.remove_uids)
2907

    
2908
  def ExpandNames(self):
2909
    # FIXME: in the future maybe other cluster params won't require checking on
2910
    # all nodes to be modified.
2911
    self.needed_locks = {
2912
      locking.LEVEL_NODE: locking.ALL_SET,
2913
    }
2914
    self.share_locks[locking.LEVEL_NODE] = 1
2915

    
2916
  def BuildHooksEnv(self):
2917
    """Build hooks env.
2918

2919
    """
2920
    return {
2921
      "OP_TARGET": self.cfg.GetClusterName(),
2922
      "NEW_VG_NAME": self.op.vg_name,
2923
      }
2924

    
2925
  def BuildHooksNodes(self):
2926
    """Build hooks nodes.
2927

2928
    """
2929
    mn = self.cfg.GetMasterNode()
2930
    return ([mn], [mn])
2931

    
2932
  def CheckPrereq(self):
2933
    """Check prerequisites.
2934

2935
    This checks whether the given params don't conflict and
2936
    if the given volume group is valid.
2937

2938
    """
2939
    if self.op.vg_name is not None and not self.op.vg_name:
2940
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2941
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2942
                                   " instances exist", errors.ECODE_INVAL)
2943

    
2944
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2945
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2946
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2947
                                   " drbd-based instances exist",
2948
                                   errors.ECODE_INVAL)
2949

    
2950
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
2951

    
2952
    # if vg_name not None, checks given volume group on all nodes
2953
    if self.op.vg_name:
2954
      vglist = self.rpc.call_vg_list(node_list)
2955
      for node in node_list:
2956
        msg = vglist[node].fail_msg
2957
        if msg:
2958
          # ignoring down node
2959
          self.LogWarning("Error while gathering data on node %s"
2960
                          " (ignoring node): %s", node, msg)
2961
          continue
2962
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2963
                                              self.op.vg_name,
2964
                                              constants.MIN_VG_SIZE)
2965
        if vgstatus:
2966
          raise errors.OpPrereqError("Error on node '%s': %s" %
2967
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2968

    
2969
    if self.op.drbd_helper:
2970
      # checks given drbd helper on all nodes
2971
      helpers = self.rpc.call_drbd_helper(node_list)
2972
      for node in node_list:
2973
        ninfo = self.cfg.GetNodeInfo(node)
2974
        if ninfo.offline:
2975
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2976
          continue
2977
        msg = helpers[node].fail_msg
2978
        if msg:
2979
          raise errors.OpPrereqError("Error checking drbd helper on node"
2980
                                     " '%s': %s" % (node, msg),
2981
                                     errors.ECODE_ENVIRON)
2982
        node_helper = helpers[node].payload
2983
        if node_helper != self.op.drbd_helper:
2984
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2985
                                     (node, node_helper), errors.ECODE_ENVIRON)
2986

    
2987
    self.cluster = cluster = self.cfg.GetClusterInfo()
2988
    # validate params changes
2989
    if self.op.beparams:
2990
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2991
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2992

    
2993
    if self.op.ndparams:
2994
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
2995
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
2996

    
2997
      # TODO: we need a more general way to handle resetting
2998
      # cluster-level parameters to default values
2999
      if self.new_ndparams["oob_program"] == "":
3000
        self.new_ndparams["oob_program"] = \
3001
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3002

    
3003
    if self.op.nicparams:
3004
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3005
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3006
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3007
      nic_errors = []
3008

    
3009
      # check all instances for consistency
3010
      for instance in self.cfg.GetAllInstancesInfo().values():
3011
        for nic_idx, nic in enumerate(instance.nics):
3012
          params_copy = copy.deepcopy(nic.nicparams)
3013
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3014

    
3015
          # check parameter syntax
3016
          try:
3017
            objects.NIC.CheckParameterSyntax(params_filled)
3018
          except errors.ConfigurationError, err:
3019
            nic_errors.append("Instance %s, nic/%d: %s" %
3020
                              (instance.name, nic_idx, err))
3021

    
3022
          # if we're moving instances to routed, check that they have an ip
3023
          target_mode = params_filled[constants.NIC_MODE]
3024
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3025
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3026
                              " address" % (instance.name, nic_idx))
3027
      if nic_errors:
3028
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3029
                                   "\n".join(nic_errors))
3030

    
3031
    # hypervisor list/parameters
3032
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3033
    if self.op.hvparams:
3034
      for hv_name, hv_dict in self.op.hvparams.items():
3035
        if hv_name not in self.new_hvparams:
3036
          self.new_hvparams[hv_name] = hv_dict
3037
        else:
3038
          self.new_hvparams[hv_name].update(hv_dict)
3039

    
3040
    # os hypervisor parameters
3041
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3042
    if self.op.os_hvp:
3043
      for os_name, hvs in self.op.os_hvp.items():
3044
        if os_name not in self.new_os_hvp:
3045
          self.new_os_hvp[os_name] = hvs
3046
        else:
3047
          for hv_name, hv_dict in hvs.items():
3048
            if hv_name not in self.new_os_hvp[os_name]:
3049
              self.new_os_hvp[os_name][hv_name] = hv_dict
3050
            else:
3051
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3052

    
3053
    # os parameters
3054
    self.new_osp = objects.FillDict(cluster.osparams, {})
3055
    if self.op.osparams:
3056
      for os_name, osp in self.op.osparams.items():
3057
        if os_name not in self.new_osp:
3058
          self.new_osp[os_name] = {}
3059

    
3060
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3061
                                                  use_none=True)
3062

    
3063
        if not self.new_osp[os_name]:
3064
          # we removed all parameters
3065
          del self.new_osp[os_name]
3066
        else:
3067
          # check the parameter validity (remote check)
3068
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3069
                         os_name, self.new_osp[os_name])
3070

    
3071
    # changes to the hypervisor list
3072
    if self.op.enabled_hypervisors is not None:
3073
      self.hv_list = self.op.enabled_hypervisors
3074
      for hv in self.hv_list:
3075
        # if the hypervisor doesn't already exist in the cluster
3076
        # hvparams, we initialize it to empty, and then (in both
3077
        # cases) we make sure to fill the defaults, as we might not
3078
        # have a complete defaults list if the hypervisor wasn't
3079
        # enabled before
3080
        if hv not in new_hvp:
3081
          new_hvp[hv] = {}
3082
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3083
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3084
    else:
3085
      self.hv_list = cluster.enabled_hypervisors
3086

    
3087
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3088
      # either the enabled list has changed, or the parameters have, validate
3089
      for hv_name, hv_params in self.new_hvparams.items():
3090
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3091
            (self.op.enabled_hypervisors and
3092
             hv_name in self.op.enabled_hypervisors)):
3093
          # either this is a new hypervisor, or its parameters have changed
3094
          hv_class = hypervisor.GetHypervisor(hv_name)
3095
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3096
          hv_class.CheckParameterSyntax(hv_params)
3097
          _CheckHVParams(self, node_list, hv_name, hv_params)
3098

    
3099
    if self.op.os_hvp:
3100
      # no need to check any newly-enabled hypervisors, since the
3101
      # defaults have already been checked in the above code-block
3102
      for os_name, os_hvp in self.new_os_hvp.items():
3103
        for hv_name, hv_params in os_hvp.items():
3104
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3105
          # we need to fill in the new os_hvp on top of the actual hv_p
3106
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3107
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3108
          hv_class = hypervisor.GetHypervisor(hv_name)
3109
          hv_class.CheckParameterSyntax(new_osp)
3110
          _CheckHVParams(self, node_list, hv_name, new_osp)
3111

    
3112
    if self.op.default_iallocator:
3113
      alloc_script = utils.FindFile(self.op.default_iallocator,
3114
                                    constants.IALLOCATOR_SEARCH_PATH,
3115
                                    os.path.isfile)
3116
      if alloc_script is None:
3117
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3118
                                   " specified" % self.op.default_iallocator,
3119
                                   errors.ECODE_INVAL)
3120

    
3121
  def Exec(self, feedback_fn):
3122
    """Change the parameters of the cluster.
3123

3124
    """
3125
    if self.op.vg_name is not None:
3126
      new_volume = self.op.vg_name
3127
      if not new_volume:
3128
        new_volume = None
3129
      if new_volume != self.cfg.GetVGName():
3130
        self.cfg.SetVGName(new_volume)
3131
      else:
3132
        feedback_fn("Cluster LVM configuration already in desired"
3133
                    " state, not changing")
3134
    if self.op.drbd_helper is not None:
3135
      new_helper = self.op.drbd_helper
3136
      if not new_helper:
3137
        new_helper = None
3138
      if new_helper != self.cfg.GetDRBDHelper():
3139
        self.cfg.SetDRBDHelper(new_helper)
3140
      else:
3141
        feedback_fn("Cluster DRBD helper already in desired state,"
3142
                    " not changing")
3143
    if self.op.hvparams:
3144
      self.cluster.hvparams = self.new_hvparams
3145
    if self.op.os_hvp:
3146
      self.cluster.os_hvp = self.new_os_hvp
3147
    if self.op.enabled_hypervisors is not None:
3148
      self.cluster.hvparams = self.new_hvparams
3149
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3150
    if self.op.beparams:
3151
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3152
    if self.op.nicparams:
3153
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3154
    if self.op.osparams:
3155
      self.cluster.osparams = self.new_osp
3156
    if self.op.ndparams:
3157
      self.cluster.ndparams = self.new_ndparams
3158

    
3159
    if self.op.candidate_pool_size is not None:
3160
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3161
      # we need to update the pool size here, otherwise the save will fail
3162
      _AdjustCandidatePool(self, [])
3163

    
3164
    if self.op.maintain_node_health is not None:
3165
      self.cluster.maintain_node_health = self.op.maintain_node_health
3166

    
3167
    if self.op.prealloc_wipe_disks is not None:
3168
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3169

    
3170
    if self.op.add_uids is not None:
3171
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3172

    
3173
    if self.op.remove_uids is not None:
3174
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3175

    
3176
    if self.op.uid_pool is not None:
3177
      self.cluster.uid_pool = self.op.uid_pool
3178

    
3179
    if self.op.default_iallocator is not None:
3180
      self.cluster.default_iallocator = self.op.default_iallocator
3181

    
3182
    if self.op.reserved_lvs is not None:
3183
      self.cluster.reserved_lvs = self.op.reserved_lvs
3184

    
3185
    def helper_os(aname, mods, desc):
3186
      desc += " OS list"
3187
      lst = getattr(self.cluster, aname)
3188
      for key, val in mods:
3189
        if key == constants.DDM_ADD:
3190
          if val in lst:
3191
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3192
          else:
3193
            lst.append(val)
3194
        elif key == constants.DDM_REMOVE:
3195
          if val in lst:
3196
            lst.remove(val)
3197
          else:
3198
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3199
        else:
3200
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3201

    
3202
    if self.op.hidden_os:
3203
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3204

    
3205
    if self.op.blacklisted_os:
3206
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3207

    
3208
    if self.op.master_netdev:
3209
      master = self.cfg.GetMasterNode()
3210
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3211
                  self.cluster.master_netdev)
3212
      result = self.rpc.call_node_stop_master(master, False)
3213
      result.Raise("Could not disable the master ip")
3214
      feedback_fn("Changing master_netdev from %s to %s" %
3215
                  (self.cluster.master_netdev, self.op.master_netdev))
3216
      self.cluster.master_netdev = self.op.master_netdev
3217

    
3218
    self.cfg.Update(self.cluster, feedback_fn)
3219

    
3220
    if self.op.master_netdev:
3221
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3222
                  self.op.master_netdev)
3223
      result = self.rpc.call_node_start_master(master, False, False)
3224
      if result.fail_msg:
3225
        self.LogWarning("Could not re-enable the master ip on"
3226
                        " the master, please restart manually: %s",
3227
                        result.fail_msg)
3228

    
3229

    
3230
def _UploadHelper(lu, nodes, fname):
3231
  """Helper for uploading a file and showing warnings.
3232

3233
  """
3234
  if os.path.exists(fname):
3235
    result = lu.rpc.call_upload_file(nodes, fname)
3236
    for to_node, to_result in result.items():
3237
      msg = to_result.fail_msg
3238
      if msg:
3239
        msg = ("Copy of file %s to node %s failed: %s" %
3240
               (fname, to_node, msg))
3241
        lu.proc.LogWarning(msg)
3242

    
3243

    
3244
def _ComputeAncillaryFiles(cluster, redist):
3245
  """Compute files external to Ganeti which need to be consistent.
3246

3247
  @type redist: boolean
3248
  @param redist: Whether to include files which need to be redistributed
3249

3250
  """
3251
  # Compute files for all nodes
3252
  files_all = set([
3253
    constants.SSH_KNOWN_HOSTS_FILE,
3254
    constants.CONFD_HMAC_KEY,
3255
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3256
    ])
3257

    
3258
  if not redist:
3259
    files_all.update(constants.ALL_CERT_FILES)
3260
    files_all.update(ssconf.SimpleStore().GetFileList())
3261

    
3262
  if cluster.modify_etc_hosts:
3263
    files_all.add(constants.ETC_HOSTS)
3264

    
3265
  # Files which must either exist on all nodes or on none
3266
  files_all_opt = set([
3267
    constants.RAPI_USERS_FILE,
3268
    ])
3269

    
3270
  # Files which should only be on master candidates
3271
  files_mc = set()
3272
  if not redist:
3273
    files_mc.add(constants.CLUSTER_CONF_FILE)
3274

    
3275
  # Files which should only be on VM-capable nodes
3276
  files_vm = set(filename
3277
    for hv_name in cluster.enabled_hypervisors
3278
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3279

    
3280
  # Filenames must be unique
3281
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3282
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3283
         "Found file listed in more than one file list"
3284

    
3285
  return (files_all, files_all_opt, files_mc, files_vm)
3286

    
3287

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

3291
  ConfigWriter takes care of distributing the config and ssconf files, but
3292
  there are more files which should be distributed to all nodes. This function
3293
  makes sure those are copied.
3294

3295
  @param lu: calling logical unit
3296
  @param additional_nodes: list of nodes not in the config to distribute to
3297
  @type additional_vm: boolean
3298
  @param additional_vm: whether the additional nodes are vm-capable or not
3299

3300
  """
3301
  # Gather target nodes
3302
  cluster = lu.cfg.GetClusterInfo()
3303
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3304

    
3305
  online_nodes = lu.cfg.GetOnlineNodeList()
3306
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3307

    
3308
  if additional_nodes is not None:
3309
    online_nodes.extend(additional_nodes)
3310
    if additional_vm:
3311
      vm_nodes.extend(additional_nodes)
3312

    
3313
  # Never distribute to master node
3314
  for nodelist in [online_nodes, vm_nodes]:
3315
    if master_info.name in nodelist:
3316
      nodelist.remove(master_info.name)
3317

    
3318
  # Gather file lists
3319
  (files_all, files_all_opt, files_mc, files_vm) = \
3320
    _ComputeAncillaryFiles(cluster, True)
3321

    
3322
  # Never re-distribute configuration file from here
3323
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3324
              constants.CLUSTER_CONF_FILE in files_vm)
3325
  assert not files_mc, "Master candidates not handled in this function"
3326

    
3327
  filemap = [
3328
    (online_nodes, files_all),
3329
    (online_nodes, files_all_opt),
3330
    (vm_nodes, files_vm),
3331
    ]
3332

    
3333
  # Upload the files
3334
  for (node_list, files) in filemap:
3335
    for fname in files:
3336
      _UploadHelper(lu, node_list, fname)
3337

    
3338

    
3339
class LUClusterRedistConf(NoHooksLU):
3340
  """Force the redistribution of cluster configuration.
3341

3342
  This is a very simple LU.
3343

3344
  """
3345
  REQ_BGL = False
3346

    
3347
  def ExpandNames(self):
3348
    self.needed_locks = {
3349
      locking.LEVEL_NODE: locking.ALL_SET,
3350
    }
3351
    self.share_locks[locking.LEVEL_NODE] = 1
3352

    
3353
  def Exec(self, feedback_fn):
3354
    """Redistribute the configuration.
3355

3356
    """
3357
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3358
    _RedistributeAncillaryFiles(self)
3359

    
3360

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

3364
  """
3365
  if not instance.disks or disks is not None and not disks:
3366
    return True
3367

    
3368
  disks = _ExpandCheckDisks(instance, disks)
3369

    
3370
  if not oneshot:
3371
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3372

    
3373
  node = instance.primary_node
3374

    
3375
  for dev in disks:
3376
    lu.cfg.SetDiskID(dev, node)
3377

    
3378
  # TODO: Convert to utils.Retry
3379

    
3380
  retries = 0
3381
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3382
  while True:
3383
    max_time = 0
3384
    done = True
3385
    cumul_degraded = False
3386
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3387
    msg = rstats.fail_msg
3388
    if msg:
3389
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3390
      retries += 1
3391
      if retries >= 10:
3392
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3393
                                 " aborting." % node)
3394
      time.sleep(6)
3395
      continue
3396
    rstats = rstats.payload
3397
    retries = 0
3398
    for i, mstat in enumerate(rstats):
3399
      if mstat is None:
3400
        lu.LogWarning("Can't compute data for node %s/%s",
3401
                           node, disks[i].iv_name)
3402
        continue
3403

    
3404
      cumul_degraded = (cumul_degraded or
3405
                        (mstat.is_degraded and mstat.sync_percent is None))
3406
      if mstat.sync_percent is not None:
3407
        done = False
3408
        if mstat.estimated_time is not None:
3409
          rem_time = ("%s remaining (estimated)" %
3410
                      utils.FormatSeconds(mstat.estimated_time))
3411
          max_time = mstat.estimated_time
3412
        else:
3413
          rem_time = "no time estimate"
3414
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3415
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3416

    
3417
    # if we're done but degraded, let's do a few small retries, to
3418
    # make sure we see a stable and not transient situation; therefore
3419
    # we force restart of the loop
3420
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3421
      logging.info("Degraded disks found, %d retries left", degr_retries)
3422
      degr_retries -= 1
3423
      time.sleep(1)
3424
      continue
3425

    
3426
    if done or oneshot:
3427
      break
3428

    
3429
    time.sleep(min(60, max_time))
3430

    
3431
  if done:
3432
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3433
  return not cumul_degraded
3434

    
3435

    
3436
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3437
  """Check that mirrors are not degraded.
3438

3439
  The ldisk parameter, if True, will change the test from the
3440
  is_degraded attribute (which represents overall non-ok status for
3441
  the device(s)) to the ldisk (representing the local storage status).
3442

3443
  """
3444
  lu.cfg.SetDiskID(dev, node)
3445

    
3446
  result = True
3447

    
3448
  if on_primary or dev.AssembleOnSecondary():
3449
    rstats = lu.rpc.call_blockdev_find(node, dev)
3450
    msg = rstats.fail_msg
3451
    if msg:
3452
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3453
      result = False
3454
    elif not rstats.payload:
3455
      lu.LogWarning("Can't find disk on node %s", node)
3456
      result = False
3457
    else:
3458
      if ldisk:
3459
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3460
      else:
3461
        result = result and not rstats.payload.is_degraded
3462

    
3463
  if dev.children:
3464
    for child in dev.children:
3465
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3466

    
3467
  return result
3468

    
3469

    
3470
class LUOobCommand(NoHooksLU):
3471
  """Logical unit for OOB handling.
3472

3473
  """
3474
  REG_BGL = False
3475
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3476

    
3477
  def ExpandNames(self):
3478
    """Gather locks we need.
3479

3480
    """
3481
    if self.op.node_names:
3482
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3483
      lock_names = self.op.node_names
3484
    else:
3485
      lock_names = locking.ALL_SET
3486

    
3487
    self.needed_locks = {
3488
      locking.LEVEL_NODE: lock_names,
3489
      }
3490

    
3491
  def CheckPrereq(self):
3492
    """Check prerequisites.
3493

3494
    This checks:
3495
     - the node exists in the configuration
3496
     - OOB is supported
3497

3498
    Any errors are signaled by raising errors.OpPrereqError.
3499

3500
    """
3501
    self.nodes = []
3502
    self.master_node = self.cfg.GetMasterNode()
3503

    
3504
    assert self.op.power_delay >= 0.0
3505

    
3506
    if self.op.node_names:
3507
      if (self.op.command in self._SKIP_MASTER and
3508
          self.master_node in self.op.node_names):
3509
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3510
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3511

    
3512
        if master_oob_handler:
3513
          additional_text = ("run '%s %s %s' if you want to operate on the"
3514
                             " master regardless") % (master_oob_handler,
3515
                                                      self.op.command,
3516
                                                      self.master_node)
3517
        else:
3518
          additional_text = "it does not support out-of-band operations"
3519

    
3520
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3521
                                    " allowed for %s; %s") %
3522
                                   (self.master_node, self.op.command,
3523
                                    additional_text), errors.ECODE_INVAL)
3524
    else:
3525
      self.op.node_names = self.cfg.GetNodeList()
3526
      if self.op.command in self._SKIP_MASTER:
3527
        self.op.node_names.remove(self.master_node)
3528

    
3529
    if self.op.command in self._SKIP_MASTER:
3530
      assert self.master_node not in self.op.node_names
3531

    
3532
    for node_name in self.op.node_names:
3533
      node = self.cfg.GetNodeInfo(node_name)
3534

    
3535
      if node is None:
3536
        raise errors.OpPrereqError("Node %s not found" % node_name,
3537
                                   errors.ECODE_NOENT)
3538
      else:
3539
        self.nodes.append(node)
3540

    
3541
      if (not self.op.ignore_status and
3542
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3543
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3544
                                    " not marked offline") % node_name,
3545
                                   errors.ECODE_STATE)
3546

    
3547
  def Exec(self, feedback_fn):
3548
    """Execute OOB and return result if we expect any.
3549

3550
    """
3551
    master_node = self.master_node
3552
    ret = []
3553

    
3554
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3555
                                              key=lambda node: node.name)):
3556
      node_entry = [(constants.RS_NORMAL, node.name)]
3557
      ret.append(node_entry)
3558

    
3559
      oob_program = _SupportsOob(self.cfg, node)
3560

    
3561
      if not oob_program:
3562
        node_entry.append((constants.RS_UNAVAIL, None))
3563
        continue
3564

    
3565
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3566
                   self.op.command, oob_program, node.name)
3567
      result = self.rpc.call_run_oob(master_node, oob_program,
3568
                                     self.op.command, node.name,
3569
                                     self.op.timeout)
3570

    
3571
      if result.fail_msg:
3572
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3573
                        node.name, result.fail_msg)
3574
        node_entry.append((constants.RS_NODATA, None))
3575
      else:
3576
        try:
3577
          self._CheckPayload(result)
3578
        except errors.OpExecError, err:
3579
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3580
                          node.name, err)
3581
          node_entry.append((constants.RS_NODATA, None))
3582
        else:
3583
          if self.op.command == constants.OOB_HEALTH:
3584
            # For health we should log important events
3585
            for item, status in result.payload:
3586
              if status in [constants.OOB_STATUS_WARNING,
3587
                            constants.OOB_STATUS_CRITICAL]:
3588
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3589
                                item, node.name, status)
3590

    
3591
          if self.op.command == constants.OOB_POWER_ON:
3592
            node.powered = True
3593
          elif self.op.command == constants.OOB_POWER_OFF:
3594
            node.powered = False
3595
          elif self.op.command == constants.OOB_POWER_STATUS:
3596
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3597
            if powered != node.powered:
3598
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3599
                               " match actual power state (%s)"), node.powered,
3600
                              node.name, powered)
3601

    
3602
          # For configuration changing commands we should update the node
3603
          if self.op.command in (constants.OOB_POWER_ON,
3604
                                 constants.OOB_POWER_OFF):
3605
            self.cfg.Update(node, feedback_fn)
3606

    
3607
          node_entry.append((constants.RS_NORMAL, result.payload))
3608

    
3609
          if (self.op.command == constants.OOB_POWER_ON and
3610
              idx < len(self.nodes) - 1):
3611
            time.sleep(self.op.power_delay)
3612

    
3613
    return ret
3614

    
3615
  def _CheckPayload(self, result):
3616
    """Checks if the payload is valid.
3617

3618
    @param result: RPC result
3619
    @raises errors.OpExecError: If payload is not valid
3620

3621
    """
3622
    errs = []
3623
    if self.op.command == constants.OOB_HEALTH:
3624
      if not isinstance(result.payload, list):
3625
        errs.append("command 'health' is expected to return a list but got %s" %
3626
                    type(result.payload))
3627
      else:
3628
        for item, status in result.payload:
3629
          if status not in constants.OOB_STATUSES:
3630
            errs.append("health item '%s' has invalid status '%s'" %
3631
                        (item, status))
3632

    
3633
    if self.op.command == constants.OOB_POWER_STATUS:
3634
      if not isinstance(result.payload, dict):
3635
        errs.append("power-status is expected to return a dict but got %s" %
3636
                    type(result.payload))
3637

    
3638
    if self.op.command in [
3639
        constants.OOB_POWER_ON,
3640
        constants.OOB_POWER_OFF,
3641
        constants.OOB_POWER_CYCLE,
3642
        ]:
3643
      if result.payload is not None:
3644
        errs.append("%s is expected to not return payload but got '%s'" %
3645
                    (self.op.command, result.payload))
3646

    
3647
    if errs:
3648
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3649
                               utils.CommaJoin(errs))
3650

    
3651
class _OsQuery(_QueryBase):
3652
  FIELDS = query.OS_FIELDS
3653

    
3654
  def ExpandNames(self, lu):
3655
    # Lock all nodes in shared mode
3656
    # Temporary removal of locks, should be reverted later
3657
    # TODO: reintroduce locks when they are lighter-weight
3658
    lu.needed_locks = {}
3659
    #self.share_locks[locking.LEVEL_NODE] = 1
3660
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3661

    
3662
    # The following variables interact with _QueryBase._GetNames
3663
    if self.names:
3664
      self.wanted = self.names
3665
    else:
3666
      self.wanted = locking.ALL_SET
3667

    
3668
    self.do_locking = self.use_locking
3669

    
3670
  def DeclareLocks(self, lu, level):
3671
    pass
3672

    
3673
  @staticmethod
3674
  def _DiagnoseByOS(rlist):
3675
    """Remaps a per-node return list into an a per-os per-node dictionary
3676

3677
    @param rlist: a map with node names as keys and OS objects as values
3678

3679
    @rtype: dict
3680
    @return: a dictionary with osnames as keys and as value another
3681
        map, with nodes as keys and tuples of (path, status, diagnose,
3682
        variants, parameters, api_versions) as values, eg::
3683

3684
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3685
                                     (/srv/..., False, "invalid api")],
3686
                           "node2": [(/srv/..., True, "", [], [])]}
3687
          }
3688

3689
    """
3690
    all_os = {}
3691
    # we build here the list of nodes that didn't fail the RPC (at RPC
3692
    # level), so that nodes with a non-responding node daemon don't
3693
    # make all OSes invalid
3694
    good_nodes = [node_name for node_name in rlist
3695
                  if not rlist[node_name].fail_msg]
3696
    for node_name, nr in rlist.items():
3697
      if nr.fail_msg or not nr.payload:
3698
        continue
3699
      for (name, path, status, diagnose, variants,
3700
           params, api_versions) in nr.payload:
3701
        if name not in all_os:
3702
          # build a list of nodes for this os containing empty lists
3703
          # for each node in node_list
3704
          all_os[name] = {}
3705
          for nname in good_nodes:
3706
            all_os[name][nname] = []
3707
        # convert params from [name, help] to (name, help)
3708
        params = [tuple(v) for v in params]
3709
        all_os[name][node_name].append((path, status, diagnose,
3710
                                        variants, params, api_versions))
3711
    return all_os
3712

    
3713
  def _GetQueryData(self, lu):
3714
    """Computes the list of nodes and their attributes.
3715

3716
    """
3717
    # Locking is not used
3718
    assert not (compat.any(lu.glm.is_owned(level)
3719
                           for level in locking.LEVELS
3720
                           if level != locking.LEVEL_CLUSTER) or
3721
                self.do_locking or self.use_locking)
3722

    
3723
    valid_nodes = [node.name
3724
                   for node in lu.cfg.GetAllNodesInfo().values()
3725
                   if not node.offline and node.vm_capable]
3726
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3727
    cluster = lu.cfg.GetClusterInfo()
3728

    
3729
    data = {}
3730

    
3731
    for (os_name, os_data) in pol.items():
3732
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3733
                          hidden=(os_name in cluster.hidden_os),
3734
                          blacklisted=(os_name in cluster.blacklisted_os))
3735

    
3736
      variants = set()
3737
      parameters = set()
3738
      api_versions = set()
3739

    
3740
      for idx, osl in enumerate(os_data.values()):
3741
        info.valid = bool(info.valid and osl and osl[0][1])
3742
        if not info.valid:
3743
          break
3744

    
3745
        (node_variants, node_params, node_api) = osl[0][3:6]
3746
        if idx == 0:
3747
          # First entry
3748
          variants.update(node_variants)
3749
          parameters.update(node_params)
3750
          api_versions.update(node_api)
3751
        else:
3752
          # Filter out inconsistent values
3753
          variants.intersection_update(node_variants)
3754
          parameters.intersection_update(node_params)
3755
          api_versions.intersection_update(node_api)
3756

    
3757
      info.variants = list(variants)
3758
      info.parameters = list(parameters)
3759
      info.api_versions = list(api_versions)
3760

    
3761
      data[os_name] = info
3762

    
3763
    # Prepare data in requested order
3764
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3765
            if name in data]
3766

    
3767

    
3768
class LUOsDiagnose(NoHooksLU):
3769
  """Logical unit for OS diagnose/query.
3770

3771
  """
3772
  REQ_BGL = False
3773

    
3774
  @staticmethod
3775
  def _BuildFilter(fields, names):
3776
    """Builds a filter for querying OSes.
3777

3778
    """
3779
    name_filter = qlang.MakeSimpleFilter("name", names)
3780

    
3781
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3782
    # respective field is not requested
3783
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3784
                     for fname in ["hidden", "blacklisted"]
3785
                     if fname not in fields]
3786
    if "valid" not in fields:
3787
      status_filter.append([qlang.OP_TRUE, "valid"])
3788

    
3789
    if status_filter:
3790
      status_filter.insert(0, qlang.OP_AND)
3791
    else:
3792
      status_filter = None
3793

    
3794
    if name_filter and status_filter:
3795
      return [qlang.OP_AND, name_filter, status_filter]
3796
    elif name_filter:
3797
      return name_filter
3798
    else:
3799
      return status_filter
3800

    
3801
  def CheckArguments(self):
3802
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
3803
                       self.op.output_fields, False)
3804

    
3805
  def ExpandNames(self):
3806
    self.oq.ExpandNames(self)
3807

    
3808
  def Exec(self, feedback_fn):
3809
    return self.oq.OldStyleQuery(self)
3810

    
3811

    
3812
class LUNodeRemove(LogicalUnit):
3813
  """Logical unit for removing a node.
3814

3815
  """
3816
  HPATH = "node-remove"
3817
  HTYPE = constants.HTYPE_NODE
3818

    
3819
  def BuildHooksEnv(self):
3820
    """Build hooks env.
3821

3822
    This doesn't run on the target node in the pre phase as a failed
3823
    node would then be impossible to remove.
3824

3825
    """
3826
    return {
3827
      "OP_TARGET": self.op.node_name,
3828
      "NODE_NAME": self.op.node_name,
3829
      }
3830

    
3831
  def BuildHooksNodes(self):
3832
    """Build hooks nodes.
3833

3834
    """
3835
    all_nodes = self.cfg.GetNodeList()
3836
    try:
3837
      all_nodes.remove(self.op.node_name)
3838
    except ValueError:
3839
      logging.warning("Node '%s', which is about to be removed, was not found"
3840
                      " in the list of all nodes", self.op.node_name)
3841
    return (all_nodes, all_nodes)
3842

    
3843
  def CheckPrereq(self):
3844
    """Check prerequisites.
3845

3846
    This checks:
3847
     - the node exists in the configuration
3848
     - it does not have primary or secondary instances
3849
     - it's not the master
3850

3851
    Any errors are signaled by raising errors.OpPrereqError.
3852

3853
    """
3854
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3855
    node = self.cfg.GetNodeInfo(self.op.node_name)
3856
    assert node is not None
3857

    
3858
    instance_list = self.cfg.GetInstanceList()
3859

    
3860
    masternode = self.cfg.GetMasterNode()
3861
    if node.name == masternode:
3862
      raise errors.OpPrereqError("Node is the master node, failover to another"
3863
                                 " node is required", errors.ECODE_INVAL)
3864

    
3865
    for instance_name in instance_list:
3866
      instance = self.cfg.GetInstanceInfo(instance_name)
3867
      if node.name in instance.all_nodes:
3868
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3869
                                   " please remove first" % instance_name,
3870
                                   errors.ECODE_INVAL)
3871
    self.op.node_name = node.name
3872
    self.node = node
3873

    
3874
  def Exec(self, feedback_fn):
3875
    """Removes the node from the cluster.
3876

3877
    """
3878
    node = self.node
3879
    logging.info("Stopping the node daemon and removing configs from node %s",
3880
                 node.name)
3881

    
3882
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3883

    
3884
    # Promote nodes to master candidate as needed
3885
    _AdjustCandidatePool(self, exceptions=[node.name])
3886
    self.context.RemoveNode(node.name)
3887

    
3888
    # Run post hooks on the node before it's removed
3889
    _RunPostHook(self, node.name)
3890

    
3891
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3892
    msg = result.fail_msg
3893
    if msg:
3894
      self.LogWarning("Errors encountered on the remote node while leaving"
3895
                      " the cluster: %s", msg)
3896

    
3897
    # Remove node from our /etc/hosts
3898
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3899
      master_node = self.cfg.GetMasterNode()
3900
      result = self.rpc.call_etc_hosts_modify(master_node,
3901
                                              constants.ETC_HOSTS_REMOVE,
3902
                                              node.name, None)
3903
      result.Raise("Can't update hosts file with new host data")
3904
      _RedistributeAncillaryFiles(self)
3905

    
3906

    
3907
class _NodeQuery(_QueryBase):
3908
  FIELDS = query.NODE_FIELDS
3909

    
3910
  def ExpandNames(self, lu):
3911
    lu.needed_locks = {}
3912
    lu.share_locks[locking.LEVEL_NODE] = 1
3913

    
3914
    if self.names:
3915
      self.wanted = _GetWantedNodes(lu, self.names)
3916
    else:
3917
      self.wanted = locking.ALL_SET
3918

    
3919
    self.do_locking = (self.use_locking and
3920
                       query.NQ_LIVE in self.requested_data)
3921

    
3922
    if self.do_locking:
3923
      # if we don't request only static fields, we need to lock the nodes
3924
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3925

    
3926
  def DeclareLocks(self, lu, level):
3927
    pass
3928

    
3929
  def _GetQueryData(self, lu):
3930
    """Computes the list of nodes and their attributes.
3931

3932
    """
3933
    all_info = lu.cfg.GetAllNodesInfo()
3934

    
3935
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3936

    
3937
    # Gather data as requested
3938
    if query.NQ_LIVE in self.requested_data:
3939
      # filter out non-vm_capable nodes
3940
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3941

    
3942
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3943
                                        lu.cfg.GetHypervisorType())
3944
      live_data = dict((name, nresult.payload)
3945
                       for (name, nresult) in node_data.items()
3946
                       if not nresult.fail_msg and nresult.payload)
3947
    else:
3948
      live_data = None
3949

    
3950
    if query.NQ_INST in self.requested_data:
3951
      node_to_primary = dict([(name, set()) for name in nodenames])
3952
      node_to_secondary = dict([(name, set()) for name in nodenames])
3953

    
3954
      inst_data = lu.cfg.GetAllInstancesInfo()
3955

    
3956
      for inst in inst_data.values():
3957
        if inst.primary_node in node_to_primary:
3958
          node_to_primary[inst.primary_node].add(inst.name)
3959
        for secnode in inst.secondary_nodes:
3960
          if secnode in node_to_secondary:
3961
            node_to_secondary[secnode].add(inst.name)
3962
    else:
3963
      node_to_primary = None
3964
      node_to_secondary = None
3965

    
3966
    if query.NQ_OOB in self.requested_data:
3967
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3968
                         for name, node in all_info.iteritems())
3969
    else:
3970
      oob_support = None
3971

    
3972
    if query.NQ_GROUP in self.requested_data:
3973
      groups = lu.cfg.GetAllNodeGroupsInfo()
3974
    else:
3975
      groups = {}
3976

    
3977
    return query.NodeQueryData([all_info[name] for name in nodenames],
3978
                               live_data, lu.cfg.GetMasterNode(),
3979
                               node_to_primary, node_to_secondary, groups,
3980
                               oob_support, lu.cfg.GetClusterInfo())
3981

    
3982

    
3983
class LUNodeQuery(NoHooksLU):
3984
  """Logical unit for querying nodes.
3985

3986
  """
3987
  # pylint: disable-msg=W0142
3988
  REQ_BGL = False
3989

    
3990
  def CheckArguments(self):
3991
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
3992
                         self.op.output_fields, self.op.use_locking)
3993

    
3994
  def ExpandNames(self):
3995
    self.nq.ExpandNames(self)
3996

    
3997
  def Exec(self, feedback_fn):
3998
    return self.nq.OldStyleQuery(self)
3999

    
4000

    
4001
class LUNodeQueryvols(NoHooksLU):
4002
  """Logical unit for getting volumes on node(s).
4003

4004
  """
4005
  REQ_BGL = False
4006
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4007
  _FIELDS_STATIC = utils.FieldSet("node")
4008

    
4009
  def CheckArguments(self):
4010
    _CheckOutputFields(static=self._FIELDS_STATIC,
4011
                       dynamic=self._FIELDS_DYNAMIC,
4012
                       selected=self.op.output_fields)
4013

    
4014
  def ExpandNames(self):
4015
    self.needed_locks = {}
4016
    self.share_locks[locking.LEVEL_NODE] = 1
4017
    if not self.op.nodes:
4018
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4019
    else:
4020
      self.needed_locks[locking.LEVEL_NODE] = \
4021
        _GetWantedNodes(self, self.op.nodes)
4022

    
4023
  def Exec(self, feedback_fn):
4024
    """Computes the list of nodes and their attributes.
4025

4026
    """
4027
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4028
    volumes = self.rpc.call_node_volumes(nodenames)
4029

    
4030
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4031
             in self.cfg.GetInstanceList()]
4032

    
4033
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4034

    
4035
    output = []
4036
    for node in nodenames:
4037
      nresult = volumes[node]
4038
      if nresult.offline:
4039
        continue
4040
      msg = nresult.fail_msg
4041
      if msg:
4042
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4043
        continue
4044

    
4045
      node_vols = nresult.payload[:]
4046
      node_vols.sort(key=lambda vol: vol['dev'])
4047

    
4048
      for vol in node_vols:
4049
        node_output = []
4050
        for field in self.op.output_fields:
4051
          if field == "node":
4052
            val = node
4053
          elif field == "phys":
4054
            val = vol['dev']
4055
          elif field == "vg":
4056
            val = vol['vg']
4057
          elif field == "name":
4058
            val = vol['name']
4059
          elif field == "size":
4060
            val = int(float(vol['size']))
4061
          elif field == "instance":
4062
            for inst in ilist:
4063
              if node not in lv_by_node[inst]:
4064
                continue
4065
              if vol['name'] in lv_by_node[inst][node]:
4066
                val = inst.name
4067
                break
4068
            else:
4069
              val = '-'
4070
          else:
4071
            raise errors.ParameterError(field)
4072
          node_output.append(str(val))
4073

    
4074
        output.append(node_output)
4075

    
4076
    return output
4077

    
4078

    
4079
class LUNodeQueryStorage(NoHooksLU):
4080
  """Logical unit for getting information on storage units on node(s).
4081

4082
  """
4083
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4084
  REQ_BGL = False
4085

    
4086
  def CheckArguments(self):
4087
    _CheckOutputFields(static=self._FIELDS_STATIC,
4088
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4089
                       selected=self.op.output_fields)
4090

    
4091
  def ExpandNames(self):
4092
    self.needed_locks = {}