Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 463f75a5

History | View | Annotate | Download (460 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, tags):
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
  @type tags: list
897
  @param tags: list of instance tags as strings
898
  @rtype: dict
899
  @return: the hook environment for this instance
900

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

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

    
933
  env["INSTANCE_NIC_COUNT"] = nic_count
934

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

    
943
  env["INSTANCE_DISK_COUNT"] = disk_count
944

    
945
  if not tags:
946
    tags = []
947

    
948
  env["INSTANCE_TAGS"] = " ".join(tags)
949

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

    
954
  return env
955

    
956

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

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

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

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

    
980

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

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

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

    
1019

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

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

    
1035

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

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

    
1046

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

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

    
1060

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

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

    
1069

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

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

1078
  """
1079
  if not os_obj.supported_variants:
1080
    return
1081
  variant = objects.OS.GetVariant(name)
1082
  if not variant:
1083
    raise errors.OpPrereqError("OS name must include a variant",
1084
                               errors.ECODE_INVAL)
1085

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

    
1089

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

    
1093

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

1097
  """
1098

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

    
1101

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

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

    
1109

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

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

    
1117

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

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

    
1127
  return []
1128

    
1129

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

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

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

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

    
1144
  return faulty
1145

    
1146

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

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

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

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

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

    
1178

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

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

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

1189
    """
1190
    return {
1191
      "OP_TARGET": self.cfg.GetClusterName(),
1192
      }
1193

    
1194
  def BuildHooksNodes(self):
1195
    """Build hooks nodes.
1196

1197
    """
1198
    return ([], [self.cfg.GetMasterNode()])
1199

    
1200
  def Exec(self, feedback_fn):
1201
    """Nothing to do.
1202

1203
    """
1204
    return True
1205

    
1206

    
1207
class LUClusterDestroy(LogicalUnit):
1208
  """Logical unit for destroying the cluster.
1209

1210
  """
1211
  HPATH = "cluster-destroy"
1212
  HTYPE = constants.HTYPE_CLUSTER
1213

    
1214
  def BuildHooksEnv(self):
1215
    """Build hooks env.
1216

1217
    """
1218
    return {
1219
      "OP_TARGET": self.cfg.GetClusterName(),
1220
      }
1221

    
1222
  def BuildHooksNodes(self):
1223
    """Build hooks nodes.
1224

1225
    """
1226
    return ([], [])
1227

    
1228
  def CheckPrereq(self):
1229
    """Check prerequisites.
1230

1231
    This checks whether the cluster is empty.
1232

1233
    Any errors are signaled by raising errors.OpPrereqError.
1234

1235
    """
1236
    master = self.cfg.GetMasterNode()
1237

    
1238
    nodelist = self.cfg.GetNodeList()
1239
    if len(nodelist) != 1 or nodelist[0] != master:
1240
      raise errors.OpPrereqError("There are still %d node(s) in"
1241
                                 " this cluster." % (len(nodelist) - 1),
1242
                                 errors.ECODE_INVAL)
1243
    instancelist = self.cfg.GetInstanceList()
1244
    if instancelist:
1245
      raise errors.OpPrereqError("There are still %d instance(s) in"
1246
                                 " this cluster." % len(instancelist),
1247
                                 errors.ECODE_INVAL)
1248

    
1249
  def Exec(self, feedback_fn):
1250
    """Destroys the cluster.
1251

1252
    """
1253
    master = self.cfg.GetMasterNode()
1254

    
1255
    # Run post hooks on master node before it's removed
1256
    _RunPostHook(self, master)
1257

    
1258
    result = self.rpc.call_node_stop_master(master, False)
1259
    result.Raise("Could not disable the master role")
1260

    
1261
    return master
1262

    
1263

    
1264
def _VerifyCertificate(filename):
1265
  """Verifies a certificate for L{LUClusterVerifyConfig}.
1266

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

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

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

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

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

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

    
1296

    
1297
def _GetAllHypervisorParameters(cluster, instances):
1298
  """Compute the set of all hypervisor parameters.
1299

1300
  @type cluster: L{objects.Cluster}
1301
  @param cluster: the cluster object
1302
  @param instances: list of L{objects.Instance}
1303
  @param instances: additional instances from which to obtain parameters
1304
  @rtype: list of (origin, hypervisor, parameters)
1305
  @return: a list with all parameters found, indicating the hypervisor they
1306
       apply to, and the origin (can be "cluster", "os X", or "instance Y")
1307

1308
  """
1309
  hvp_data = []
1310

    
1311
  for hv_name in cluster.enabled_hypervisors:
1312
    hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
1313

    
1314
  for os_name, os_hvp in cluster.os_hvp.items():
1315
    for hv_name, hv_params in os_hvp.items():
1316
      if hv_params:
1317
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
1318
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
1319

    
1320
  # TODO: collapse identical parameter values in a single one
1321
  for instance in instances:
1322
    if instance.hvparams:
1323
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
1324
                       cluster.FillHV(instance)))
1325

    
1326
  return hvp_data
1327

    
1328

    
1329
class _VerifyErrors(object):
1330
  """Mix-in for cluster/group verify LUs.
1331

1332
  It provides _Error and _ErrorIf, and updates the self.bad boolean. (Expects
1333
  self.op and self._feedback_fn to be available.)
1334

1335
  """
1336
  TCLUSTER = "cluster"
1337
  TNODE = "node"
1338
  TINSTANCE = "instance"
1339

    
1340
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1341
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1342
  ECLUSTERFILECHECK = (TCLUSTER, "ECLUSTERFILECHECK")
1343
  ECLUSTERDANGLINGNODES = (TNODE, "ECLUSTERDANGLINGNODES")
1344
  ECLUSTERDANGLINGINST = (TNODE, "ECLUSTERDANGLINGINST")
1345
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1346
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1347
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1348
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1349
  EINSTANCEFAULTYDISK = (TINSTANCE, "EINSTANCEFAULTYDISK")
1350
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1351
  EINSTANCESPLITGROUPS = (TINSTANCE, "EINSTANCESPLITGROUPS")
1352
  ENODEDRBD = (TNODE, "ENODEDRBD")
1353
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1354
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1355
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1356
  ENODEHV = (TNODE, "ENODEHV")
1357
  ENODELVM = (TNODE, "ENODELVM")
1358
  ENODEN1 = (TNODE, "ENODEN1")
1359
  ENODENET = (TNODE, "ENODENET")
1360
  ENODEOS = (TNODE, "ENODEOS")
1361
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1362
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1363
  ENODERPC = (TNODE, "ENODERPC")
1364
  ENODESSH = (TNODE, "ENODESSH")
1365
  ENODEVERSION = (TNODE, "ENODEVERSION")
1366
  ENODESETUP = (TNODE, "ENODESETUP")
1367
  ENODETIME = (TNODE, "ENODETIME")
1368
  ENODEOOBPATH = (TNODE, "ENODEOOBPATH")
1369

    
1370
  ETYPE_FIELD = "code"
1371
  ETYPE_ERROR = "ERROR"
1372
  ETYPE_WARNING = "WARNING"
1373

    
1374
  def _Error(self, ecode, item, msg, *args, **kwargs):
1375
    """Format an error message.
1376

1377
    Based on the opcode's error_codes parameter, either format a
1378
    parseable error code, or a simpler error string.
1379

1380
    This must be called only from Exec and functions called from Exec.
1381

1382
    """
1383
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1384
    itype, etxt = ecode
1385
    # first complete the msg
1386
    if args:
1387
      msg = msg % args
1388
    # then format the whole message
1389
    if self.op.error_codes: # This is a mix-in. pylint: disable-msg=E1101
1390
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1391
    else:
1392
      if item:
1393
        item = " " + item
1394
      else:
1395
        item = ""
1396
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1397
    # and finally report it via the feedback_fn
1398
    self._feedback_fn("  - %s" % msg) # Mix-in. pylint: disable-msg=E1101
1399

    
1400
  def _ErrorIf(self, cond, *args, **kwargs):
1401
    """Log an error message if the passed condition is True.
1402

1403
    """
1404
    cond = (bool(cond)
1405
            or self.op.debug_simulate_errors) # pylint: disable-msg=E1101
1406
    if cond:
1407
      self._Error(*args, **kwargs)
1408
    # do not mark the operation as failed for WARN cases only
1409
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1410
      self.bad = self.bad or cond
1411

    
1412

    
1413
class LUClusterVerifyConfig(NoHooksLU, _VerifyErrors):
1414
  """Verifies the cluster config.
1415

1416
  """
1417
  REQ_BGL = True
1418

    
1419
  def _VerifyHVP(self, hvp_data):
1420
    """Verifies locally the syntax of the hypervisor parameters.
1421

1422
    """
1423
    for item, hv_name, hv_params in hvp_data:
1424
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
1425
             (item, hv_name))
1426
      try:
1427
        hv_class = hypervisor.GetHypervisor(hv_name)
1428
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
1429
        hv_class.CheckParameterSyntax(hv_params)
1430
      except errors.GenericError, err:
1431
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
1432

    
1433
  def ExpandNames(self):
1434
    # Information can be safely retrieved as the BGL is acquired in exclusive
1435
    # mode
1436
    self.all_group_info = self.cfg.GetAllNodeGroupsInfo()
1437
    self.all_node_info = self.cfg.GetAllNodesInfo()
1438
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1439
    self.needed_locks = {}
1440

    
1441
  def Exec(self, feedback_fn):
1442
    """Verify integrity of cluster, performing various test on nodes.
1443

1444
    """
1445
    self.bad = False
1446
    self._feedback_fn = feedback_fn
1447

    
1448
    feedback_fn("* Verifying cluster config")
1449

    
1450
    for msg in self.cfg.VerifyConfig():
1451
      self._ErrorIf(True, self.ECLUSTERCFG, None, msg)
1452

    
1453
    feedback_fn("* Verifying cluster certificate files")
1454

    
1455
    for cert_filename in constants.ALL_CERT_FILES:
1456
      (errcode, msg) = _VerifyCertificate(cert_filename)
1457
      self._ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1458

    
1459
    feedback_fn("* Verifying hypervisor parameters")
1460

    
1461
    self._VerifyHVP(_GetAllHypervisorParameters(self.cfg.GetClusterInfo(),
1462
                                                self.all_inst_info.values()))
1463

    
1464
    feedback_fn("* Verifying all nodes belong to an existing group")
1465

    
1466
    # We do this verification here because, should this bogus circumstance
1467
    # occur, it would never be caught by VerifyGroup, which only acts on
1468
    # nodes/instances reachable from existing node groups.
1469

    
1470
    dangling_nodes = set(node.name for node in self.all_node_info.values()
1471
                         if node.group not in self.all_group_info)
1472

    
1473
    dangling_instances = {}
1474
    no_node_instances = []
1475

    
1476
    for inst in self.all_inst_info.values():
1477
      if inst.primary_node in dangling_nodes:
1478
        dangling_instances.setdefault(inst.primary_node, []).append(inst.name)
1479
      elif inst.primary_node not in self.all_node_info:
1480
        no_node_instances.append(inst.name)
1481

    
1482
    pretty_dangling = [
1483
        "%s (%s)" %
1484
        (node.name,
1485
         utils.CommaJoin(dangling_instances.get(node.name,
1486
                                                ["no instances"])))
1487
        for node in dangling_nodes]
1488

    
1489
    self._ErrorIf(bool(dangling_nodes), self.ECLUSTERDANGLINGNODES, None,
1490
                  "the following nodes (and their instances) belong to a non"
1491
                  " existing group: %s", utils.CommaJoin(pretty_dangling))
1492

    
1493
    self._ErrorIf(bool(no_node_instances), self.ECLUSTERDANGLINGINST, None,
1494
                  "the following instances have a non-existing primary-node:"
1495
                  " %s", utils.CommaJoin(no_node_instances))
1496

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

    
1499

    
1500
class LUClusterVerifyGroup(LogicalUnit, _VerifyErrors):
1501
  """Verifies the status of a node group.
1502

1503
  """
1504
  HPATH = "cluster-verify"
1505
  HTYPE = constants.HTYPE_CLUSTER
1506
  REQ_BGL = False
1507

    
1508
  _HOOKS_INDENT_RE = re.compile("^", re.M)
1509

    
1510
  class NodeImage(object):
1511
    """A class representing the logical and physical status of a node.
1512

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

1541
    """
1542
    def __init__(self, offline=False, name=None, vm_capable=True):
1543
      self.name = name
1544
      self.volumes = {}
1545
      self.instances = []
1546
      self.pinst = []
1547
      self.sinst = []
1548
      self.sbp = {}
1549
      self.mfree = 0
1550
      self.dfree = 0
1551
      self.offline = offline
1552
      self.vm_capable = vm_capable
1553
      self.rpc_fail = False
1554
      self.lvm_fail = False
1555
      self.hyp_fail = False
1556
      self.ghost = False
1557
      self.os_fail = False
1558
      self.oslist = {}
1559

    
1560
  def ExpandNames(self):
1561
    # This raises errors.OpPrereqError on its own:
1562
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
1563

    
1564
    # Get instances in node group; this is unsafe and needs verification later
1565
    inst_names = self.cfg.GetNodeGroupInstances(self.group_uuid)
1566

    
1567
    self.needed_locks = {
1568
      locking.LEVEL_INSTANCE: inst_names,
1569
      locking.LEVEL_NODEGROUP: [self.group_uuid],
1570
      locking.LEVEL_NODE: [],
1571
      }
1572

    
1573
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1574

    
1575
  def DeclareLocks(self, level):
1576
    if level == locking.LEVEL_NODE:
1577
      # Get members of node group; this is unsafe and needs verification later
1578
      nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1579

    
1580
      all_inst_info = self.cfg.GetAllInstancesInfo()
1581

    
1582
      # In Exec(), we warn about mirrored instances that have primary and
1583
      # secondary living in separate node groups. To fully verify that
1584
      # volumes for these instances are healthy, we will need to do an
1585
      # extra call to their secondaries. We ensure here those nodes will
1586
      # be locked.
1587
      for inst in self.glm.list_owned(locking.LEVEL_INSTANCE):
1588
        # Important: access only the instances whose lock is owned
1589
        if all_inst_info[inst].disk_template in constants.DTS_INT_MIRROR:
1590
          nodes.update(all_inst_info[inst].secondary_nodes)
1591

    
1592
      self.needed_locks[locking.LEVEL_NODE] = nodes
1593

    
1594
  def CheckPrereq(self):
1595
    group_nodes = set(self.cfg.GetNodeGroup(self.group_uuid).members)
1596
    group_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
1597

    
1598
    unlocked_nodes = \
1599
        group_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1600

    
1601
    unlocked_instances = \
1602
        group_instances.difference(self.glm.list_owned(locking.LEVEL_INSTANCE))
1603

    
1604
    if unlocked_nodes:
1605
      raise errors.OpPrereqError("Missing lock for nodes: %s" %
1606
                                 utils.CommaJoin(unlocked_nodes))
1607

    
1608
    if unlocked_instances:
1609
      raise errors.OpPrereqError("Missing lock for instances: %s" %
1610
                                 utils.CommaJoin(unlocked_instances))
1611

    
1612
    self.all_node_info = self.cfg.GetAllNodesInfo()
1613
    self.all_inst_info = self.cfg.GetAllInstancesInfo()
1614

    
1615
    self.my_node_names = utils.NiceSort(group_nodes)
1616
    self.my_inst_names = utils.NiceSort(group_instances)
1617

    
1618
    self.my_node_info = dict((name, self.all_node_info[name])
1619
                             for name in self.my_node_names)
1620

    
1621
    self.my_inst_info = dict((name, self.all_inst_info[name])
1622
                             for name in self.my_inst_names)
1623

    
1624
    # We detect here the nodes that will need the extra RPC calls for verifying
1625
    # split LV volumes; they should be locked.
1626
    extra_lv_nodes = set()
1627

    
1628
    for inst in self.my_inst_info.values():
1629
      if inst.disk_template in constants.DTS_INT_MIRROR:
1630
        group = self.my_node_info[inst.primary_node].group
1631
        for nname in inst.secondary_nodes:
1632
          if self.all_node_info[nname].group != group:
1633
            extra_lv_nodes.add(nname)
1634

    
1635
    unlocked_lv_nodes = \
1636
        extra_lv_nodes.difference(self.glm.list_owned(locking.LEVEL_NODE))
1637

    
1638
    if unlocked_lv_nodes:
1639
      raise errors.OpPrereqError("these nodes could be locked: %s" %
1640
                                 utils.CommaJoin(unlocked_lv_nodes))
1641
    self.extra_lv_nodes = list(extra_lv_nodes)
1642

    
1643
  def _VerifyNode(self, ninfo, nresult):
1644
    """Perform some basic validation on data returned from a node.
1645

1646
      - check the result data structure is well formed and has all the
1647
        mandatory fields
1648
      - check ganeti version
1649

1650
    @type ninfo: L{objects.Node}
1651
    @param ninfo: the node to check
1652
    @param nresult: the results from the node
1653
    @rtype: boolean
1654
    @return: whether overall this call was successful (and we can expect
1655
         reasonable values in the respose)
1656

1657
    """
1658
    node = ninfo.name
1659
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1660

    
1661
    # main result, nresult should be a non-empty dict
1662
    test = not nresult or not isinstance(nresult, dict)
1663
    _ErrorIf(test, self.ENODERPC, node,
1664
                  "unable to verify node: no data returned")
1665
    if test:
1666
      return False
1667

    
1668
    # compares ganeti version
1669
    local_version = constants.PROTOCOL_VERSION
1670
    remote_version = nresult.get("version", None)
1671
    test = not (remote_version and
1672
                isinstance(remote_version, (list, tuple)) and
1673
                len(remote_version) == 2)
1674
    _ErrorIf(test, self.ENODERPC, node,
1675
             "connection to node returned invalid data")
1676
    if test:
1677
      return False
1678

    
1679
    test = local_version != remote_version[0]
1680
    _ErrorIf(test, self.ENODEVERSION, node,
1681
             "incompatible protocol versions: master %s,"
1682
             " node %s", local_version, remote_version[0])
1683
    if test:
1684
      return False
1685

    
1686
    # node seems compatible, we can actually try to look into its results
1687

    
1688
    # full package version
1689
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1690
                  self.ENODEVERSION, node,
1691
                  "software version mismatch: master %s, node %s",
1692
                  constants.RELEASE_VERSION, remote_version[1],
1693
                  code=self.ETYPE_WARNING)
1694

    
1695
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1696
    if ninfo.vm_capable and isinstance(hyp_result, dict):
1697
      for hv_name, hv_result in hyp_result.iteritems():
1698
        test = hv_result is not None
1699
        _ErrorIf(test, self.ENODEHV, node,
1700
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1701

    
1702
    hvp_result = nresult.get(constants.NV_HVPARAMS, None)
1703
    if ninfo.vm_capable and isinstance(hvp_result, list):
1704
      for item, hv_name, hv_result in hvp_result:
1705
        _ErrorIf(True, self.ENODEHV, node,
1706
                 "hypervisor %s parameter verify failure (source %s): %s",
1707
                 hv_name, item, hv_result)
1708

    
1709
    test = nresult.get(constants.NV_NODESETUP,
1710
                       ["Missing NODESETUP results"])
1711
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1712
             "; ".join(test))
1713

    
1714
    return True
1715

    
1716
  def _VerifyNodeTime(self, ninfo, nresult,
1717
                      nvinfo_starttime, nvinfo_endtime):
1718
    """Check the node time.
1719

1720
    @type ninfo: L{objects.Node}
1721
    @param ninfo: the node to check
1722
    @param nresult: the remote results for the node
1723
    @param nvinfo_starttime: the start time of the RPC call
1724
    @param nvinfo_endtime: the end time of the RPC call
1725

1726
    """
1727
    node = ninfo.name
1728
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1729

    
1730
    ntime = nresult.get(constants.NV_TIME, None)
1731
    try:
1732
      ntime_merged = utils.MergeTime(ntime)
1733
    except (ValueError, TypeError):
1734
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1735
      return
1736

    
1737
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1738
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1739
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1740
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1741
    else:
1742
      ntime_diff = None
1743

    
1744
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1745
             "Node time diverges by at least %s from master node time",
1746
             ntime_diff)
1747

    
1748
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1749
    """Check the node LVM results.
1750

1751
    @type ninfo: L{objects.Node}
1752
    @param ninfo: the node to check
1753
    @param nresult: the remote results for the node
1754
    @param vg_name: the configured VG name
1755

1756
    """
1757
    if vg_name is None:
1758
      return
1759

    
1760
    node = ninfo.name
1761
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1762

    
1763
    # checks vg existence and size > 20G
1764
    vglist = nresult.get(constants.NV_VGLIST, None)
1765
    test = not vglist
1766
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1767
    if not test:
1768
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1769
                                            constants.MIN_VG_SIZE)
1770
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1771

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

    
1785
  def _VerifyNodeBridges(self, ninfo, nresult, bridges):
1786
    """Check the node bridges.
1787

1788
    @type ninfo: L{objects.Node}
1789
    @param ninfo: the node to check
1790
    @param nresult: the remote results for the node
1791
    @param bridges: the expected list of bridges
1792

1793
    """
1794
    if not bridges:
1795
      return
1796

    
1797
    node = ninfo.name
1798
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1799

    
1800
    missing = nresult.get(constants.NV_BRIDGES, None)
1801
    test = not isinstance(missing, list)
1802
    _ErrorIf(test, self.ENODENET, node,
1803
             "did not return valid bridge information")
1804
    if not test:
1805
      _ErrorIf(bool(missing), self.ENODENET, node, "missing bridges: %s" %
1806
               utils.CommaJoin(sorted(missing)))
1807

    
1808
  def _VerifyNodeNetwork(self, ninfo, nresult):
1809
    """Check the node network connectivity results.
1810

1811
    @type ninfo: L{objects.Node}
1812
    @param ninfo: the node to check
1813
    @param nresult: the remote results for the node
1814

1815
    """
1816
    node = ninfo.name
1817
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1818

    
1819
    test = constants.NV_NODELIST not in nresult
1820
    _ErrorIf(test, self.ENODESSH, node,
1821
             "node hasn't returned node ssh connectivity data")
1822
    if not test:
1823
      if nresult[constants.NV_NODELIST]:
1824
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1825
          _ErrorIf(True, self.ENODESSH, node,
1826
                   "ssh communication with node '%s': %s", a_node, a_msg)
1827

    
1828
    test = constants.NV_NODENETTEST not in nresult
1829
    _ErrorIf(test, self.ENODENET, node,
1830
             "node hasn't returned node tcp connectivity data")
1831
    if not test:
1832
      if nresult[constants.NV_NODENETTEST]:
1833
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1834
        for anode in nlist:
1835
          _ErrorIf(True, self.ENODENET, node,
1836
                   "tcp communication with node '%s': %s",
1837
                   anode, nresult[constants.NV_NODENETTEST][anode])
1838

    
1839
    test = constants.NV_MASTERIP not in nresult
1840
    _ErrorIf(test, self.ENODENET, node,
1841
             "node hasn't returned node master IP reachability data")
1842
    if not test:
1843
      if not nresult[constants.NV_MASTERIP]:
1844
        if node == self.master_node:
1845
          msg = "the master node cannot reach the master IP (not configured?)"
1846
        else:
1847
          msg = "cannot reach the master IP"
1848
        _ErrorIf(True, self.ENODENET, node, msg)
1849

    
1850
  def _VerifyInstance(self, instance, instanceconfig, node_image,
1851
                      diskstatus):
1852
    """Verify an instance.
1853

1854
    This function checks to see if the required block devices are
1855
    available on the instance's node.
1856

1857
    """
1858
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1859
    node_current = instanceconfig.primary_node
1860

    
1861
    node_vol_should = {}
1862
    instanceconfig.MapLVsByNode(node_vol_should)
1863

    
1864
    for node in node_vol_should:
1865
      n_img = node_image[node]
1866
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1867
        # ignore missing volumes on offline or broken nodes
1868
        continue
1869
      for volume in node_vol_should[node]:
1870
        test = volume not in n_img.volumes
1871
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1872
                 "volume %s missing on node %s", volume, node)
1873

    
1874
    if instanceconfig.admin_up:
1875
      pri_img = node_image[node_current]
1876
      test = instance not in pri_img.instances and not pri_img.offline
1877
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1878
               "instance not running on its primary node %s",
1879
               node_current)
1880

    
1881
    diskdata = [(nname, success, status, idx)
1882
                for (nname, disks) in diskstatus.items()
1883
                for idx, (success, status) in enumerate(disks)]
1884

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

    
1899
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1900
    """Verify if there are any unknown volumes in the cluster.
1901

1902
    The .os, .swap and backup volumes are ignored. All other volumes are
1903
    reported as unknown.
1904

1905
    @type reserved: L{ganeti.utils.FieldSet}
1906
    @param reserved: a FieldSet of reserved volume names
1907

1908
    """
1909
    for node, n_img in node_image.items():
1910
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1911
        # skip non-healthy nodes
1912
        continue
1913
      for volume in n_img.volumes:
1914
        test = ((node not in node_vol_should or
1915
                volume not in node_vol_should[node]) and
1916
                not reserved.Matches(volume))
1917
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1918
                      "volume %s is unknown", volume)
1919

    
1920
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1921
    """Verify N+1 Memory Resilience.
1922

1923
    Check that if one single node dies we can still start all the
1924
    instances it was primary for.
1925

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

    
1955
  @classmethod
1956
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1957
                   (files_all, files_all_opt, files_mc, files_vm)):
1958
    """Verifies file checksums collected from all nodes.
1959

1960
    @param errorif: Callback for reporting errors
1961
    @param nodeinfo: List of L{objects.Node} objects
1962
    @param master_node: Name of master node
1963
    @param all_nvinfo: RPC results
1964

1965
    """
1966
    node_names = frozenset(node.name for node in nodeinfo)
1967

    
1968
    assert master_node in node_names
1969
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1970
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1971
           "Found file listed in more than one file list"
1972

    
1973
    # Define functions determining which nodes to consider for a file
1974
    file2nodefn = dict([(filename, fn)
1975
      for (files, fn) in [(files_all, None),
1976
                          (files_all_opt, None),
1977
                          (files_mc, lambda node: (node.master_candidate or
1978
                                                   node.name == master_node)),
1979
                          (files_vm, lambda node: node.vm_capable)]
1980
      for filename in files])
1981

    
1982
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1983

    
1984
    for node in nodeinfo:
1985
      nresult = all_nvinfo[node.name]
1986

    
1987
      if nresult.fail_msg or not nresult.payload:
1988
        node_files = None
1989
      else:
1990
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1991

    
1992
      test = not (node_files and isinstance(node_files, dict))
1993
      errorif(test, cls.ENODEFILECHECK, node.name,
1994
              "Node did not return file checksum data")
1995
      if test:
1996
        continue
1997

    
1998
      for (filename, checksum) in node_files.items():
1999
        # Check if the file should be considered for a node
2000
        fn = file2nodefn[filename]
2001
        if fn is None or fn(node):
2002
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
2003

    
2004
    for (filename, checksums) in fileinfo.items():
2005
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
2006

    
2007
      # Nodes having the file
2008
      with_file = frozenset(node_name
2009
                            for nodes in fileinfo[filename].values()
2010
                            for node_name in nodes)
2011

    
2012
      # Nodes missing file
2013
      missing_file = node_names - with_file
2014

    
2015
      if filename in files_all_opt:
2016
        # All or no nodes
2017
        errorif(missing_file and missing_file != node_names,
2018
                cls.ECLUSTERFILECHECK, None,
2019
                "File %s is optional, but it must exist on all or no"
2020
                " nodes (not found on %s)",
2021
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
2022
      else:
2023
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
2024
                "File %s is missing from node(s) %s", filename,
2025
                utils.CommaJoin(utils.NiceSort(missing_file)))
2026

    
2027
      # See if there are multiple versions of the file
2028
      test = len(checksums) > 1
2029
      if test:
2030
        variants = ["variant %s on %s" %
2031
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
2032
                    for (idx, (checksum, nodes)) in
2033
                      enumerate(sorted(checksums.items()))]
2034
      else:
2035
        variants = []
2036

    
2037
      errorif(test, cls.ECLUSTERFILECHECK, None,
2038
              "File %s found with %s different checksums (%s)",
2039
              filename, len(checksums), "; ".join(variants))
2040

    
2041
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
2042
                      drbd_map):
2043
    """Verifies and the node DRBD status.
2044

2045
    @type ninfo: L{objects.Node}
2046
    @param ninfo: the node to check
2047
    @param nresult: the remote results for the node
2048
    @param instanceinfo: the dict of instances
2049
    @param drbd_helper: the configured DRBD usermode helper
2050
    @param drbd_map: the DRBD map as returned by
2051
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
2052

2053
    """
2054
    node = ninfo.name
2055
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2056

    
2057
    if drbd_helper:
2058
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
2059
      test = (helper_result == None)
2060
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
2061
               "no drbd usermode helper returned")
2062
      if helper_result:
2063
        status, payload = helper_result
2064
        test = not status
2065
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2066
                 "drbd usermode helper check unsuccessful: %s", payload)
2067
        test = status and (payload != drbd_helper)
2068
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
2069
                 "wrong drbd usermode helper: %s", payload)
2070

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

    
2086
    # and now check them
2087
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
2088
    test = not isinstance(used_minors, (tuple, list))
2089
    _ErrorIf(test, self.ENODEDRBD, node,
2090
             "cannot parse drbd status file: %s", str(used_minors))
2091
    if test:
2092
      # we cannot check drbd status
2093
      return
2094

    
2095
    for minor, (iname, must_exist) in node_drbd.items():
2096
      test = minor not in used_minors and must_exist
2097
      _ErrorIf(test, self.ENODEDRBD, node,
2098
               "drbd minor %d of instance %s is not active", minor, iname)
2099
    for minor in used_minors:
2100
      test = minor not in node_drbd
2101
      _ErrorIf(test, self.ENODEDRBD, node,
2102
               "unallocated drbd minor %d is in use", minor)
2103

    
2104
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
2105
    """Builds the node OS structures.
2106

2107
    @type ninfo: L{objects.Node}
2108
    @param ninfo: the node to check
2109
    @param nresult: the remote results for the node
2110
    @param nimg: the node image object
2111

2112
    """
2113
    node = ninfo.name
2114
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2115

    
2116
    remote_os = nresult.get(constants.NV_OSLIST, None)
2117
    test = (not isinstance(remote_os, list) or
2118
            not compat.all(isinstance(v, list) and len(v) == 7
2119
                           for v in remote_os))
2120

    
2121
    _ErrorIf(test, self.ENODEOS, node,
2122
             "node hasn't returned valid OS data")
2123

    
2124
    nimg.os_fail = test
2125

    
2126
    if test:
2127
      return
2128

    
2129
    os_dict = {}
2130

    
2131
    for (name, os_path, status, diagnose,
2132
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
2133

    
2134
      if name not in os_dict:
2135
        os_dict[name] = []
2136

    
2137
      # parameters is a list of lists instead of list of tuples due to
2138
      # JSON lacking a real tuple type, fix it:
2139
      parameters = [tuple(v) for v in parameters]
2140
      os_dict[name].append((os_path, status, diagnose,
2141
                            set(variants), set(parameters), set(api_ver)))
2142

    
2143
    nimg.oslist = os_dict
2144

    
2145
  def _VerifyNodeOS(self, ninfo, nimg, base):
2146
    """Verifies the node OS list.
2147

2148
    @type ninfo: L{objects.Node}
2149
    @param ninfo: the node to check
2150
    @param nimg: the node image object
2151
    @param base: the 'template' node we match against (e.g. from the master)
2152

2153
    """
2154
    node = ninfo.name
2155
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2156

    
2157
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
2158

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

    
2194
    # check any missing OSes
2195
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
2196
    _ErrorIf(missing, self.ENODEOS, node,
2197
             "OSes present on reference node %s but missing on this node: %s",
2198
             base.name, utils.CommaJoin(missing))
2199

    
2200
  def _VerifyOob(self, ninfo, nresult):
2201
    """Verifies out of band functionality of a node.
2202

2203
    @type ninfo: L{objects.Node}
2204
    @param ninfo: the node to check
2205
    @param nresult: the remote results for the node
2206

2207
    """
2208
    node = ninfo.name
2209
    # We just have to verify the paths on master and/or master candidates
2210
    # as the oob helper is invoked on the master
2211
    if ((ninfo.master_candidate or ninfo.master_capable) and
2212
        constants.NV_OOB_PATHS in nresult):
2213
      for path_result in nresult[constants.NV_OOB_PATHS]:
2214
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2215

    
2216
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2217
    """Verifies and updates the node volume data.
2218

2219
    This function will update a L{NodeImage}'s internal structures
2220
    with data from the remote call.
2221

2222
    @type ninfo: L{objects.Node}
2223
    @param ninfo: the node to check
2224
    @param nresult: the remote results for the node
2225
    @param nimg: the node image object
2226
    @param vg_name: the configured VG name
2227

2228
    """
2229
    node = ninfo.name
2230
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2231

    
2232
    nimg.lvm_fail = True
2233
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2234
    if vg_name is None:
2235
      pass
2236
    elif isinstance(lvdata, basestring):
2237
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2238
               utils.SafeEncode(lvdata))
2239
    elif not isinstance(lvdata, dict):
2240
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2241
    else:
2242
      nimg.volumes = lvdata
2243
      nimg.lvm_fail = False
2244

    
2245
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2246
    """Verifies and updates the node instance list.
2247

2248
    If the listing was successful, then updates this node's instance
2249
    list. Otherwise, it marks the RPC call as failed for the instance
2250
    list key.
2251

2252
    @type ninfo: L{objects.Node}
2253
    @param ninfo: the node to check
2254
    @param nresult: the remote results for the node
2255
    @param nimg: the node image object
2256

2257
    """
2258
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2259
    test = not isinstance(idata, list)
2260
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2261
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2262
    if test:
2263
      nimg.hyp_fail = True
2264
    else:
2265
      nimg.instances = idata
2266

    
2267
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2268
    """Verifies and computes a node information map
2269

2270
    @type ninfo: L{objects.Node}
2271
    @param ninfo: the node to check
2272
    @param nresult: the remote results for the node
2273
    @param nimg: the node image object
2274
    @param vg_name: the configured VG name
2275

2276
    """
2277
    node = ninfo.name
2278
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2279

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

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

    
2305
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2306
    """Gets per-disk status information for all instances.
2307

2308
    @type nodelist: list of strings
2309
    @param nodelist: Node names
2310
    @type node_image: dict of (name, L{objects.Node})
2311
    @param node_image: Node objects
2312
    @type instanceinfo: dict of (name, L{objects.Instance})
2313
    @param instanceinfo: Instance objects
2314
    @rtype: {instance: {node: [(succes, payload)]}}
2315
    @return: a dictionary of per-instance dictionaries with nodes as
2316
        keys and disk information as values; the disk information is a
2317
        list of tuples (success, payload)
2318

2319
    """
2320
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2321

    
2322
    node_disks = {}
2323
    node_disks_devonly = {}
2324
    diskless_instances = set()
2325
    diskless = constants.DT_DISKLESS
2326

    
2327
    for nname in nodelist:
2328
      node_instances = list(itertools.chain(node_image[nname].pinst,
2329
                                            node_image[nname].sinst))
2330
      diskless_instances.update(inst for inst in node_instances
2331
                                if instanceinfo[inst].disk_template == diskless)
2332
      disks = [(inst, disk)
2333
               for inst in node_instances
2334
               for disk in instanceinfo[inst].disks]
2335

    
2336
      if not disks:
2337
        # No need to collect data
2338
        continue
2339

    
2340
      node_disks[nname] = disks
2341

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

    
2346
      for dev in devonly:
2347
        self.cfg.SetDiskID(dev, nname)
2348

    
2349
      node_disks_devonly[nname] = devonly
2350

    
2351
    assert len(node_disks) == len(node_disks_devonly)
2352

    
2353
    # Collect data from all nodes with disks
2354
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2355
                                                          node_disks_devonly)
2356

    
2357
    assert len(result) == len(node_disks)
2358

    
2359
    instdisk = {}
2360

    
2361
    for (nname, nres) in result.items():
2362
      disks = node_disks[nname]
2363

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

    
2384
      for ((inst, _), status) in zip(disks, data):
2385
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2386

    
2387
    # Add empty entries for diskless instances.
2388
    for inst in diskless_instances:
2389
      assert inst not in instdisk
2390
      instdisk[inst] = {}
2391

    
2392
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2393
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2394
                      compat.all(isinstance(s, (tuple, list)) and
2395
                                 len(s) == 2 for s in statuses)
2396
                      for inst, nnames in instdisk.items()
2397
                      for nname, statuses in nnames.items())
2398
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2399

    
2400
    return instdisk
2401

    
2402
  def BuildHooksEnv(self):
2403
    """Build hooks env.
2404

2405
    Cluster-Verify hooks just ran in the post phase and their failure makes
2406
    the output be logged in the verify output and the verification to fail.
2407

2408
    """
2409
    env = {
2410
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2411
      }
2412

    
2413
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2414
               for node in self.my_node_info.values())
2415

    
2416
    return env
2417

    
2418
  def BuildHooksNodes(self):
2419
    """Build hooks nodes.
2420

2421
    """
2422
    return ([], self.my_node_names)
2423

    
2424
  def Exec(self, feedback_fn):
2425
    """Verify integrity of the node group, performing various test on nodes.
2426

2427
    """
2428
    # This method has too many local variables. pylint: disable-msg=R0914
2429

    
2430
    if not self.my_node_names:
2431
      # empty node group
2432
      feedback_fn("* Empty node group, skipping verification")
2433
      return True
2434

    
2435
    self.bad = False
2436
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2437
    verbose = self.op.verbose
2438
    self._feedback_fn = feedback_fn
2439

    
2440
    vg_name = self.cfg.GetVGName()
2441
    drbd_helper = self.cfg.GetDRBDHelper()
2442
    cluster = self.cfg.GetClusterInfo()
2443
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2444
    hypervisors = cluster.enabled_hypervisors
2445
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2446

    
2447
    i_non_redundant = [] # Non redundant instances
2448
    i_non_a_balanced = [] # Non auto-balanced instances
2449
    n_offline = 0 # Count of offline nodes
2450
    n_drained = 0 # Count of nodes being drained
2451
    node_vol_should = {}
2452

    
2453
    # FIXME: verify OS list
2454

    
2455
    # File verification
2456
    filemap = _ComputeAncillaryFiles(cluster, False)
2457

    
2458
    # do local checksums
2459
    master_node = self.master_node = self.cfg.GetMasterNode()
2460
    master_ip = self.cfg.GetMasterIP()
2461

    
2462
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2463

    
2464
    # We will make nodes contact all nodes in their group, and one node from
2465
    # every other group.
2466
    # TODO: should it be a *random* node, different every time?
2467
    online_nodes = [node.name for node in node_data_list if not node.offline]
2468
    other_group_nodes = {}
2469

    
2470
    for name in sorted(self.all_node_info):
2471
      node = self.all_node_info[name]
2472
      if (node.group not in other_group_nodes
2473
          and node.group != self.group_uuid
2474
          and not node.offline):
2475
        other_group_nodes[node.group] = node.name
2476

    
2477
    node_verify_param = {
2478
      constants.NV_FILELIST:
2479
        utils.UniqueSequence(filename
2480
                             for files in filemap
2481
                             for filename in files),
2482
      constants.NV_NODELIST: online_nodes + other_group_nodes.values(),
2483
      constants.NV_HYPERVISOR: hypervisors,
2484
      constants.NV_HVPARAMS:
2485
        _GetAllHypervisorParameters(cluster, self.all_inst_info.values()),
2486
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2487
                                 for node in node_data_list
2488
                                 if not node.offline],
2489
      constants.NV_INSTANCELIST: hypervisors,
2490
      constants.NV_VERSION: None,
2491
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2492
      constants.NV_NODESETUP: None,
2493
      constants.NV_TIME: None,
2494
      constants.NV_MASTERIP: (master_node, master_ip),
2495
      constants.NV_OSLIST: None,
2496
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2497
      }
2498

    
2499
    if vg_name is not None:
2500
      node_verify_param[constants.NV_VGLIST] = None
2501
      node_verify_param[constants.NV_LVLIST] = vg_name
2502
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2503
      node_verify_param[constants.NV_DRBDLIST] = None
2504

    
2505
    if drbd_helper:
2506
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2507

    
2508
    # bridge checks
2509
    # FIXME: this needs to be changed per node-group, not cluster-wide
2510
    bridges = set()
2511
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2512
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2513
      bridges.add(default_nicpp[constants.NIC_LINK])
2514
    for instance in self.my_inst_info.values():
2515
      for nic in instance.nics:
2516
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2517
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2518
          bridges.add(full_nic[constants.NIC_LINK])
2519

    
2520
    if bridges:
2521
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2522

    
2523
    # Build our expected cluster state
2524
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2525
                                                 name=node.name,
2526
                                                 vm_capable=node.vm_capable))
2527
                      for node in node_data_list)
2528

    
2529
    # Gather OOB paths
2530
    oob_paths = []
2531
    for node in self.all_node_info.values():
2532
      path = _SupportsOob(self.cfg, node)
2533
      if path and path not in oob_paths:
2534
        oob_paths.append(path)
2535

    
2536
    if oob_paths:
2537
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2538

    
2539
    for instance in self.my_inst_names:
2540
      inst_config = self.my_inst_info[instance]
2541

    
2542
      for nname in inst_config.all_nodes:
2543
        if nname not in node_image:
2544
          gnode = self.NodeImage(name=nname)
2545
          gnode.ghost = (nname not in self.all_node_info)
2546
          node_image[nname] = gnode
2547

    
2548
      inst_config.MapLVsByNode(node_vol_should)
2549

    
2550
      pnode = inst_config.primary_node
2551
      node_image[pnode].pinst.append(instance)
2552

    
2553
      for snode in inst_config.secondary_nodes:
2554
        nimg = node_image[snode]
2555
        nimg.sinst.append(instance)
2556
        if pnode not in nimg.sbp:
2557
          nimg.sbp[pnode] = []
2558
        nimg.sbp[pnode].append(instance)
2559

    
2560
    # At this point, we have the in-memory data structures complete,
2561
    # except for the runtime information, which we'll gather next
2562

    
2563
    # Due to the way our RPC system works, exact response times cannot be
2564
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2565
    # time before and after executing the request, we can at least have a time
2566
    # window.
2567
    nvinfo_starttime = time.time()
2568
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2569
                                           node_verify_param,
2570
                                           self.cfg.GetClusterName())
2571
    nvinfo_endtime = time.time()
2572

    
2573
    if self.extra_lv_nodes and vg_name is not None:
2574
      extra_lv_nvinfo = \
2575
          self.rpc.call_node_verify(self.extra_lv_nodes,
2576
                                    {constants.NV_LVLIST: vg_name},
2577
                                    self.cfg.GetClusterName())
2578
    else:
2579
      extra_lv_nvinfo = {}
2580

    
2581
    all_drbd_map = self.cfg.ComputeDRBDMap()
2582

    
2583
    feedback_fn("* Gathering disk information (%s nodes)" %
2584
                len(self.my_node_names))
2585
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2586
                                     self.my_inst_info)
2587

    
2588
    feedback_fn("* Verifying configuration file consistency")
2589

    
2590
    # If not all nodes are being checked, we need to make sure the master node
2591
    # and a non-checked vm_capable node are in the list.
2592
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2593
    if absent_nodes:
2594
      vf_nvinfo = all_nvinfo.copy()
2595
      vf_node_info = list(self.my_node_info.values())
2596
      additional_nodes = []
2597
      if master_node not in self.my_node_info:
2598
        additional_nodes.append(master_node)
2599
        vf_node_info.append(self.all_node_info[master_node])
2600
      # Add the first vm_capable node we find which is not included
2601
      for node in absent_nodes:
2602
        nodeinfo = self.all_node_info[node]
2603
        if nodeinfo.vm_capable and not nodeinfo.offline:
2604
          additional_nodes.append(node)
2605
          vf_node_info.append(self.all_node_info[node])
2606
          break
2607
      key = constants.NV_FILELIST
2608
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2609
                                                 {key: node_verify_param[key]},
2610
                                                 self.cfg.GetClusterName()))
2611
    else:
2612
      vf_nvinfo = all_nvinfo
2613
      vf_node_info = self.my_node_info.values()
2614

    
2615
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2616

    
2617
    feedback_fn("* Verifying node status")
2618

    
2619
    refos_img = None
2620

    
2621
    for node_i in node_data_list:
2622
      node = node_i.name
2623
      nimg = node_image[node]
2624

    
2625
      if node_i.offline:
2626
        if verbose:
2627
          feedback_fn("* Skipping offline node %s" % (node,))
2628
        n_offline += 1
2629
        continue
2630

    
2631
      if node == master_node:
2632
        ntype = "master"
2633
      elif node_i.master_candidate:
2634
        ntype = "master candidate"
2635
      elif node_i.drained:
2636
        ntype = "drained"
2637
        n_drained += 1
2638
      else:
2639
        ntype = "regular"
2640
      if verbose:
2641
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2642

    
2643
      msg = all_nvinfo[node].fail_msg
2644
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2645
      if msg:
2646
        nimg.rpc_fail = True
2647
        continue
2648

    
2649
      nresult = all_nvinfo[node].payload
2650

    
2651
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2652
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2653
      self._VerifyNodeNetwork(node_i, nresult)
2654
      self._VerifyOob(node_i, nresult)
2655

    
2656
      if nimg.vm_capable:
2657
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2658
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2659
                             all_drbd_map)
2660

    
2661
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2662
        self._UpdateNodeInstances(node_i, nresult, nimg)
2663
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2664
        self._UpdateNodeOS(node_i, nresult, nimg)
2665

    
2666
        if not nimg.os_fail:
2667
          if refos_img is None:
2668
            refos_img = nimg
2669
          self._VerifyNodeOS(node_i, nimg, refos_img)
2670
        self._VerifyNodeBridges(node_i, nresult, bridges)
2671

    
2672
        # Check whether all running instancies are primary for the node. (This
2673
        # can no longer be done from _VerifyInstance below, since some of the
2674
        # wrong instances could be from other node groups.)
2675
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2676

    
2677
        for inst in non_primary_inst:
2678
          test = inst in self.all_inst_info
2679
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2680
                   "instance should not run on node %s", node_i.name)
2681
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2682
                   "node is running unknown instance %s", inst)
2683

    
2684
    for node, result in extra_lv_nvinfo.items():
2685
      self._UpdateNodeVolumes(self.all_node_info[node], result.payload,
2686
                              node_image[node], vg_name)
2687

    
2688
    feedback_fn("* Verifying instance status")
2689
    for instance in self.my_inst_names:
2690
      if verbose:
2691
        feedback_fn("* Verifying instance %s" % instance)
2692
      inst_config = self.my_inst_info[instance]
2693
      self._VerifyInstance(instance, inst_config, node_image,
2694
                           instdisk[instance])
2695
      inst_nodes_offline = []
2696

    
2697
      pnode = inst_config.primary_node
2698
      pnode_img = node_image[pnode]
2699
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2700
               self.ENODERPC, pnode, "instance %s, connection to"
2701
               " primary node failed", instance)
2702

    
2703
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2704
               self.EINSTANCEBADNODE, instance,
2705
               "instance is marked as running and lives on offline node %s",
2706
               inst_config.primary_node)
2707

    
2708
      # If the instance is non-redundant we cannot survive losing its primary
2709
      # node, so we are not N+1 compliant. On the other hand we have no disk
2710
      # templates with more than one secondary so that situation is not well
2711
      # supported either.
2712
      # FIXME: does not support file-backed instances
2713
      if not inst_config.secondary_nodes:
2714
        i_non_redundant.append(instance)
2715

    
2716
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2717
               instance, "instance has multiple secondary nodes: %s",
2718
               utils.CommaJoin(inst_config.secondary_nodes),
2719
               code=self.ETYPE_WARNING)
2720

    
2721
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2722
        pnode = inst_config.primary_node
2723
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2724
        instance_groups = {}
2725

    
2726
        for node in instance_nodes:
2727
          instance_groups.setdefault(self.all_node_info[node].group,
2728
                                     []).append(node)
2729

    
2730
        pretty_list = [
2731
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2732
          # Sort so that we always list the primary node first.
2733
          for group, nodes in sorted(instance_groups.items(),
2734
                                     key=lambda (_, nodes): pnode in nodes,
2735
                                     reverse=True)]
2736

    
2737
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2738
                      instance, "instance has primary and secondary nodes in"
2739
                      " different groups: %s", utils.CommaJoin(pretty_list),
2740
                      code=self.ETYPE_WARNING)
2741

    
2742
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2743
        i_non_a_balanced.append(instance)
2744

    
2745
      for snode in inst_config.secondary_nodes:
2746
        s_img = node_image[snode]
2747
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2748
                 "instance %s, connection to secondary node failed", instance)
2749

    
2750
        if s_img.offline:
2751
          inst_nodes_offline.append(snode)
2752

    
2753
      # warn that the instance lives on offline nodes
2754
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2755
               "instance has offline secondary node(s) %s",
2756
               utils.CommaJoin(inst_nodes_offline))
2757
      # ... or ghost/non-vm_capable nodes
2758
      for node in inst_config.all_nodes:
2759
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2760
                 "instance lives on ghost node %s", node)
2761
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2762
                 instance, "instance lives on non-vm_capable node %s", node)
2763

    
2764
    feedback_fn("* Verifying orphan volumes")
2765
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2766

    
2767
    # We will get spurious "unknown volume" warnings if any node of this group
2768
    # is secondary for an instance whose primary is in another group. To avoid
2769
    # them, we find these instances and add their volumes to node_vol_should.
2770
    for inst in self.all_inst_info.values():
2771
      for secondary in inst.secondary_nodes:
2772
        if (secondary in self.my_node_info
2773
            and inst.name not in self.my_inst_info):
2774
          inst.MapLVsByNode(node_vol_should)
2775
          break
2776

    
2777
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2778

    
2779
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2780
      feedback_fn("* Verifying N+1 Memory redundancy")
2781
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2782

    
2783
    feedback_fn("* Other Notes")
2784
    if i_non_redundant:
2785
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2786
                  % len(i_non_redundant))
2787

    
2788
    if i_non_a_balanced:
2789
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2790
                  % len(i_non_a_balanced))
2791

    
2792
    if n_offline:
2793
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2794

    
2795
    if n_drained:
2796
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2797

    
2798
    return not self.bad
2799

    
2800
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2801
    """Analyze the post-hooks' result
2802

2803
    This method analyses the hook result, handles it, and sends some
2804
    nicely-formatted feedback back to the user.
2805

2806
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2807
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2808
    @param hooks_results: the results of the multi-node hooks rpc call
2809
    @param feedback_fn: function used send feedback back to the caller
2810
    @param lu_result: previous Exec result
2811
    @return: the new Exec result, based on the previous result
2812
        and hook results
2813

2814
    """
2815
    # We only really run POST phase hooks, only for non-empty groups,
2816
    # and are only interested in their results
2817
    if not self.my_node_names:
2818
      # empty node group
2819
      pass
2820
    elif phase == constants.HOOKS_PHASE_POST:
2821
      # Used to change hooks' output to proper indentation
2822
      feedback_fn("* Hooks Results")
2823
      assert hooks_results, "invalid result from hooks"
2824

    
2825
      for node_name in hooks_results:
2826
        res = hooks_results[node_name]
2827
        msg = res.fail_msg
2828
        test = msg and not res.offline
2829
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2830
                      "Communication failure in hooks execution: %s", msg)
2831
        if res.offline or msg:
2832
          # No need to investigate payload if node is offline or gave an error.
2833
          # override manually lu_result here as _ErrorIf only
2834
          # overrides self.bad
2835
          lu_result = 1
2836
          continue
2837
        for script, hkr, output in res.payload:
2838
          test = hkr == constants.HKR_FAIL
2839
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2840
                        "Script %s failed, output:", script)
2841
          if test:
2842
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2843
            feedback_fn("%s" % output)
2844
            lu_result = 0
2845

    
2846
    return lu_result
2847

    
2848

    
2849
class LUClusterVerifyDisks(NoHooksLU):
2850
  """Verifies the cluster disks status.
2851

2852
  """
2853
  REQ_BGL = False
2854

    
2855
  def ExpandNames(self):
2856
    self.needed_locks = {
2857
      locking.LEVEL_NODE: locking.ALL_SET,
2858
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2859
    }
2860
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2861

    
2862
  def Exec(self, feedback_fn):
2863
    """Verify integrity of cluster disks.
2864

2865
    @rtype: tuple of three items
2866
    @return: a tuple of (dict of node-to-node_error, list of instances
2867
        which need activate-disks, dict of instance: (node, volume) for
2868
        missing volumes
2869

2870
    """
2871
    result = res_nodes, res_instances, res_missing = {}, [], {}
2872

    
2873
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2874
    instances = self.cfg.GetAllInstancesInfo().values()
2875

    
2876
    nv_dict = {}
2877
    for inst in instances:
2878
      inst_lvs = {}
2879
      if not inst.admin_up:
2880
        continue
2881
      inst.MapLVsByNode(inst_lvs)
2882
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2883
      for node, vol_list in inst_lvs.iteritems():
2884
        for vol in vol_list:
2885
          nv_dict[(node, vol)] = inst
2886

    
2887
    if not nv_dict:
2888
      return result
2889

    
2890
    node_lvs = self.rpc.call_lv_list(nodes, [])
2891
    for node, node_res in node_lvs.items():
2892
      if node_res.offline:
2893
        continue
2894
      msg = node_res.fail_msg
2895
      if msg:
2896
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2897
        res_nodes[node] = msg
2898
        continue
2899

    
2900
      lvs = node_res.payload
2901
      for lv_name, (_, _, lv_online) in lvs.items():
2902
        inst = nv_dict.pop((node, lv_name), None)
2903
        if (not lv_online and inst is not None
2904
            and inst.name not in res_instances):
2905
          res_instances.append(inst.name)
2906

    
2907
    # any leftover items in nv_dict are missing LVs, let's arrange the
2908
    # data better
2909
    for key, inst in nv_dict.iteritems():
2910
      if inst.name not in res_missing:
2911
        res_missing[inst.name] = []
2912
      res_missing[inst.name].append(key)
2913

    
2914
    return result
2915

    
2916

    
2917
class LUClusterRepairDiskSizes(NoHooksLU):
2918
  """Verifies the cluster disks sizes.
2919

2920
  """
2921
  REQ_BGL = False
2922

    
2923
  def ExpandNames(self):
2924
    if self.op.instances:
2925
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2926
      self.needed_locks = {
2927
        locking.LEVEL_NODE: [],
2928
        locking.LEVEL_INSTANCE: self.wanted_names,
2929
        }
2930
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2931
    else:
2932
      self.wanted_names = None
2933
      self.needed_locks = {
2934
        locking.LEVEL_NODE: locking.ALL_SET,
2935
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2936
        }
2937
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2938

    
2939
  def DeclareLocks(self, level):
2940
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2941
      self._LockInstancesNodes(primary_only=True)
2942

    
2943
  def CheckPrereq(self):
2944
    """Check prerequisites.
2945

2946
    This only checks the optional instance list against the existing names.
2947

2948
    """
2949
    if self.wanted_names is None:
2950
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2951

    
2952
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2953
                             in self.wanted_names]
2954

    
2955
  def _EnsureChildSizes(self, disk):
2956
    """Ensure children of the disk have the needed disk size.
2957

2958
    This is valid mainly for DRBD8 and fixes an issue where the
2959
    children have smaller disk size.
2960

2961
    @param disk: an L{ganeti.objects.Disk} object
2962

2963
    """
2964
    if disk.dev_type == constants.LD_DRBD8:
2965
      assert disk.children, "Empty children for DRBD8?"
2966
      fchild = disk.children[0]
2967
      mismatch = fchild.size < disk.size
2968
      if mismatch:
2969
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2970
                     fchild.size, disk.size)
2971
        fchild.size = disk.size
2972

    
2973
      # and we recurse on this child only, not on the metadev
2974
      return self._EnsureChildSizes(fchild) or mismatch
2975
    else:
2976
      return False
2977

    
2978
  def Exec(self, feedback_fn):
2979
    """Verify the size of cluster disks.
2980

2981
    """
2982
    # TODO: check child disks too
2983
    # TODO: check differences in size between primary/secondary nodes
2984
    per_node_disks = {}
2985
    for instance in self.wanted_instances:
2986
      pnode = instance.primary_node
2987
      if pnode not in per_node_disks:
2988
        per_node_disks[pnode] = []
2989
      for idx, disk in enumerate(instance.disks):
2990
        per_node_disks[pnode].append((instance, idx, disk))
2991

    
2992
    changed = []
2993
    for node, dskl in per_node_disks.items():
2994
      newl = [v[2].Copy() for v in dskl]
2995
      for dsk in newl:
2996
        self.cfg.SetDiskID(dsk, node)
2997
      result = self.rpc.call_blockdev_getsize(node, newl)
2998
      if result.fail_msg:
2999
        self.LogWarning("Failure in blockdev_getsize call to node"
3000
                        " %s, ignoring", node)
3001
        continue
3002
      if len(result.payload) != len(dskl):
3003
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
3004
                        " result.payload=%s", node, len(dskl), result.payload)
3005
        self.LogWarning("Invalid result from node %s, ignoring node results",
3006
                        node)
3007
        continue
3008
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
3009
        if size is None:
3010
          self.LogWarning("Disk %d of instance %s did not return size"
3011
                          " information, ignoring", idx, instance.name)
3012
          continue
3013
        if not isinstance(size, (int, long)):
3014
          self.LogWarning("Disk %d of instance %s did not return valid"
3015
                          " size information, ignoring", idx, instance.name)
3016
          continue
3017
        size = size >> 20
3018
        if size != disk.size:
3019
          self.LogInfo("Disk %d of instance %s has mismatched size,"
3020
                       " correcting: recorded %d, actual %d", idx,
3021
                       instance.name, disk.size, size)
3022
          disk.size = size
3023
          self.cfg.Update(instance, feedback_fn)
3024
          changed.append((instance.name, idx, size))
3025
        if self._EnsureChildSizes(disk):
3026
          self.cfg.Update(instance, feedback_fn)
3027
          changed.append((instance.name, idx, disk.size))
3028
    return changed
3029

    
3030

    
3031
class LUClusterRename(LogicalUnit):
3032
  """Rename the cluster.
3033

3034
  """
3035
  HPATH = "cluster-rename"
3036
  HTYPE = constants.HTYPE_CLUSTER
3037

    
3038
  def BuildHooksEnv(self):
3039
    """Build hooks env.
3040

3041
    """
3042
    return {
3043
      "OP_TARGET": self.cfg.GetClusterName(),
3044
      "NEW_NAME": self.op.name,
3045
      }
3046

    
3047
  def BuildHooksNodes(self):
3048
    """Build hooks nodes.
3049

3050
    """
3051
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
3052

    
3053
  def CheckPrereq(self):
3054
    """Verify that the passed name is a valid one.
3055

3056
    """
3057
    hostname = netutils.GetHostname(name=self.op.name,
3058
                                    family=self.cfg.GetPrimaryIPFamily())
3059

    
3060
    new_name = hostname.name
3061
    self.ip = new_ip = hostname.ip
3062
    old_name = self.cfg.GetClusterName()
3063
    old_ip = self.cfg.GetMasterIP()
3064
    if new_name == old_name and new_ip == old_ip:
3065
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
3066
                                 " cluster has changed",
3067
                                 errors.ECODE_INVAL)
3068
    if new_ip != old_ip:
3069
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
3070
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
3071
                                   " reachable on the network" %
3072
                                   new_ip, errors.ECODE_NOTUNIQUE)
3073

    
3074
    self.op.name = new_name
3075

    
3076
  def Exec(self, feedback_fn):
3077
    """Rename the cluster.
3078

3079
    """
3080
    clustername = self.op.name
3081
    ip = self.ip
3082

    
3083
    # shutdown the master IP
3084
    master = self.cfg.GetMasterNode()
3085
    result = self.rpc.call_node_stop_master(master, False)
3086
    result.Raise("Could not disable the master role")
3087

    
3088
    try:
3089
      cluster = self.cfg.GetClusterInfo()
3090
      cluster.cluster_name = clustername
3091
      cluster.master_ip = ip
3092
      self.cfg.Update(cluster, feedback_fn)
3093

    
3094
      # update the known hosts file
3095
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
3096
      node_list = self.cfg.GetOnlineNodeList()
3097
      try:
3098
        node_list.remove(master)
3099
      except ValueError:
3100
        pass
3101
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
3102
    finally:
3103
      result = self.rpc.call_node_start_master(master, False, False)
3104
      msg = result.fail_msg
3105
      if msg:
3106
        self.LogWarning("Could not re-enable the master role on"
3107
                        " the master, please restart manually: %s", msg)
3108

    
3109
    return clustername
3110

    
3111

    
3112
class LUClusterSetParams(LogicalUnit):
3113
  """Change the parameters of the cluster.
3114

3115
  """
3116
  HPATH = "cluster-modify"
3117
  HTYPE = constants.HTYPE_CLUSTER
3118
  REQ_BGL = False
3119

    
3120
  def CheckArguments(self):
3121
    """Check parameters
3122

3123
    """
3124
    if self.op.uid_pool:
3125
      uidpool.CheckUidPool(self.op.uid_pool)
3126

    
3127
    if self.op.add_uids:
3128
      uidpool.CheckUidPool(self.op.add_uids)
3129

    
3130
    if self.op.remove_uids:
3131
      uidpool.CheckUidPool(self.op.remove_uids)
3132

    
3133
  def ExpandNames(self):
3134
    # FIXME: in the future maybe other cluster params won't require checking on
3135
    # all nodes to be modified.
3136
    self.needed_locks = {
3137
      locking.LEVEL_NODE: locking.ALL_SET,
3138
    }
3139
    self.share_locks[locking.LEVEL_NODE] = 1
3140

    
3141
  def BuildHooksEnv(self):
3142
    """Build hooks env.
3143

3144
    """
3145
    return {
3146
      "OP_TARGET": self.cfg.GetClusterName(),
3147
      "NEW_VG_NAME": self.op.vg_name,
3148
      }
3149

    
3150
  def BuildHooksNodes(self):
3151
    """Build hooks nodes.
3152

3153
    """
3154
    mn = self.cfg.GetMasterNode()
3155
    return ([mn], [mn])
3156

    
3157
  def CheckPrereq(self):
3158
    """Check prerequisites.
3159

3160
    This checks whether the given params don't conflict and
3161
    if the given volume group is valid.
3162

3163
    """
3164
    if self.op.vg_name is not None and not self.op.vg_name:
3165
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
3166
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
3167
                                   " instances exist", errors.ECODE_INVAL)
3168

    
3169
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
3170
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
3171
        raise errors.OpPrereqError("Cannot disable drbd helper while"
3172
                                   " drbd-based instances exist",
3173
                                   errors.ECODE_INVAL)
3174

    
3175
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
3176

    
3177
    # if vg_name not None, checks given volume group on all nodes
3178
    if self.op.vg_name:
3179
      vglist = self.rpc.call_vg_list(node_list)
3180
      for node in node_list:
3181
        msg = vglist[node].fail_msg
3182
        if msg:
3183
          # ignoring down node
3184
          self.LogWarning("Error while gathering data on node %s"
3185
                          " (ignoring node): %s", node, msg)
3186
          continue
3187
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
3188
                                              self.op.vg_name,
3189
                                              constants.MIN_VG_SIZE)
3190
        if vgstatus:
3191
          raise errors.OpPrereqError("Error on node '%s': %s" %
3192
                                     (node, vgstatus), errors.ECODE_ENVIRON)
3193

    
3194
    if self.op.drbd_helper:
3195
      # checks given drbd helper on all nodes
3196
      helpers = self.rpc.call_drbd_helper(node_list)
3197
      for node in node_list:
3198
        ninfo = self.cfg.GetNodeInfo(node)
3199
        if ninfo.offline:
3200
          self.LogInfo("Not checking drbd helper on offline node %s", node)
3201
          continue
3202
        msg = helpers[node].fail_msg
3203
        if msg:
3204
          raise errors.OpPrereqError("Error checking drbd helper on node"
3205
                                     " '%s': %s" % (node, msg),
3206
                                     errors.ECODE_ENVIRON)
3207
        node_helper = helpers[node].payload
3208
        if node_helper != self.op.drbd_helper:
3209
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3210
                                     (node, node_helper), errors.ECODE_ENVIRON)
3211

    
3212
    self.cluster = cluster = self.cfg.GetClusterInfo()
3213
    # validate params changes
3214
    if self.op.beparams:
3215
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3216
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3217

    
3218
    if self.op.ndparams:
3219
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3220
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3221

    
3222
      # TODO: we need a more general way to handle resetting
3223
      # cluster-level parameters to default values
3224
      if self.new_ndparams["oob_program"] == "":
3225
        self.new_ndparams["oob_program"] = \
3226
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3227

    
3228
    if self.op.nicparams:
3229
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3230
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3231
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3232
      nic_errors = []
3233

    
3234
      # check all instances for consistency
3235
      for instance in self.cfg.GetAllInstancesInfo().values():
3236
        for nic_idx, nic in enumerate(instance.nics):
3237
          params_copy = copy.deepcopy(nic.nicparams)
3238
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3239

    
3240
          # check parameter syntax
3241
          try:
3242
            objects.NIC.CheckParameterSyntax(params_filled)
3243
          except errors.ConfigurationError, err:
3244
            nic_errors.append("Instance %s, nic/%d: %s" %
3245
                              (instance.name, nic_idx, err))
3246

    
3247
          # if we're moving instances to routed, check that they have an ip
3248
          target_mode = params_filled[constants.NIC_MODE]
3249
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3250
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3251
                              " address" % (instance.name, nic_idx))
3252
      if nic_errors:
3253
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3254
                                   "\n".join(nic_errors))
3255

    
3256
    # hypervisor list/parameters
3257
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3258
    if self.op.hvparams:
3259
      for hv_name, hv_dict in self.op.hvparams.items():
3260
        if hv_name not in self.new_hvparams:
3261
          self.new_hvparams[hv_name] = hv_dict
3262
        else:
3263
          self.new_hvparams[hv_name].update(hv_dict)
3264

    
3265
    # os hypervisor parameters
3266
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3267
    if self.op.os_hvp:
3268
      for os_name, hvs in self.op.os_hvp.items():
3269
        if os_name not in self.new_os_hvp:
3270
          self.new_os_hvp[os_name] = hvs
3271
        else:
3272
          for hv_name, hv_dict in hvs.items():
3273
            if hv_name not in self.new_os_hvp[os_name]:
3274
              self.new_os_hvp[os_name][hv_name] = hv_dict
3275
            else:
3276
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3277

    
3278
    # os parameters
3279
    self.new_osp = objects.FillDict(cluster.osparams, {})
3280
    if self.op.osparams:
3281
      for os_name, osp in self.op.osparams.items():
3282
        if os_name not in self.new_osp:
3283
          self.new_osp[os_name] = {}
3284

    
3285
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3286
                                                  use_none=True)
3287

    
3288
        if not self.new_osp[os_name]:
3289
          # we removed all parameters
3290
          del self.new_osp[os_name]
3291
        else:
3292
          # check the parameter validity (remote check)
3293
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3294
                         os_name, self.new_osp[os_name])
3295

    
3296
    # changes to the hypervisor list
3297
    if self.op.enabled_hypervisors is not None:
3298
      self.hv_list = self.op.enabled_hypervisors
3299
      for hv in self.hv_list:
3300
        # if the hypervisor doesn't already exist in the cluster
3301
        # hvparams, we initialize it to empty, and then (in both
3302
        # cases) we make sure to fill the defaults, as we might not
3303
        # have a complete defaults list if the hypervisor wasn't
3304
        # enabled before
3305
        if hv not in new_hvp:
3306
          new_hvp[hv] = {}
3307
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3308
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3309
    else:
3310
      self.hv_list = cluster.enabled_hypervisors
3311

    
3312
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3313
      # either the enabled list has changed, or the parameters have, validate
3314
      for hv_name, hv_params in self.new_hvparams.items():
3315
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3316
            (self.op.enabled_hypervisors and
3317
             hv_name in self.op.enabled_hypervisors)):
3318
          # either this is a new hypervisor, or its parameters have changed
3319
          hv_class = hypervisor.GetHypervisor(hv_name)
3320
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3321
          hv_class.CheckParameterSyntax(hv_params)
3322
          _CheckHVParams(self, node_list, hv_name, hv_params)
3323

    
3324
    if self.op.os_hvp:
3325
      # no need to check any newly-enabled hypervisors, since the
3326
      # defaults have already been checked in the above code-block
3327
      for os_name, os_hvp in self.new_os_hvp.items():
3328
        for hv_name, hv_params in os_hvp.items():
3329
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3330
          # we need to fill in the new os_hvp on top of the actual hv_p
3331
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3332
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3333
          hv_class = hypervisor.GetHypervisor(hv_name)
3334
          hv_class.CheckParameterSyntax(new_osp)
3335
          _CheckHVParams(self, node_list, hv_name, new_osp)
3336

    
3337
    if self.op.default_iallocator:
3338
      alloc_script = utils.FindFile(self.op.default_iallocator,
3339
                                    constants.IALLOCATOR_SEARCH_PATH,
3340
                                    os.path.isfile)
3341
      if alloc_script is None:
3342
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3343
                                   " specified" % self.op.default_iallocator,
3344
                                   errors.ECODE_INVAL)
3345

    
3346
  def Exec(self, feedback_fn):
3347
    """Change the parameters of the cluster.
3348

3349
    """
3350
    if self.op.vg_name is not None:
3351
      new_volume = self.op.vg_name
3352
      if not new_volume:
3353
        new_volume = None
3354
      if new_volume != self.cfg.GetVGName():
3355
        self.cfg.SetVGName(new_volume)
3356
      else:
3357
        feedback_fn("Cluster LVM configuration already in desired"
3358
                    " state, not changing")
3359
    if self.op.drbd_helper is not None:
3360
      new_helper = self.op.drbd_helper
3361
      if not new_helper:
3362
        new_helper = None
3363
      if new_helper != self.cfg.GetDRBDHelper():
3364
        self.cfg.SetDRBDHelper(new_helper)
3365
      else:
3366
        feedback_fn("Cluster DRBD helper already in desired state,"
3367
                    " not changing")
3368
    if self.op.hvparams:
3369
      self.cluster.hvparams = self.new_hvparams
3370
    if self.op.os_hvp:
3371
      self.cluster.os_hvp = self.new_os_hvp
3372
    if self.op.enabled_hypervisors is not None:
3373
      self.cluster.hvparams = self.new_hvparams
3374
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3375
    if self.op.beparams:
3376
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3377
    if self.op.nicparams:
3378
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3379
    if self.op.osparams:
3380
      self.cluster.osparams = self.new_osp
3381
    if self.op.ndparams:
3382
      self.cluster.ndparams = self.new_ndparams
3383

    
3384
    if self.op.candidate_pool_size is not None:
3385
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3386
      # we need to update the pool size here, otherwise the save will fail
3387
      _AdjustCandidatePool(self, [])
3388

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

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

    
3395
    if self.op.add_uids is not None:
3396
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3397

    
3398
    if self.op.remove_uids is not None:
3399
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3400

    
3401
    if self.op.uid_pool is not None:
3402
      self.cluster.uid_pool = self.op.uid_pool
3403

    
3404
    if self.op.default_iallocator is not None:
3405
      self.cluster.default_iallocator = self.op.default_iallocator
3406

    
3407
    if self.op.reserved_lvs is not None:
3408
      self.cluster.reserved_lvs = self.op.reserved_lvs
3409

    
3410
    def helper_os(aname, mods, desc):
3411
      desc += " OS list"
3412
      lst = getattr(self.cluster, aname)
3413
      for key, val in mods:
3414
        if key == constants.DDM_ADD:
3415
          if val in lst:
3416
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3417
          else:
3418
            lst.append(val)
3419
        elif key == constants.DDM_REMOVE:
3420
          if val in lst:
3421
            lst.remove(val)
3422
          else:
3423
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3424
        else:
3425
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3426

    
3427
    if self.op.hidden_os:
3428
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3429

    
3430
    if self.op.blacklisted_os:
3431
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3432

    
3433
    if self.op.master_netdev:
3434
      master = self.cfg.GetMasterNode()
3435
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3436
                  self.cluster.master_netdev)
3437
      result = self.rpc.call_node_stop_master(master, False)
3438
      result.Raise("Could not disable the master ip")
3439
      feedback_fn("Changing master_netdev from %s to %s" %
3440
                  (self.cluster.master_netdev, self.op.master_netdev))
3441
      self.cluster.master_netdev = self.op.master_netdev
3442

    
3443
    self.cfg.Update(self.cluster, feedback_fn)
3444

    
3445
    if self.op.master_netdev:
3446
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3447
                  self.op.master_netdev)
3448
      result = self.rpc.call_node_start_master(master, False, False)
3449
      if result.fail_msg:
3450
        self.LogWarning("Could not re-enable the master ip on"
3451
                        " the master, please restart manually: %s",
3452
                        result.fail_msg)
3453

    
3454

    
3455
def _UploadHelper(lu, nodes, fname):
3456
  """Helper for uploading a file and showing warnings.
3457

3458
  """
3459
  if os.path.exists(fname):
3460
    result = lu.rpc.call_upload_file(nodes, fname)
3461
    for to_node, to_result in result.items():
3462
      msg = to_result.fail_msg
3463
      if msg:
3464
        msg = ("Copy of file %s to node %s failed: %s" %
3465
               (fname, to_node, msg))
3466
        lu.proc.LogWarning(msg)
3467

    
3468

    
3469
def _ComputeAncillaryFiles(cluster, redist):
3470
  """Compute files external to Ganeti which need to be consistent.
3471

3472
  @type redist: boolean
3473
  @param redist: Whether to include files which need to be redistributed
3474

3475
  """
3476
  # Compute files for all nodes
3477
  files_all = set([
3478
    constants.SSH_KNOWN_HOSTS_FILE,
3479
    constants.CONFD_HMAC_KEY,
3480
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3481
    ])
3482

    
3483
  if not redist:
3484
    files_all.update(constants.ALL_CERT_FILES)
3485
    files_all.update(ssconf.SimpleStore().GetFileList())
3486

    
3487
  if cluster.modify_etc_hosts:
3488
    files_all.add(constants.ETC_HOSTS)
3489

    
3490
  # Files which must either exist on all nodes or on none
3491
  files_all_opt = set([
3492
    constants.RAPI_USERS_FILE,
3493
    ])
3494

    
3495
  # Files which should only be on master candidates
3496
  files_mc = set()
3497
  if not redist:
3498
    files_mc.add(constants.CLUSTER_CONF_FILE)
3499

    
3500
  # Files which should only be on VM-capable nodes
3501
  files_vm = set(filename
3502
    for hv_name in cluster.enabled_hypervisors
3503
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3504

    
3505
  # Filenames must be unique
3506
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3507
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3508
         "Found file listed in more than one file list"
3509

    
3510
  return (files_all, files_all_opt, files_mc, files_vm)
3511

    
3512

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

3516
  ConfigWriter takes care of distributing the config and ssconf files, but
3517
  there are more files which should be distributed to all nodes. This function
3518
  makes sure those are copied.
3519

3520
  @param lu: calling logical unit
3521
  @param additional_nodes: list of nodes not in the config to distribute to
3522
  @type additional_vm: boolean
3523
  @param additional_vm: whether the additional nodes are vm-capable or not
3524

3525
  """
3526
  # Gather target nodes
3527
  cluster = lu.cfg.GetClusterInfo()
3528
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3529

    
3530
  online_nodes = lu.cfg.GetOnlineNodeList()
3531
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3532

    
3533
  if additional_nodes is not None:
3534
    online_nodes.extend(additional_nodes)
3535
    if additional_vm:
3536
      vm_nodes.extend(additional_nodes)
3537

    
3538
  # Never distribute to master node
3539
  for nodelist in [online_nodes, vm_nodes]:
3540
    if master_info.name in nodelist:
3541
      nodelist.remove(master_info.name)
3542

    
3543
  # Gather file lists
3544
  (files_all, files_all_opt, files_mc, files_vm) = \
3545
    _ComputeAncillaryFiles(cluster, True)
3546

    
3547
  # Never re-distribute configuration file from here
3548
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3549
              constants.CLUSTER_CONF_FILE in files_vm)
3550
  assert not files_mc, "Master candidates not handled in this function"
3551

    
3552
  filemap = [
3553
    (online_nodes, files_all),
3554
    (online_nodes, files_all_opt),
3555
    (vm_nodes, files_vm),
3556
    ]
3557

    
3558
  # Upload the files
3559
  for (node_list, files) in filemap:
3560
    for fname in files:
3561
      _UploadHelper(lu, node_list, fname)
3562

    
3563

    
3564
class LUClusterRedistConf(NoHooksLU):
3565
  """Force the redistribution of cluster configuration.
3566

3567
  This is a very simple LU.
3568

3569
  """
3570
  REQ_BGL = False
3571

    
3572
  def ExpandNames(self):
3573
    self.needed_locks = {
3574
      locking.LEVEL_NODE: locking.ALL_SET,
3575
    }
3576
    self.share_locks[locking.LEVEL_NODE] = 1
3577

    
3578
  def Exec(self, feedback_fn):
3579
    """Redistribute the configuration.
3580

3581
    """
3582
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3583
    _RedistributeAncillaryFiles(self)
3584

    
3585

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

3589
  """
3590
  if not instance.disks or disks is not None and not disks:
3591
    return True
3592

    
3593
  disks = _ExpandCheckDisks(instance, disks)
3594

    
3595
  if not oneshot:
3596
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3597

    
3598
  node = instance.primary_node
3599

    
3600
  for dev in disks:
3601
    lu.cfg.SetDiskID(dev, node)
3602

    
3603
  # TODO: Convert to utils.Retry
3604

    
3605
  retries = 0
3606
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3607
  while True:
3608
    max_time = 0
3609
    done = True
3610
    cumul_degraded = False
3611
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3612
    msg = rstats.fail_msg
3613
    if msg:
3614
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3615
      retries += 1
3616
      if retries >= 10:
3617
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3618
                                 " aborting." % node)
3619
      time.sleep(6)
3620
      continue
3621
    rstats = rstats.payload
3622
    retries = 0
3623
    for i, mstat in enumerate(rstats):
3624
      if mstat is None:
3625
        lu.LogWarning("Can't compute data for node %s/%s",
3626
                           node, disks[i].iv_name)
3627
        continue
3628

    
3629
      cumul_degraded = (cumul_degraded or
3630
                        (mstat.is_degraded and mstat.sync_percent is None))
3631
      if mstat.sync_percent is not None:
3632
        done = False
3633
        if mstat.estimated_time is not None:
3634
          rem_time = ("%s remaining (estimated)" %
3635
                      utils.FormatSeconds(mstat.estimated_time))
3636
          max_time = mstat.estimated_time
3637
        else:
3638
          rem_time = "no time estimate"
3639
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3640
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3641

    
3642
    # if we're done but degraded, let's do a few small retries, to
3643
    # make sure we see a stable and not transient situation; therefore
3644
    # we force restart of the loop
3645
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3646
      logging.info("Degraded disks found, %d retries left", degr_retries)
3647
      degr_retries -= 1
3648
      time.sleep(1)
3649
      continue
3650

    
3651
    if done or oneshot:
3652
      break
3653

    
3654
    time.sleep(min(60, max_time))
3655

    
3656
  if done:
3657
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3658
  return not cumul_degraded
3659

    
3660

    
3661
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3662
  """Check that mirrors are not degraded.
3663

3664
  The ldisk parameter, if True, will change the test from the
3665
  is_degraded attribute (which represents overall non-ok status for
3666
  the device(s)) to the ldisk (representing the local storage status).
3667

3668
  """
3669
  lu.cfg.SetDiskID(dev, node)
3670

    
3671
  result = True
3672

    
3673
  if on_primary or dev.AssembleOnSecondary():
3674
    rstats = lu.rpc.call_blockdev_find(node, dev)
3675
    msg = rstats.fail_msg
3676
    if msg:
3677
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3678
      result = False
3679
    elif not rstats.payload:
3680
      lu.LogWarning("Can't find disk on node %s", node)
3681
      result = False
3682
    else:
3683
      if ldisk:
3684
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3685
      else:
3686
        result = result and not rstats.payload.is_degraded
3687

    
3688
  if dev.children:
3689
    for child in dev.children:
3690
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3691

    
3692
  return result
3693

    
3694

    
3695
class LUOobCommand(NoHooksLU):
3696
  """Logical unit for OOB handling.
3697

3698
  """
3699
  REG_BGL = False
3700
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3701

    
3702
  def ExpandNames(self):
3703
    """Gather locks we need.
3704

3705
    """
3706
    if self.op.node_names:
3707
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3708
      lock_names = self.op.node_names
3709
    else:
3710
      lock_names = locking.ALL_SET
3711

    
3712
    self.needed_locks = {
3713
      locking.LEVEL_NODE: lock_names,
3714
      }
3715

    
3716
  def CheckPrereq(self):
3717
    """Check prerequisites.
3718

3719
    This checks:
3720
     - the node exists in the configuration
3721
     - OOB is supported
3722

3723
    Any errors are signaled by raising errors.OpPrereqError.
3724

3725
    """
3726
    self.nodes = []
3727
    self.master_node = self.cfg.GetMasterNode()
3728

    
3729
    assert self.op.power_delay >= 0.0
3730

    
3731
    if self.op.node_names:
3732
      if (self.op.command in self._SKIP_MASTER and
3733
          self.master_node in self.op.node_names):
3734
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3735
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3736

    
3737
        if master_oob_handler:
3738
          additional_text = ("run '%s %s %s' if you want to operate on the"
3739
                             " master regardless") % (master_oob_handler,
3740
                                                      self.op.command,
3741
                                                      self.master_node)
3742
        else:
3743
          additional_text = "it does not support out-of-band operations"
3744

    
3745
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3746
                                    " allowed for %s; %s") %
3747
                                   (self.master_node, self.op.command,
3748
                                    additional_text), errors.ECODE_INVAL)
3749
    else:
3750
      self.op.node_names = self.cfg.GetNodeList()
3751
      if self.op.command in self._SKIP_MASTER:
3752
        self.op.node_names.remove(self.master_node)
3753

    
3754
    if self.op.command in self._SKIP_MASTER:
3755
      assert self.master_node not in self.op.node_names
3756

    
3757
    for node_name in self.op.node_names:
3758
      node = self.cfg.GetNodeInfo(node_name)
3759

    
3760
      if node is None:
3761
        raise errors.OpPrereqError("Node %s not found" % node_name,
3762
                                   errors.ECODE_NOENT)
3763
      else:
3764
        self.nodes.append(node)
3765

    
3766
      if (not self.op.ignore_status and
3767
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3768
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3769
                                    " not marked offline") % node_name,
3770
                                   errors.ECODE_STATE)
3771

    
3772
  def Exec(self, feedback_fn):
3773
    """Execute OOB and return result if we expect any.
3774

3775
    """
3776
    master_node = self.master_node
3777
    ret = []
3778

    
3779
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3780
                                              key=lambda node: node.name)):
3781
      node_entry = [(constants.RS_NORMAL, node.name)]
3782
      ret.append(node_entry)
3783

    
3784
      oob_program = _SupportsOob(self.cfg, node)
3785

    
3786
      if not oob_program:
3787
        node_entry.append((constants.RS_UNAVAIL, None))
3788
        continue
3789

    
3790
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3791
                   self.op.command, oob_program, node.name)
3792
      result = self.rpc.call_run_oob(master_node, oob_program,
3793
                                     self.op.command, node.name,
3794
                                     self.op.timeout)
3795

    
3796
      if result.fail_msg:
3797
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3798
                        node.name, result.fail_msg)
3799
        node_entry.append((constants.RS_NODATA, None))
3800
      else:
3801
        try:
3802
          self._CheckPayload(result)
3803
        except errors.OpExecError, err:
3804
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3805
                          node.name, err)
3806
          node_entry.append((constants.RS_NODATA, None))
3807
        else:
3808
          if self.op.command == constants.OOB_HEALTH:
3809
            # For health we should log important events
3810
            for item, status in result.payload:
3811
              if status in [constants.OOB_STATUS_WARNING,
3812
                            constants.OOB_STATUS_CRITICAL]:
3813
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3814
                                item, node.name, status)
3815

    
3816
          if self.op.command == constants.OOB_POWER_ON:
3817
            node.powered = True
3818
          elif self.op.command == constants.OOB_POWER_OFF:
3819
            node.powered = False
3820
          elif self.op.command == constants.OOB_POWER_STATUS:
3821
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3822
            if powered != node.powered:
3823
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3824
                               " match actual power state (%s)"), node.powered,
3825
                              node.name, powered)
3826

    
3827
          # For configuration changing commands we should update the node
3828
          if self.op.command in (constants.OOB_POWER_ON,
3829
                                 constants.OOB_POWER_OFF):
3830
            self.cfg.Update(node, feedback_fn)
3831

    
3832
          node_entry.append((constants.RS_NORMAL, result.payload))
3833

    
3834
          if (self.op.command == constants.OOB_POWER_ON and
3835
              idx < len(self.nodes) - 1):
3836
            time.sleep(self.op.power_delay)
3837

    
3838
    return ret
3839

    
3840
  def _CheckPayload(self, result):
3841
    """Checks if the payload is valid.
3842

3843
    @param result: RPC result
3844
    @raises errors.OpExecError: If payload is not valid
3845

3846
    """
3847
    errs = []
3848
    if self.op.command == constants.OOB_HEALTH:
3849
      if not isinstance(result.payload, list):
3850
        errs.append("command 'health' is expected to return a list but got %s" %
3851
                    type(result.payload))
3852
      else:
3853
        for item, status in result.payload:
3854
          if status not in constants.OOB_STATUSES:
3855
            errs.append("health item '%s' has invalid status '%s'" %
3856
                        (item, status))
3857

    
3858
    if self.op.command == constants.OOB_POWER_STATUS:
3859
      if not isinstance(result.payload, dict):
3860
        errs.append("power-status is expected to return a dict but got %s" %
3861
                    type(result.payload))
3862

    
3863
    if self.op.command in [
3864
        constants.OOB_POWER_ON,
3865
        constants.OOB_POWER_OFF,
3866
        constants.OOB_POWER_CYCLE,
3867
        ]:
3868
      if result.payload is not None:
3869
        errs.append("%s is expected to not return payload but got '%s'" %
3870
                    (self.op.command, result.payload))
3871

    
3872
    if errs:
3873
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3874
                               utils.CommaJoin(errs))
3875

    
3876
class _OsQuery(_QueryBase):
3877
  FIELDS = query.OS_FIELDS
3878

    
3879
  def ExpandNames(self, lu):
3880
    # Lock all nodes in shared mode
3881
    # Temporary removal of locks, should be reverted later
3882
    # TODO: reintroduce locks when they are lighter-weight
3883
    lu.needed_locks = {}
3884
    #self.share_locks[locking.LEVEL_NODE] = 1
3885
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3886

    
3887
    # The following variables interact with _QueryBase._GetNames
3888
    if self.names:
3889
      self.wanted = self.names
3890
    else:
3891
      self.wanted = locking.ALL_SET
3892

    
3893
    self.do_locking = self.use_locking
3894

    
3895
  def DeclareLocks(self, lu, level):
3896
    pass
3897

    
3898
  @staticmethod
3899
  def _DiagnoseByOS(rlist):
3900
    """Remaps a per-node return list into an a per-os per-node dictionary
3901

3902
    @param rlist: a map with node names as keys and OS objects as values
3903

3904
    @rtype: dict
3905
    @return: a dictionary with osnames as keys and as value another
3906
        map, with nodes as keys and tuples of (path, status, diagnose,
3907
        variants, parameters, api_versions) as values, eg::
3908

3909
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3910
                                     (/srv/..., False, "invalid api")],
3911
                           "node2": [(/srv/..., True, "", [], [])]}
3912
          }
3913

3914
    """
3915
    all_os = {}
3916
    # we build here the list of nodes that didn't fail the RPC (at RPC
3917
    # level), so that nodes with a non-responding node daemon don't
3918
    # make all OSes invalid
3919
    good_nodes = [node_name for node_name in rlist
3920
                  if not rlist[node_name].fail_msg]
3921
    for node_name, nr in rlist.items():
3922
      if nr.fail_msg or not nr.payload:
3923
        continue
3924
      for (name, path, status, diagnose, variants,
3925
           params, api_versions) in nr.payload:
3926
        if name not in all_os:
3927
          # build a list of nodes for this os containing empty lists
3928
          # for each node in node_list
3929
          all_os[name] = {}
3930
          for nname in good_nodes:
3931
            all_os[name][nname] = []
3932
        # convert params from [name, help] to (name, help)
3933
        params = [tuple(v) for v in params]
3934
        all_os[name][node_name].append((path, status, diagnose,
3935
                                        variants, params, api_versions))
3936
    return all_os
3937

    
3938
  def _GetQueryData(self, lu):
3939
    """Computes the list of nodes and their attributes.
3940

3941
    """
3942
    # Locking is not used
3943
    assert not (compat.any(lu.glm.is_owned(level)
3944
                           for level in locking.LEVELS
3945
                           if level != locking.LEVEL_CLUSTER) or
3946
                self.do_locking or self.use_locking)
3947

    
3948
    valid_nodes = [node.name
3949
                   for node in lu.cfg.GetAllNodesInfo().values()
3950
                   if not node.offline and node.vm_capable]
3951
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3952
    cluster = lu.cfg.GetClusterInfo()
3953

    
3954
    data = {}
3955

    
3956
    for (os_name, os_data) in pol.items():
3957
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3958
                          hidden=(os_name in cluster.hidden_os),
3959
                          blacklisted=(os_name in cluster.blacklisted_os))
3960

    
3961
      variants = set()
3962
      parameters = set()
3963
      api_versions = set()
3964

    
3965
      for idx, osl in enumerate(os_data.values()):
3966
        info.valid = bool(info.valid and osl and osl[0][1])
3967
        if not info.valid:
3968
          break
3969

    
3970
        (node_variants, node_params, node_api) = osl[0][3:6]
3971
        if idx == 0:
3972
          # First entry
3973
          variants.update(node_variants)
3974
          parameters.update(node_params)
3975
          api_versions.update(node_api)
3976
        else:
3977
          # Filter out inconsistent values
3978
          variants.intersection_update(node_variants)
3979
          parameters.intersection_update(node_params)
3980
          api_versions.intersection_update(node_api)
3981

    
3982
      info.variants = list(variants)
3983
      info.parameters = list(parameters)
3984
      info.api_versions = list(api_versions)
3985

    
3986
      data[os_name] = info
3987

    
3988
    # Prepare data in requested order
3989
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3990
            if name in data]
3991

    
3992

    
3993
class LUOsDiagnose(NoHooksLU):
3994
  """Logical unit for OS diagnose/query.
3995

3996
  """
3997
  REQ_BGL = False
3998

    
3999
  @staticmethod
4000
  def _BuildFilter(fields, names):
4001
    """Builds a filter for querying OSes.
4002

4003
    """
4004
    name_filter = qlang.MakeSimpleFilter("name", names)
4005

    
4006
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
4007
    # respective field is not requested
4008
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
4009
                     for fname in ["hidden", "blacklisted"]
4010
                     if fname not in fields]
4011
    if "valid" not in fields:
4012
      status_filter.append([qlang.OP_TRUE, "valid"])
4013

    
4014
    if status_filter:
4015
      status_filter.insert(0, qlang.OP_AND)
4016
    else:
4017
      status_filter = None
4018

    
4019
    if name_filter and status_filter:
4020
      return [qlang.OP_AND, name_filter, status_filter]
4021
    elif name_filter:
4022
      return name_filter
4023
    else:
4024
      return status_filter
4025

    
4026
  def CheckArguments(self):
4027
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
4028
                       self.op.output_fields, False)
4029

    
4030
  def ExpandNames(self):
4031
    self.oq.ExpandNames(self)
4032

    
4033
  def Exec(self, feedback_fn):
4034
    return self.oq.OldStyleQuery(self)
4035

    
4036

    
4037
class LUNodeRemove(LogicalUnit):
4038
  """Logical unit for removing a node.
4039

4040
  """
4041
  HPATH = "node-remove"
4042
  HTYPE = constants.HTYPE_NODE
4043

    
4044
  def BuildHooksEnv(self):
4045
    """Build hooks env.
4046

4047
    This doesn't run on the target node in the pre phase as a failed
4048
    node would then be impossible to remove.
4049

4050
    """
4051
    return {
4052
      "OP_TARGET": self.op.node_name,
4053
      "NODE_NAME": self.op.node_name,
4054
      }
4055

    
4056
  def BuildHooksNodes(self):
4057
    """Build hooks nodes.
4058

4059
    """
4060
    all_nodes = self.cfg.GetNodeList()
4061
    try:
4062
      all_nodes.remove(self.op.node_name)
4063
    except ValueError:
4064
      logging.warning("Node '%s', which is about to be removed, was not found"
4065
                      " in the list of all nodes", self.op.node_name)
4066
    return (all_nodes, all_nodes)
4067

    
4068
  def CheckPrereq(self):
4069
    """Check prerequisites.
4070

4071
    This checks:
4072
     - the node exists in the configuration
4073
     - it does not have primary or secondary instances
4074
     - it's not the master
4075

4076
    Any errors are signaled by raising errors.OpPrereqError.
4077

4078
    """
4079
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4080
    node = self.cfg.GetNodeInfo(self.op.node_name)
4081
    assert node is not None
4082

    
4083
    instance_list = self.cfg.GetInstanceList()
4084

    
4085
    masternode = self.cfg.GetMasterNode()
4086
    if node.name == masternode:
4087
      raise errors.OpPrereqError("Node is the master node, failover to another"
4088
                                 " node is required", errors.ECODE_INVAL)
4089

    
4090
    for instance_name in instance_list:
4091
      instance = self.cfg.GetInstanceInfo(instance_name)
4092
      if node.name in instance.all_nodes:
4093
        raise errors.OpPrereqError("Instance %s is still running on the node,"
4094
                                   " please remove first" % instance_name,
4095
                                   errors.ECODE_INVAL)
4096
    self.op.node_name = node.name
4097
    self.node = node
4098

    
4099
  def Exec(self, feedback_fn):
4100
    """Removes the node from the cluster.
4101

4102
    """
4103
    node = self.node
4104
    logging.info("Stopping the node daemon and removing configs from node %s",
4105
                 node.name)
4106

    
4107
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
4108

    
4109
    # Promote nodes to master candidate as needed
4110
    _AdjustCandidatePool(self, exceptions=[node.name])
4111
    self.context.RemoveNode(node.name)
4112

    
4113
    # Run post hooks on the node before it's removed
4114
    _RunPostHook(self, node.name)
4115

    
4116
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
4117
    msg = result.fail_msg
4118
    if msg:
4119
      self.LogWarning("Errors encountered on the remote node while leaving"
4120
                      " the cluster: %s", msg)
4121

    
4122
    # Remove node from our /etc/hosts
4123
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4124
      master_node = self.cfg.GetMasterNode()
4125
      result = self.rpc.call_etc_hosts_modify(master_node,
4126
                                              constants.ETC_HOSTS_REMOVE,
4127
                                              node.name, None)
4128
      result.Raise("Can't update hosts file with new host data")
4129
      _RedistributeAncillaryFiles(self)
4130

    
4131

    
4132
class _NodeQuery(_QueryBase):
4133
  FIELDS = query.NODE_FIELDS
4134

    
4135
  def ExpandNames(self, lu):
4136
    lu.needed_locks = {}
4137
    lu.share_locks[locking.LEVEL_NODE] = 1
4138

    
4139
    if self.names:
4140
      self.wanted = _GetWantedNodes(lu, self.names)
4141
    else:
4142
      self.wanted = locking.ALL_SET
4143

    
4144
    self.do_locking = (self.use_locking and
4145
                       query.NQ_LIVE in self.requested_data)
4146

    
4147
    if self.do_locking:
4148
      # if we don't request only static fields, we need to lock the nodes
4149
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
4150

    
4151
  def DeclareLocks(self, lu, level):
4152
    pass
4153

    
4154
  def _GetQueryData(self, lu):
4155
    """Computes the list of nodes and their attributes.
4156

4157
    """
4158
    all_info = lu.cfg.GetAllNodesInfo()
4159

    
4160
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
4161

    
4162
    # Gather data as requested
4163
    if query.NQ_LIVE in self.requested_data:
4164
      # filter out non-vm_capable nodes
4165
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
4166

    
4167
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
4168
                                        lu.cfg.GetHypervisorType())
4169
      live_data = dict((name, nresult.payload)
4170
                       for (name, nresult) in node_data.items()
4171
                       if not nresult.fail_msg and nresult.payload)
4172
    else:
4173
      live_data = None
4174

    
4175
    if query.NQ_INST in self.requested_data:
4176
      node_to_primary = dict([(name, set()) for name in nodenames])
4177
      node_to_secondary = dict([(name, set()) for name in nodenames])
4178

    
4179
      inst_data = lu.cfg.GetAllInstancesInfo()
4180

    
4181
      for inst in inst_data.values():
4182
        if inst.primary_node in node_to_primary:
4183
          node_to_primary[inst.primary_node].add(inst.name)
4184
        for secnode in inst.secondary_nodes:
4185
          if secnode in node_to_secondary:
4186
            node_to_secondary[secnode].add(inst.name)
4187
    else:
4188
      node_to_primary = None
4189
      node_to_secondary = None
4190

    
4191
    if query.NQ_OOB in self.requested_data:
4192
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
4193
                         for name, node in all_info.iteritems())
4194
    else:
4195
      oob_support = None
4196

    
4197
    if query.NQ_GROUP in self.requested_data:
4198
      groups = lu.cfg.GetAllNodeGroupsInfo()
4199
    else:
4200
      groups = {}
4201

    
4202
    return query.NodeQueryData([all_info[name] for name in nodenames],
4203
                               live_data, lu.cfg.GetMasterNode(),
4204
                               node_to_primary, node_to_secondary, groups,
4205
                               oob_support, lu.cfg.GetClusterInfo())
4206

    
4207

    
4208
class LUNodeQuery(NoHooksLU):
4209
  """Logical unit for querying nodes.
4210

4211
  """
4212
  # pylint: disable-msg=W0142
4213
  REQ_BGL = False
4214

    
4215
  def CheckArguments(self):
4216
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4217
                         self.op.output_fields, self.op.use_locking)
4218

    
4219
  def ExpandNames(self):
4220
    self.nq.ExpandNames(self)
4221

    
4222
  def Exec(self, feedback_fn):
4223
    return self.nq.OldStyleQuery(self)
4224

    
4225

    
4226
class LUNodeQueryvols(NoHooksLU):
4227
  """Logical unit for getting volumes on node(s).
4228

4229
  """
4230
  REQ_BGL = False
4231
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4232
  _FIELDS_STATIC = utils.FieldSet("node")
4233

    
4234
  def CheckArguments(self):
4235
    _CheckOutputFields(static=self._FIELDS_STATIC,
4236
                       dynamic=self._FIELDS_DYNAMIC,
4237
                       selected=self.op.output_fields)
4238

    
4239
  def ExpandNames(self):
4240
    self.needed_locks = {}
4241
    self.share_locks[locking.LEVEL_NODE] = 1
4242
    if not self.op.nodes:
4243
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4244
    else:
4245
      self.needed_locks[locking.LEVEL_NODE] = \
4246
        _GetWantedNodes(self, self.op.nodes)
4247

    
4248
  def Exec(self, feedback_fn):
4249
    """Computes the list of nodes and their attributes.
4250

4251
    """
4252
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4253
    volumes = self.rpc.call_node_volumes(nodenames)
4254

    
4255
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4256
             in self.cfg.GetInstanceList()]
4257

    
4258
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4259

    
4260
    output = []
4261
    for node in nodenames:
4262
      nresult = volumes[node]
4263
      if nresult.offline:
4264
        continue
4265
      msg = nresult.fail_msg
4266
      if msg:
4267
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4268
        continue
4269

    
4270
      node_vols = nresult.payload[:]
4271
      node_vols.sort(key=lambda vol: vol['dev'])
4272

    
4273
      for vol in node_vols:
4274
        node_output = []
4275
        for field in self.op.output_fields:
4276
          if field == "node":
4277
            val = node
4278
          elif field == "phys":
4279
            val = vol['dev']
4280
          elif field == "vg":
4281
            val = vol['vg']
4282
          elif field == "name":
4283
            val = vol['name']
4284
          elif field == "size":
4285
            val = int(float(vol['size']))
4286
          elif field == "instance":
4287
            for inst in ilist:
4288
              if node not in lv_by_node[inst]:
4289
                continue
4290
              if vol['name'] in lv_by_node[inst][node]:
4291
                val = inst.name
4292
                break
4293
            else:
4294
              val = '-'
4295
          else:
4296
            raise errors.ParameterError(field)
4297
          node_output.append(str(val))
4298

    
4299
        output.append(node_output)
4300

    
4301
    return output
4302

    
4303

    
4304
class LUNodeQueryStorage(NoHooksLU):
4305
  """Logical unit for getting information on storage units on node(s).
4306

4307
  """
4308
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4309
  REQ_BGL = False
4310

    
4311
  def CheckArguments(self):
4312
    _CheckOutputFields(static=self._FIELDS_STATIC,
4313
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4314
                       selected=self.op.output_fields)
4315

    
4316
  def ExpandNames(self):
4317
    self.needed_locks = {}
4318
    self.share_locks[locking.LEVEL_NODE] = 1
4319

    
4320
    if self.op.nodes:
4321
      self.needed_locks[locking.LEVEL_NODE] = \
4322
        _GetWantedNodes(self, self.op.nodes)
4323
    else:
4324
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4325

    
4326
  def Exec(self, feedback_fn):
4327
    """Computes the list of nodes and their attributes.
4328

4329
    """
4330
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4331

    
4332
    # Always get name to sort by
4333
    if constants.SF_NAME in self.op.output_fields:
4334
      fields = self.op.output_fields[:]
4335
    else:
4336
      fields = [constants.SF_NAME] + self.op.output_fields
4337

    
4338
    # Never ask for node or type as it's only known to the LU
4339
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4340
      while extra in fields:
4341
        fields.remove(extra)
4342

    
4343
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4344
    name_idx = field_idx[constants.SF_NAME]
4345

    
4346
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4347
    data = self.rpc.call_storage_list(self.nodes,
4348
                                      self.op.storage_type, st_args,
4349
                                      self.op.name, fields)
4350

    
4351
    result = []
4352

    
4353
    for node in utils.NiceSort(self.nodes):
4354
      nresult = data[node]
4355
      if nresult.offline:
4356
        continue
4357

    
4358
      msg = nresult.fail_msg
4359
      if msg:
4360
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4361
        continue
4362

    
4363
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4364

    
4365
      for name in utils.NiceSort(rows.keys()):
4366
        row = rows[name]
4367

    
4368
        out = []
4369

    
4370
        for field in self.op.output_fields:
4371
          if field == constants.SF_NODE:
4372
            val = node
4373
          elif field == constants.SF_TYPE:
4374
            val = self.op.storage_type
4375
          elif field in field_idx:
4376
            val = row[field_idx[field]]
4377
          else:
4378
            raise errors.ParameterError(field)
4379

    
4380
          out.append(val)
4381

    
4382
        result.append(out)
4383

    
4384
    return result
4385

    
4386

    
4387
class _InstanceQuery(_QueryBase):
4388
  FIELDS = query.INSTANCE_FIELDS
4389

    
4390
  def ExpandNames(self, lu):
4391
    lu.needed_locks = {}
4392
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4393
    lu.share_locks[locking.LEVEL_NODE] = 1
4394

    
4395
    if self.names:
4396
      self.wanted = _GetWantedInstances(lu, self.names)
4397
    else:
4398
      self.wanted = locking.ALL_SET
4399

    
4400
    self.do_locking = (self.use_locking and
4401
                       query.IQ_LIVE in self.requested_data)
4402
    if self.do_locking:
4403
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4404
      lu.needed_locks[locking.LEVEL_NODE] = []
4405
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4406

    
4407
  def DeclareLocks(self, lu, level):
4408
    if level == locking.LEVEL_NODE and self.do_locking:
4409
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4410

    
4411
  def _GetQueryData(self, lu):
4412
    """Computes the list of instances and their attributes.
4413

4414
    """
4415
    cluster = lu.cfg.GetClusterInfo()
4416
    all_info = lu.cfg.GetAllInstancesInfo()
4417

    
4418
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4419

    
4420
    instance_list = [all_info[name] for name in instance_names]
4421
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4422
                                        for inst in instance_list)))
4423
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4424
    bad_nodes = []
4425
    offline_nodes = []
4426
    wrongnode_inst = set()
4427

    
4428
    # Gather data as requested
4429
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4430
      live_data = {}
4431
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4432
      for name in nodes:
4433
        result = node_data[name]
4434
        if result.offline:
4435
          # offline nodes will be in both lists
4436
          assert result.fail_msg
4437
          offline_nodes.append(name)
4438
        if result.fail_msg:
4439
          bad_nodes.append(name)
4440
        elif result.payload:
4441
          for inst in result.payload:
4442
            if inst in all_info:
4443
              if all_info[inst].primary_node == name:
4444
                live_data.update(result.payload)
4445
              else:
4446
                wrongnode_inst.add(inst)
4447
            else:
4448
              # orphan instance; we don't list it here as we don't
4449
              # handle this case yet in the output of instance listing
4450
              logging.warning("Orphan instance '%s' found on node %s",
4451
                              inst, name)
4452
        # else no instance is alive
4453
    else:
4454
      live_data = {}
4455

    
4456
    if query.IQ_DISKUSAGE in self.requested_data:
4457
      disk_usage = dict((inst.name,
4458
                         _ComputeDiskSize(inst.disk_template,
4459
                                          [{constants.IDISK_SIZE: disk.size}
4460
                                           for disk in inst.disks]))
4461
                        for inst in instance_list)
4462
    else:
4463
      disk_usage = None
4464

    
4465
    if query.IQ_CONSOLE in self.requested_data:
4466
      consinfo = {}
4467
      for inst in instance_list:
4468
        if inst.name in live_data:
4469
          # Instance is running
4470
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4471
        else:
4472
          consinfo[inst.name] = None
4473
      assert set(consinfo.keys()) == set(instance_names)
4474
    else:
4475
      consinfo = None
4476

    
4477
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4478
                                   disk_usage, offline_nodes, bad_nodes,
4479
                                   live_data, wrongnode_inst, consinfo)
4480

    
4481

    
4482
class LUQuery(NoHooksLU):
4483
  """Query for resources/items of a certain kind.
4484

4485
  """
4486
  # pylint: disable-msg=W0142
4487
  REQ_BGL = False
4488

    
4489
  def CheckArguments(self):
4490
    qcls = _GetQueryImplementation(self.op.what)
4491

    
4492
    self.impl = qcls(self.op.filter, self.op.fields, False)
4493

    
4494
  def ExpandNames(self):
4495
    self.impl.ExpandNames(self)
4496

    
4497
  def DeclareLocks(self, level):
4498
    self.impl.DeclareLocks(self, level)
4499

    
4500
  def Exec(self, feedback_fn):
4501
    return self.impl.NewStyleQuery(self)
4502

    
4503

    
4504
class LUQueryFields(NoHooksLU):
4505
  """Query for resources/items of a certain kind.
4506

4507
  """
4508
  # pylint: disable-msg=W0142
4509
  REQ_BGL = False
4510

    
4511
  def CheckArguments(self):
4512
    self.qcls = _GetQueryImplementation(self.op.what)
4513

    
4514
  def ExpandNames(self):
4515
    self.needed_locks = {}
4516

    
4517
  def Exec(self, feedback_fn):
4518
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4519

    
4520

    
4521
class LUNodeModifyStorage(NoHooksLU):
4522
  """Logical unit for modifying a storage volume on a node.
4523

4524
  """
4525
  REQ_BGL = False
4526

    
4527
  def CheckArguments(self):
4528
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4529

    
4530
    storage_type = self.op.storage_type
4531

    
4532
    try:
4533
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4534
    except KeyError:
4535
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4536
                                 " modified" % storage_type,
4537
                                 errors.ECODE_INVAL)
4538

    
4539
    diff = set(self.op.changes.keys()) - modifiable
4540
    if diff:
4541
      raise errors.OpPrereqError("The following fields can not be modified for"
4542
                                 " storage units of type '%s': %r" %
4543
                                 (storage_type, list(diff)),
4544
                                 errors.ECODE_INVAL)
4545

    
4546
  def ExpandNames(self):
4547
    self.needed_locks = {
4548
      locking.LEVEL_NODE: self.op.node_name,
4549
      }
4550

    
4551
  def Exec(self, feedback_fn):
4552
    """Computes the list of nodes and their attributes.
4553

4554
    """
4555
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4556
    result = self.rpc.call_storage_modify(self.op.node_name,
4557
                                          self.op.storage_type, st_args,
4558
                                          self.op.name, self.op.changes)
4559
    result.Raise("Failed to modify storage unit '%s' on %s" %
4560
                 (self.op.name, self.op.node_name))
4561

    
4562

    
4563
class LUNodeAdd(LogicalUnit):
4564
  """Logical unit for adding node to the cluster.
4565

4566
  """
4567
  HPATH = "node-add"
4568
  HTYPE = constants.HTYPE_NODE
4569
  _NFLAGS = ["master_capable", "vm_capable"]
4570

    
4571
  def CheckArguments(self):
4572
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4573
    # validate/normalize the node name
4574
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4575
                                         family=self.primary_ip_family)
4576
    self.op.node_name = self.hostname.name
4577

    
4578
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4579
      raise errors.OpPrereqError("Cannot readd the master node",
4580
                                 errors.ECODE_STATE)
4581

    
4582
    if self.op.readd and self.op.group:
4583
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4584
                                 " being readded", errors.ECODE_INVAL)
4585

    
4586
  def BuildHooksEnv(self):
4587
    """Build hooks env.
4588

4589
    This will run on all nodes before, and on all nodes + the new node after.
4590

4591
    """
4592
    return {
4593
      "OP_TARGET": self.op.node_name,
4594
      "NODE_NAME": self.op.node_name,
4595
      "NODE_PIP": self.op.primary_ip,
4596
      "NODE_SIP": self.op.secondary_ip,
4597
      "MASTER_CAPABLE": str(self.op.master_capable),
4598
      "VM_CAPABLE": str(self.op.vm_capable),
4599
      }
4600

    
4601
  def BuildHooksNodes(self):
4602
    """Build hooks nodes.
4603

4604
    """
4605
    # Exclude added node
4606
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4607
    post_nodes = pre_nodes + [self.op.node_name, ]
4608

    
4609
    return (pre_nodes, post_nodes)
4610

    
4611
  def CheckPrereq(self):
4612
    """Check prerequisites.
4613

4614
    This checks:
4615
     - the new node is not already in the config
4616
     - it is resolvable
4617
     - its parameters (single/dual homed) matches the cluster
4618

4619
    Any errors are signaled by raising errors.OpPrereqError.
4620

4621
    """
4622
    cfg = self.cfg
4623
    hostname = self.hostname
4624
    node = hostname.name
4625
    primary_ip = self.op.primary_ip = hostname.ip
4626
    if self.op.secondary_ip is None:
4627
      if self.primary_ip_family == netutils.IP6Address.family:
4628
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4629
                                   " IPv4 address must be given as secondary",
4630
                                   errors.ECODE_INVAL)
4631
      self.op.secondary_ip = primary_ip
4632

    
4633
    secondary_ip = self.op.secondary_ip
4634
    if not netutils.IP4Address.IsValid(secondary_ip):
4635
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4636
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4637

    
4638
    node_list = cfg.GetNodeList()
4639
    if not self.op.readd and node in node_list:
4640
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4641
                                 node, errors.ECODE_EXISTS)
4642
    elif self.op.readd and node not in node_list:
4643
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4644
                                 errors.ECODE_NOENT)
4645

    
4646
    self.changed_primary_ip = False
4647

    
4648
    for existing_node_name in node_list:
4649
      existing_node = cfg.GetNodeInfo(existing_node_name)
4650

    
4651
      if self.op.readd and node == existing_node_name:
4652
        if existing_node.secondary_ip != secondary_ip:
4653
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4654
                                     " address configuration as before",
4655
                                     errors.ECODE_INVAL)
4656
        if existing_node.primary_ip != primary_ip:
4657
          self.changed_primary_ip = True
4658

    
4659
        continue
4660

    
4661
      if (existing_node.primary_ip == primary_ip or
4662
          existing_node.secondary_ip == primary_ip or
4663
          existing_node.primary_ip == secondary_ip or
4664
          existing_node.secondary_ip == secondary_ip):
4665
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4666
                                   " existing node %s" % existing_node.name,
4667
                                   errors.ECODE_NOTUNIQUE)
4668

    
4669
    # After this 'if' block, None is no longer a valid value for the
4670
    # _capable op attributes
4671
    if self.op.readd:
4672
      old_node = self.cfg.GetNodeInfo(node)
4673
      assert old_node is not None, "Can't retrieve locked node %s" % node
4674
      for attr in self._NFLAGS:
4675
        if getattr(self.op, attr) is None:
4676
          setattr(self.op, attr, getattr(old_node, attr))
4677
    else:
4678
      for attr in self._NFLAGS:
4679
        if getattr(self.op, attr) is None:
4680
          setattr(self.op, attr, True)
4681

    
4682
    if self.op.readd and not self.op.vm_capable:
4683
      pri, sec = cfg.GetNodeInstances(node)
4684
      if pri or sec:
4685
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4686
                                   " flag set to false, but it already holds"
4687
                                   " instances" % node,
4688
                                   errors.ECODE_STATE)
4689

    
4690
    # check that the type of the node (single versus dual homed) is the
4691
    # same as for the master
4692
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4693
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4694
    newbie_singlehomed = secondary_ip == primary_ip
4695
    if master_singlehomed != newbie_singlehomed:
4696
      if master_singlehomed:
4697
        raise errors.OpPrereqError("The master has no secondary ip but the"
4698
                                   " new node has one",
4699
                                   errors.ECODE_INVAL)
4700
      else:
4701
        raise errors.OpPrereqError("The master has a secondary ip but the"
4702
                                   " new node doesn't have one",
4703
                                   errors.ECODE_INVAL)
4704

    
4705
    # checks reachability
4706
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4707
      raise errors.OpPrereqError("Node not reachable by ping",
4708
                                 errors.ECODE_ENVIRON)
4709

    
4710
    if not newbie_singlehomed:
4711
      # check reachability from my secondary ip to newbie's secondary ip
4712
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4713
                           source=myself.secondary_ip):
4714
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4715
                                   " based ping to node daemon port",
4716
                                   errors.ECODE_ENVIRON)
4717

    
4718
    if self.op.readd:
4719
      exceptions = [node]
4720
    else:
4721
      exceptions = []
4722

    
4723
    if self.op.master_capable:
4724
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4725
    else:
4726
      self.master_candidate = False
4727

    
4728
    if self.op.readd:
4729
      self.new_node = old_node
4730
    else:
4731
      node_group = cfg.LookupNodeGroup(self.op.group)
4732
      self.new_node = objects.Node(name=node,
4733
                                   primary_ip=primary_ip,
4734
                                   secondary_ip=secondary_ip,
4735
                                   master_candidate=self.master_candidate,
4736
                                   offline=False, drained=False,
4737
                                   group=node_group)
4738

    
4739
    if self.op.ndparams:
4740
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4741

    
4742
  def Exec(self, feedback_fn):
4743
    """Adds the new node to the cluster.
4744

4745
    """
4746
    new_node = self.new_node
4747
    node = new_node.name
4748

    
4749
    # We adding a new node so we assume it's powered
4750
    new_node.powered = True
4751

    
4752
    # for re-adds, reset the offline/drained/master-candidate flags;
4753
    # we need to reset here, otherwise offline would prevent RPC calls
4754
    # later in the procedure; this also means that if the re-add
4755
    # fails, we are left with a non-offlined, broken node
4756
    if self.op.readd:
4757
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4758
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4759
      # if we demote the node, we do cleanup later in the procedure
4760
      new_node.master_candidate = self.master_candidate
4761
      if self.changed_primary_ip:
4762
        new_node.primary_ip = self.op.primary_ip
4763

    
4764
    # copy the master/vm_capable flags
4765
    for attr in self._NFLAGS:
4766
      setattr(new_node, attr, getattr(self.op, attr))
4767

    
4768
    # notify the user about any possible mc promotion
4769
    if new_node.master_candidate:
4770
      self.LogInfo("Node will be a master candidate")
4771

    
4772
    if self.op.ndparams:
4773
      new_node.ndparams = self.op.ndparams
4774
    else:
4775
      new_node.ndparams = {}
4776

    
4777
    # check connectivity
4778
    result = self.rpc.call_version([node])[node]
4779
    result.Raise("Can't get version information from node %s" % node)
4780
    if constants.PROTOCOL_VERSION == result.payload:
4781
      logging.info("Communication to node %s fine, sw version %s match",
4782
                   node, result.payload)
4783
    else:
4784
      raise errors.OpExecError("Version mismatch master version %s,"
4785
                               " node version %s" %
4786
                               (constants.PROTOCOL_VERSION, result.payload))
4787

    
4788
    # Add node to our /etc/hosts, and add key to known_hosts
4789
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4790
      master_node = self.cfg.GetMasterNode()
4791
      result = self.rpc.call_etc_hosts_modify(master_node,
4792
                                              constants.ETC_HOSTS_ADD,
4793
                                              self.hostname.name,
4794
                                              self.hostname.ip)
4795
      result.Raise("Can't update hosts file with new host data")
4796

    
4797
    if new_node.secondary_ip != new_node.primary_ip:
4798
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4799
                               False)
4800

    
4801
    node_verify_list = [self.cfg.GetMasterNode()]
4802
    node_verify_param = {
4803
      constants.NV_NODELIST: [node],
4804
      # TODO: do a node-net-test as well?
4805
    }
4806

    
4807
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4808
                                       self.cfg.GetClusterName())
4809
    for verifier in node_verify_list:
4810
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4811
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4812
      if nl_payload:
4813
        for failed in nl_payload:
4814
          feedback_fn("ssh/hostname verification failed"
4815
                      " (checking from %s): %s" %
4816
                      (verifier, nl_payload[failed]))
4817
        raise errors.OpExecError("ssh/hostname verification failed")
4818

    
4819
    if self.op.readd:
4820
      _RedistributeAncillaryFiles(self)
4821
      self.context.ReaddNode(new_node)
4822
      # make sure we redistribute the config
4823
      self.cfg.Update(new_node, feedback_fn)
4824
      # and make sure the new node will not have old files around
4825
      if not new_node.master_candidate:
4826
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4827
        msg = result.fail_msg
4828
        if msg:
4829
          self.LogWarning("Node failed to demote itself from master"
4830
                          " candidate status: %s" % msg)
4831
    else:
4832
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4833
                                  additional_vm=self.op.vm_capable)
4834
      self.context.AddNode(new_node, self.proc.GetECId())
4835

    
4836

    
4837
class LUNodeSetParams(LogicalUnit):
4838
  """Modifies the parameters of a node.
4839

4840
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4841
      to the node role (as _ROLE_*)
4842
  @cvar _R2F: a dictionary from node role to tuples of flags
4843
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4844

4845
  """
4846
  HPATH = "node-modify"
4847
  HTYPE = constants.HTYPE_NODE
4848
  REQ_BGL = False
4849
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4850
  _F2R = {
4851
    (True, False, False): _ROLE_CANDIDATE,
4852
    (False, True, False): _ROLE_DRAINED,
4853
    (False, False, True): _ROLE_OFFLINE,
4854
    (False, False, False): _ROLE_REGULAR,
4855
    }
4856
  _R2F = dict((v, k) for k, v in _F2R.items())
4857
  _FLAGS = ["master_candidate", "drained", "offline"]
4858

    
4859
  def CheckArguments(self):
4860
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4861
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4862
                self.op.master_capable, self.op.vm_capable,
4863
                self.op.secondary_ip, self.op.ndparams]
4864
    if all_mods.count(None) == len(all_mods):
4865
      raise errors.OpPrereqError("Please pass at least one modification",
4866
                                 errors.ECODE_INVAL)
4867
    if all_mods.count(True) > 1:
4868
      raise errors.OpPrereqError("Can't set the node into more than one"
4869
                                 " state at the same time",
4870
                                 errors.ECODE_INVAL)
4871

    
4872
    # Boolean value that tells us whether we might be demoting from MC
4873
    self.might_demote = (self.op.master_candidate == False or
4874
                         self.op.offline == True or
4875
                         self.op.drained == True or
4876
                         self.op.master_capable == False)
4877

    
4878
    if self.op.secondary_ip:
4879
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4880
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4881
                                   " address" % self.op.secondary_ip,
4882
                                   errors.ECODE_INVAL)
4883

    
4884
    self.lock_all = self.op.auto_promote and self.might_demote
4885
    self.lock_instances = self.op.secondary_ip is not None
4886

    
4887
  def ExpandNames(self):
4888
    if self.lock_all:
4889
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4890
    else:
4891
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4892

    
4893
    if self.lock_instances:
4894
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4895

    
4896
  def DeclareLocks(self, level):
4897
    # If we have locked all instances, before waiting to lock nodes, release
4898
    # all the ones living on nodes unrelated to the current operation.
4899
    if level == locking.LEVEL_NODE and self.lock_instances:
4900
      self.affected_instances = []
4901
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4902
        instances_keep = []
4903

    
4904
        # Build list of instances to release
4905
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4906
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4907
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4908
              self.op.node_name in instance.all_nodes):
4909
            instances_keep.append(instance_name)
4910
            self.affected_instances.append(instance)
4911

    
4912
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4913

    
4914
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4915
                set(instances_keep))
4916

    
4917
  def BuildHooksEnv(self):
4918
    """Build hooks env.
4919

4920
    This runs on the master node.
4921

4922
    """
4923
    return {
4924
      "OP_TARGET": self.op.node_name,
4925
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4926
      "OFFLINE": str(self.op.offline),
4927
      "DRAINED": str(self.op.drained),
4928
      "MASTER_CAPABLE": str(self.op.master_capable),
4929
      "VM_CAPABLE": str(self.op.vm_capable),
4930
      }
4931

    
4932
  def BuildHooksNodes(self):
4933
    """Build hooks nodes.
4934

4935
    """
4936
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4937
    return (nl, nl)
4938

    
4939
  def CheckPrereq(self):
4940
    """Check prerequisites.
4941

4942
    This only checks the instance list against the existing names.
4943

4944
    """
4945
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4946

    
4947
    if (self.op.master_candidate is not None or
4948
        self.op.drained is not None or
4949
        self.op.offline is not None):
4950
      # we can't change the master's node flags
4951
      if self.op.node_name == self.cfg.GetMasterNode():
4952
        raise errors.OpPrereqError("The master role can be changed"
4953
                                   " only via master-failover",
4954
                                   errors.ECODE_INVAL)
4955

    
4956
    if self.op.master_candidate and not node.master_capable:
4957
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4958
                                 " it a master candidate" % node.name,
4959
                                 errors.ECODE_STATE)
4960

    
4961
    if self.op.vm_capable == False:
4962
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4963
      if ipri or isec:
4964
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4965
                                   " the vm_capable flag" % node.name,
4966
                                   errors.ECODE_STATE)
4967

    
4968
    if node.master_candidate and self.might_demote and not self.lock_all:
4969
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4970
      # check if after removing the current node, we're missing master
4971
      # candidates
4972
      (mc_remaining, mc_should, _) = \
4973
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4974
      if mc_remaining < mc_should:
4975
        raise errors.OpPrereqError("Not enough master candidates, please"
4976
                                   " pass auto promote option to allow"
4977
                                   " promotion", errors.ECODE_STATE)
4978

    
4979
    self.old_flags = old_flags = (node.master_candidate,
4980
                                  node.drained, node.offline)
4981
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4982
    self.old_role = old_role = self._F2R[old_flags]
4983

    
4984
    # Check for ineffective changes
4985
    for attr in self._FLAGS:
4986
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4987
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4988
        setattr(self.op, attr, None)
4989

    
4990
    # Past this point, any flag change to False means a transition
4991
    # away from the respective state, as only real changes are kept
4992

    
4993
    # TODO: We might query the real power state if it supports OOB
4994
    if _SupportsOob(self.cfg, node):
4995
      if self.op.offline is False and not (node.powered or
4996
                                           self.op.powered == True):
4997
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4998
                                    " offline status can be reset") %
4999
                                   self.op.node_name)
5000
    elif self.op.powered is not None:
5001
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
5002
                                  " as it does not support out-of-band"
5003
                                  " handling") % self.op.node_name)
5004

    
5005
    # If we're being deofflined/drained, we'll MC ourself if needed
5006
    if (self.op.drained == False or self.op.offline == False or
5007
        (self.op.master_capable and not node.master_capable)):
5008
      if _DecideSelfPromotion(self):
5009
        self.op.master_candidate = True
5010
        self.LogInfo("Auto-promoting node to master candidate")
5011

    
5012
    # If we're no longer master capable, we'll demote ourselves from MC
5013
    if self.op.master_capable == False and node.master_candidate:
5014
      self.LogInfo("Demoting from master candidate")
5015
      self.op.master_candidate = False
5016

    
5017
    # Compute new role
5018
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
5019
    if self.op.master_candidate:
5020
      new_role = self._ROLE_CANDIDATE
5021
    elif self.op.drained:
5022
      new_role = self._ROLE_DRAINED
5023
    elif self.op.offline:
5024
      new_role = self._ROLE_OFFLINE
5025
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
5026
      # False is still in new flags, which means we're un-setting (the
5027
      # only) True flag
5028
      new_role = self._ROLE_REGULAR
5029
    else: # no new flags, nothing, keep old role
5030
      new_role = old_role
5031

    
5032
    self.new_role = new_role
5033

    
5034
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
5035
      # Trying to transition out of offline status
5036
      result = self.rpc.call_version([node.name])[node.name]
5037
      if result.fail_msg:
5038
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
5039
                                   " to report its version: %s" %
5040
                                   (node.name, result.fail_msg),
5041
                                   errors.ECODE_STATE)
5042
      else:
5043
        self.LogWarning("Transitioning node from offline to online state"
5044
                        " without using re-add. Please make sure the node"
5045
                        " is healthy!")
5046

    
5047
    if self.op.secondary_ip:
5048
      # Ok even without locking, because this can't be changed by any LU
5049
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
5050
      master_singlehomed = master.secondary_ip == master.primary_ip
5051
      if master_singlehomed and self.op.secondary_ip:
5052
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
5053
                                   " homed cluster", errors.ECODE_INVAL)
5054

    
5055
      if node.offline:
5056
        if self.affected_instances:
5057
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
5058
                                     " node has instances (%s) configured"
5059
                                     " to use it" % self.affected_instances)
5060
      else:
5061
        # On online nodes, check that no instances are running, and that
5062
        # the node has the new ip and we can reach it.
5063
        for instance in self.affected_instances:
5064
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
5065

    
5066
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
5067
        if master.name != node.name:
5068
          # check reachability from master secondary ip to new secondary ip
5069
          if not netutils.TcpPing(self.op.secondary_ip,
5070
                                  constants.DEFAULT_NODED_PORT,
5071
                                  source=master.secondary_ip):
5072
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
5073
                                       " based ping to node daemon port",
5074
                                       errors.ECODE_ENVIRON)
5075

    
5076
    if self.op.ndparams:
5077
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
5078
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
5079
      self.new_ndparams = new_ndparams
5080

    
5081
  def Exec(self, feedback_fn):
5082
    """Modifies a node.
5083

5084
    """
5085
    node = self.node
5086
    old_role = self.old_role
5087
    new_role = self.new_role
5088

    
5089
    result = []
5090

    
5091
    if self.op.ndparams:
5092
      node.ndparams = self.new_ndparams
5093

    
5094
    if self.op.powered is not None:
5095
      node.powered = self.op.powered
5096

    
5097
    for attr in ["master_capable", "vm_capable"]:
5098
      val = getattr(self.op, attr)
5099
      if val is not None:
5100
        setattr(node, attr, val)
5101
        result.append((attr, str(val)))
5102

    
5103
    if new_role != old_role:
5104
      # Tell the node to demote itself, if no longer MC and not offline
5105
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
5106
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
5107
        if msg:
5108
          self.LogWarning("Node failed to demote itself: %s", msg)
5109

    
5110
      new_flags = self._R2F[new_role]
5111
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
5112
        if of != nf:
5113
          result.append((desc, str(nf)))
5114
      (node.master_candidate, node.drained, node.offline) = new_flags
5115

    
5116
      # we locked all nodes, we adjust the CP before updating this node
5117
      if self.lock_all:
5118
        _AdjustCandidatePool(self, [node.name])
5119

    
5120
    if self.op.secondary_ip:
5121
      node.secondary_ip = self.op.secondary_ip
5122
      result.append(("secondary_ip", self.op.secondary_ip))
5123

    
5124
    # this will trigger configuration file update, if needed
5125
    self.cfg.Update(node, feedback_fn)
5126

    
5127
    # this will trigger job queue propagation or cleanup if the mc
5128
    # flag changed
5129
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
5130
      self.context.ReaddNode(node)
5131

    
5132
    return result
5133

    
5134

    
5135
class LUNodePowercycle(NoHooksLU):
5136
  """Powercycles a node.
5137

5138
  """
5139
  REQ_BGL = False
5140

    
5141
  def CheckArguments(self):
5142
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5143
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
5144
      raise errors.OpPrereqError("The node is the master and the force"
5145
                                 " parameter was not set",
5146
                                 errors.ECODE_INVAL)
5147

    
5148
  def ExpandNames(self):
5149
    """Locking for PowercycleNode.
5150

5151
    This is a last-resort option and shouldn't block on other
5152
    jobs. Therefore, we grab no locks.
5153

5154
    """
5155
    self.needed_locks = {}
5156

    
5157
  def Exec(self, feedback_fn):
5158
    """Reboots a node.
5159

5160
    """
5161
    result = self.rpc.call_node_powercycle(self.op.node_name,
5162
                                           self.cfg.GetHypervisorType())
5163
    result.Raise("Failed to schedule the reboot")
5164
    return result.payload
5165

    
5166

    
5167
class LUClusterQuery(NoHooksLU):
5168
  """Query cluster configuration.
5169

5170
  """
5171
  REQ_BGL = False
5172

    
5173
  def ExpandNames(self):
5174
    self.needed_locks = {}
5175

    
5176
  def Exec(self, feedback_fn):
5177
    """Return cluster config.
5178

5179
    """
5180
    cluster = self.cfg.GetClusterInfo()
5181
    os_hvp = {}
5182

    
5183
    # Filter just for enabled hypervisors
5184
    for os_name, hv_dict in cluster.os_hvp.items():
5185
      os_hvp[os_name] = {}
5186
      for hv_name, hv_params in hv_dict.items():
5187
        if hv_name in cluster.enabled_hypervisors:
5188
          os_hvp[os_name][hv_name] = hv_params
5189

    
5190
    # Convert ip_family to ip_version
5191
    primary_ip_version = constants.IP4_VERSION
5192
    if cluster.primary_ip_family == netutils.IP6Address.family:
5193
      primary_ip_version = constants.IP6_VERSION
5194

    
5195
    result = {
5196
      "software_version": constants.RELEASE_VERSION,
5197
      "protocol_version": constants.PROTOCOL_VERSION,
5198
      "config_version": constants.CONFIG_VERSION,
5199
      "os_api_version": max(constants.OS_API_VERSIONS),
5200
      "export_version": constants.EXPORT_VERSION,
5201
      "architecture": (platform.architecture()[0], platform.machine()),
5202
      "name": cluster.cluster_name,
5203
      "master": cluster.master_node,
5204
      "default_hypervisor": cluster.enabled_hypervisors[0],
5205
      "enabled_hypervisors": cluster.enabled_hypervisors,
5206
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
5207
                        for hypervisor_name in cluster.enabled_hypervisors]),
5208
      "os_hvp": os_hvp,
5209
      "beparams": cluster.beparams,
5210
      "osparams": cluster.osparams,
5211
      "nicparams": cluster.nicparams,
5212
      "ndparams": cluster.ndparams,
5213
      "candidate_pool_size": cluster.candidate_pool_size,
5214
      "master_netdev": cluster.master_netdev,
5215
      "volume_group_name": cluster.volume_group_name,
5216
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5217
      "file_storage_dir": cluster.file_storage_dir,
5218
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5219
      "maintain_node_health": cluster.maintain_node_health,
5220
      "ctime": cluster.ctime,
5221
      "mtime": cluster.mtime,
5222
      "uuid": cluster.uuid,
5223
      "tags": list(cluster.GetTags()),
5224
      "uid_pool": cluster.uid_pool,
5225
      "default_iallocator": cluster.default_iallocator,
5226
      "reserved_lvs": cluster.reserved_lvs,
5227
      "primary_ip_version": primary_ip_version,
5228
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5229
      "hidden_os": cluster.hidden_os,
5230
      "blacklisted_os": cluster.blacklisted_os,
5231
      }
5232

    
5233
    return result
5234

    
5235

    
5236
class LUClusterConfigQuery(NoHooksLU):
5237
  """Return configuration values.
5238

5239
  """
5240
  REQ_BGL = False
5241
  _FIELDS_DYNAMIC = utils.FieldSet()
5242
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5243
                                  "watcher_pause", "volume_group_name")
5244

    
5245
  def CheckArguments(self):
5246
    _CheckOutputFields(static=self._FIELDS_STATIC,
5247
                       dynamic=self._FIELDS_DYNAMIC,
5248
                       selected=self.op.output_fields)
5249

    
5250
  def ExpandNames(self):
5251
    self.needed_locks = {}
5252

    
5253
  def Exec(self, feedback_fn):
5254
    """Dump a representation of the cluster config to the standard output.
5255

5256
    """
5257
    values = []
5258
    for field in self.op.output_fields:
5259
      if field == "cluster_name":
5260
        entry = self.cfg.GetClusterName()
5261
      elif field == "master_node":
5262
        entry = self.cfg.GetMasterNode()
5263
      elif field == "drain_flag":
5264
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5265
      elif field == "watcher_pause":
5266
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5267
      elif field == "volume_group_name":
5268
        entry = self.cfg.GetVGName()
5269
      else:
5270
        raise errors.ParameterError(field)
5271
      values.append(entry)
5272
    return values
5273

    
5274

    
5275
class LUInstanceActivateDisks(NoHooksLU):
5276
  """Bring up an instance's disks.
5277

5278
  """
5279
  REQ_BGL = False
5280

    
5281
  def ExpandNames(self):
5282
    self._ExpandAndLockInstance()
5283
    self.needed_locks[locking.LEVEL_NODE] = []
5284
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5285

    
5286
  def DeclareLocks(self, level):
5287
    if level == locking.LEVEL_NODE:
5288
      self._LockInstancesNodes()
5289

    
5290
  def CheckPrereq(self):
5291
    """Check prerequisites.
5292

5293
    This checks that the instance is in the cluster.
5294

5295
    """
5296
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5297
    assert self.instance is not None, \
5298
      "Cannot retrieve locked instance %s" % self.op.instance_name
5299
    _CheckNodeOnline(self, self.instance.primary_node)
5300

    
5301
  def Exec(self, feedback_fn):
5302
    """Activate the disks.
5303

5304
    """
5305
    disks_ok, disks_info = \
5306
              _AssembleInstanceDisks(self, self.instance,
5307
                                     ignore_size=self.op.ignore_size)
5308
    if not disks_ok:
5309
      raise errors.OpExecError("Cannot activate block devices")
5310

    
5311
    return disks_info
5312

    
5313

    
5314
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5315
                           ignore_size=False):
5316
  """Prepare the block devices for an instance.
5317

5318
  This sets up the block devices on all nodes.
5319

5320
  @type lu: L{LogicalUnit}
5321
  @param lu: the logical unit on whose behalf we execute
5322
  @type instance: L{objects.Instance}
5323
  @param instance: the instance for whose disks we assemble
5324
  @type disks: list of L{objects.Disk} or None
5325
  @param disks: which disks to assemble (or all, if None)
5326
  @type ignore_secondaries: boolean
5327
  @param ignore_secondaries: if true, errors on secondary nodes
5328
      won't result in an error return from the function
5329
  @type ignore_size: boolean
5330
  @param ignore_size: if true, the current known size of the disk
5331
      will not be used during the disk activation, useful for cases
5332
      when the size is wrong
5333
  @return: False if the operation failed, otherwise a list of
5334
      (host, instance_visible_name, node_visible_name)
5335
      with the mapping from node devices to instance devices
5336

5337
  """
5338
  device_info = []
5339
  disks_ok = True
5340
  iname = instance.name
5341
  disks = _ExpandCheckDisks(instance, disks)
5342

    
5343
  # With the two passes mechanism we try to reduce the window of
5344
  # opportunity for the race condition of switching DRBD to primary
5345
  # before handshaking occured, but we do not eliminate it
5346

    
5347
  # The proper fix would be to wait (with some limits) until the
5348
  # connection has been made and drbd transitions from WFConnection
5349
  # into any other network-connected state (Connected, SyncTarget,
5350
  # SyncSource, etc.)
5351

    
5352
  # 1st pass, assemble on all nodes in secondary mode
5353
  for idx, inst_disk in enumerate(disks):
5354
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5355
      if ignore_size:
5356
        node_disk = node_disk.Copy()
5357
        node_disk.UnsetSize()
5358
      lu.cfg.SetDiskID(node_disk, node)
5359
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5360
      msg = result.fail_msg
5361
      if msg:
5362
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5363
                           " (is_primary=False, pass=1): %s",
5364
                           inst_disk.iv_name, node, msg)
5365
        if not ignore_secondaries:
5366
          disks_ok = False
5367

    
5368
  # FIXME: race condition on drbd migration to primary
5369

    
5370
  # 2nd pass, do only the primary node
5371
  for idx, inst_disk in enumerate(disks):
5372
    dev_path = None
5373

    
5374
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5375
      if node != instance.primary_node:
5376
        continue
5377
      if ignore_size:
5378
        node_disk = node_disk.Copy()
5379
        node_disk.UnsetSize()
5380
      lu.cfg.SetDiskID(node_disk, node)
5381
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5382
      msg = result.fail_msg
5383
      if msg:
5384
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5385
                           " (is_primary=True, pass=2): %s",
5386
                           inst_disk.iv_name, node, msg)
5387
        disks_ok = False
5388
      else:
5389
        dev_path = result.payload
5390

    
5391
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5392

    
5393
  # leave the disks configured for the primary node
5394
  # this is a workaround that would be fixed better by
5395
  # improving the logical/physical id handling
5396
  for disk in disks:
5397
    lu.cfg.SetDiskID(disk, instance.primary_node)
5398

    
5399
  return disks_ok, device_info
5400

    
5401

    
5402
def _StartInstanceDisks(lu, instance, force):
5403
  """Start the disks of an instance.
5404

5405
  """
5406
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5407
                                           ignore_secondaries=force)
5408
  if not disks_ok:
5409
    _ShutdownInstanceDisks(lu, instance)
5410
    if force is not None and not force:
5411
      lu.proc.LogWarning("", hint="If the message above refers to a"
5412
                         " secondary node,"
5413
                         " you can retry the operation using '--force'.")
5414
    raise errors.OpExecError("Disk consistency error")
5415

    
5416

    
5417
class LUInstanceDeactivateDisks(NoHooksLU):
5418
  """Shutdown an instance's disks.
5419

5420
  """
5421
  REQ_BGL = False
5422

    
5423
  def ExpandNames(self):
5424
    self._ExpandAndLockInstance()
5425
    self.needed_locks[locking.LEVEL_NODE] = []
5426
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5427

    
5428
  def DeclareLocks(self, level):
5429
    if level == locking.LEVEL_NODE:
5430
      self._LockInstancesNodes()
5431

    
5432
  def CheckPrereq(self):
5433
    """Check prerequisites.
5434

5435
    This checks that the instance is in the cluster.
5436

5437
    """
5438
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5439
    assert self.instance is not None, \
5440
      "Cannot retrieve locked instance %s" % self.op.instance_name
5441

    
5442
  def Exec(self, feedback_fn):
5443
    """Deactivate the disks
5444

5445
    """
5446
    instance = self.instance
5447
    if self.op.force:
5448
      _ShutdownInstanceDisks(self, instance)
5449
    else:
5450
      _SafeShutdownInstanceDisks(self, instance)
5451

    
5452

    
5453
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5454
  """Shutdown block devices of an instance.
5455

5456
  This function checks if an instance is running, before calling
5457
  _ShutdownInstanceDisks.
5458

5459
  """
5460
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5461
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5462

    
5463

    
5464
def _ExpandCheckDisks(instance, disks):
5465
  """Return the instance disks selected by the disks list
5466

5467
  @type disks: list of L{objects.Disk} or None
5468
  @param disks: selected disks
5469
  @rtype: list of L{objects.Disk}
5470
  @return: selected instance disks to act on
5471

5472
  """
5473
  if disks is None:
5474
    return instance.disks
5475
  else:
5476
    if not set(disks).issubset(instance.disks):
5477
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5478
                                   " target instance")
5479
    return disks
5480

    
5481

    
5482
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5483
  """Shutdown block devices of an instance.
5484

5485
  This does the shutdown on all nodes of the instance.
5486

5487
  If the ignore_primary is false, errors on the primary node are
5488
  ignored.
5489

5490
  """
5491
  all_result = True
5492
  disks = _ExpandCheckDisks(instance, disks)
5493

    
5494
  for disk in disks:
5495
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5496
      lu.cfg.SetDiskID(top_disk, node)
5497
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5498
      msg = result.fail_msg
5499
      if msg:
5500
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5501
                      disk.iv_name, node, msg)
5502
        if ((node == instance.primary_node and not ignore_primary) or
5503
            (node != instance.primary_node and not result.offline)):
5504
          all_result = False
5505
  return all_result
5506

    
5507

    
5508
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5509
  """Checks if a node has enough free memory.
5510

5511
  This function check if a given node has the needed amount of free
5512
  memory. In case the node has less memory or we cannot get the
5513
  information from the node, this function raise an OpPrereqError
5514
  exception.
5515

5516
  @type lu: C{LogicalUnit}
5517
  @param lu: a logical unit from which we get configuration data
5518
  @type node: C{str}
5519
  @param node: the node to check
5520
  @type reason: C{str}
5521
  @param reason: string to use in the error message
5522
  @type requested: C{int}
5523
  @param requested: the amount of memory in MiB to check for
5524
  @type hypervisor_name: C{str}
5525
  @param hypervisor_name: the hypervisor to ask for memory stats
5526
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5527
      we cannot check the node
5528

5529
  """
5530
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5531
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5532
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5533
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5534
  if not isinstance(free_mem, int):
5535
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5536
                               " was '%s'" % (node, free_mem),
5537
                               errors.ECODE_ENVIRON)
5538
  if requested > free_mem:
5539
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5540
                               " needed %s MiB, available %s MiB" %
5541
                               (node, reason, requested, free_mem),
5542
                               errors.ECODE_NORES)
5543

    
5544

    
5545
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5546
  """Checks if nodes have enough free disk space in the all VGs.
5547

5548
  This function check if all given nodes have the needed amount of
5549
  free disk. In case any node has less disk or we cannot get the
5550
  information from the node, this function raise an OpPrereqError
5551
  exception.
5552

5553
  @type lu: C{LogicalUnit}
5554
  @param lu: a logical unit from which we get configuration data
5555
  @type nodenames: C{list}
5556
  @param nodenames: the list of node names to check
5557
  @type req_sizes: C{dict}
5558
  @param req_sizes: the hash of vg and corresponding amount of disk in
5559
      MiB to check for
5560
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5561
      or we cannot check the node
5562

5563
  """
5564
  for vg, req_size in req_sizes.items():
5565
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5566

    
5567

    
5568
def _CheckNodesFreeDiskOnVG(lu, nodenames, vg, requested):
5569
  """Checks if nodes have enough free disk space in the specified VG.
5570

5571
  This function check if all given nodes have the needed amount of
5572
  free disk. In case any node has less disk or we cannot get the
5573
  information from the node, this function raise an OpPrereqError
5574
  exception.
5575

5576
  @type lu: C{LogicalUnit}
5577
  @param lu: a logical unit from which we get configuration data
5578
  @type nodenames: C{list}
5579
  @param nodenames: the list of node names to check
5580
  @type vg: C{str}
5581
  @param vg: the volume group to check
5582
  @type requested: C{int}
5583
  @param requested: the amount of disk in MiB to check for
5584
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5585
      or we cannot check the node
5586

5587
  """
5588
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5589
  for node in nodenames:
5590
    info = nodeinfo[node]
5591
    info.Raise("Cannot get current information from node %s" % node,
5592
               prereq=True, ecode=errors.ECODE_ENVIRON)
5593
    vg_free = info.payload.get("vg_free", None)
5594
    if not isinstance(vg_free, int):
5595
      raise errors.OpPrereqError("Can't compute free disk space on node"
5596
                                 " %s for vg %s, result was '%s'" %
5597
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5598
    if requested > vg_free:
5599
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5600
                                 " vg %s: required %d MiB, available %d MiB" %
5601
                                 (node, vg, requested, vg_free),
5602
                                 errors.ECODE_NORES)
5603

    
5604

    
5605
class LUInstanceStartup(LogicalUnit):
5606
  """Starts an instance.
5607

5608
  """
5609
  HPATH = "instance-start"
5610
  HTYPE = constants.HTYPE_INSTANCE
5611
  REQ_BGL = False
5612

    
5613
  def CheckArguments(self):
5614
    # extra beparams
5615
    if self.op.beparams:
5616
      # fill the beparams dict
5617
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5618

    
5619
  def ExpandNames(self):
5620
    self._ExpandAndLockInstance()
5621

    
5622
  def BuildHooksEnv(self):
5623
    """Build hooks env.
5624

5625
    This runs on master, primary and secondary nodes of the instance.
5626

5627
    """
5628
    env = {
5629
      "FORCE": self.op.force,
5630
      }
5631

    
5632
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5633

    
5634
    return env
5635

    
5636
  def BuildHooksNodes(self):
5637
    """Build hooks nodes.
5638

5639
    """
5640
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5641
    return (nl, nl)
5642

    
5643
  def CheckPrereq(self):
5644
    """Check prerequisites.
5645

5646
    This checks that the instance is in the cluster.
5647

5648
    """
5649
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5650
    assert self.instance is not None, \
5651
      "Cannot retrieve locked instance %s" % self.op.instance_name
5652

    
5653
    # extra hvparams
5654
    if self.op.hvparams:
5655
      # check hypervisor parameter syntax (locally)
5656
      cluster = self.cfg.GetClusterInfo()
5657
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5658
      filled_hvp = cluster.FillHV(instance)
5659
      filled_hvp.update(self.op.hvparams)
5660
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5661
      hv_type.CheckParameterSyntax(filled_hvp)
5662
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5663

    
5664
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5665

    
5666
    if self.primary_offline and self.op.ignore_offline_nodes:
5667
      self.proc.LogWarning("Ignoring offline primary node")
5668

    
5669
      if self.op.hvparams or self.op.beparams:
5670
        self.proc.LogWarning("Overridden parameters are ignored")
5671
    else:
5672
      _CheckNodeOnline(self, instance.primary_node)
5673

    
5674
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5675

    
5676
      # check bridges existence
5677
      _CheckInstanceBridgesExist(self, instance)
5678

    
5679
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5680
                                                instance.name,
5681
                                                instance.hypervisor)
5682
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5683
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5684
      if not remote_info.payload: # not running already
5685
        _CheckNodeFreeMemory(self, instance.primary_node,
5686
                             "starting instance %s" % instance.name,
5687
                             bep[constants.BE_MEMORY], instance.hypervisor)
5688

    
5689
  def Exec(self, feedback_fn):
5690
    """Start the instance.
5691

5692
    """
5693
    instance = self.instance
5694
    force = self.op.force
5695

    
5696
    if not self.op.no_remember:
5697
      self.cfg.MarkInstanceUp(instance.name)
5698

    
5699
    if self.primary_offline:
5700
      assert self.op.ignore_offline_nodes
5701
      self.proc.LogInfo("Primary node offline, marked instance as started")
5702
    else:
5703
      node_current = instance.primary_node
5704

    
5705
      _StartInstanceDisks(self, instance, force)
5706

    
5707
      result = self.rpc.call_instance_start(node_current, instance,
5708
                                            self.op.hvparams, self.op.beparams,
5709
                                            self.op.startup_paused)
5710
      msg = result.fail_msg
5711
      if msg:
5712
        _ShutdownInstanceDisks(self, instance)
5713
        raise errors.OpExecError("Could not start instance: %s" % msg)
5714

    
5715

    
5716
class LUInstanceReboot(LogicalUnit):
5717
  """Reboot an instance.
5718

5719
  """
5720
  HPATH = "instance-reboot"
5721
  HTYPE = constants.HTYPE_INSTANCE
5722
  REQ_BGL = False
5723

    
5724
  def ExpandNames(self):
5725
    self._ExpandAndLockInstance()
5726

    
5727
  def BuildHooksEnv(self):
5728
    """Build hooks env.
5729

5730
    This runs on master, primary and secondary nodes of the instance.
5731

5732
    """
5733
    env = {
5734
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5735
      "REBOOT_TYPE": self.op.reboot_type,
5736
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5737
      }
5738

    
5739
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5740

    
5741
    return env
5742

    
5743
  def BuildHooksNodes(self):
5744
    """Build hooks nodes.
5745

5746
    """
5747
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5748
    return (nl, nl)
5749

    
5750
  def CheckPrereq(self):
5751
    """Check prerequisites.
5752

5753
    This checks that the instance is in the cluster.
5754

5755
    """
5756
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5757
    assert self.instance is not None, \
5758
      "Cannot retrieve locked instance %s" % self.op.instance_name
5759

    
5760
    _CheckNodeOnline(self, instance.primary_node)
5761

    
5762
    # check bridges existence
5763
    _CheckInstanceBridgesExist(self, instance)
5764

    
5765
  def Exec(self, feedback_fn):
5766
    """Reboot the instance.
5767

5768
    """
5769
    instance = self.instance
5770
    ignore_secondaries = self.op.ignore_secondaries
5771
    reboot_type = self.op.reboot_type
5772

    
5773
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5774
                                              instance.name,
5775
                                              instance.hypervisor)
5776
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5777
    instance_running = bool(remote_info.payload)
5778

    
5779
    node_current = instance.primary_node
5780

    
5781
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5782
                                            constants.INSTANCE_REBOOT_HARD]:
5783
      for disk in instance.disks:
5784
        self.cfg.SetDiskID(disk, node_current)
5785
      result = self.rpc.call_instance_reboot(node_current, instance,
5786
                                             reboot_type,
5787
                                             self.op.shutdown_timeout)
5788
      result.Raise("Could not reboot instance")
5789
    else:
5790
      if instance_running:
5791
        result = self.rpc.call_instance_shutdown(node_current, instance,
5792
                                                 self.op.shutdown_timeout)
5793
        result.Raise("Could not shutdown instance for full reboot")
5794
        _ShutdownInstanceDisks(self, instance)
5795
      else:
5796
        self.LogInfo("Instance %s was already stopped, starting now",
5797
                     instance.name)
5798
      _StartInstanceDisks(self, instance, ignore_secondaries)
5799
      result = self.rpc.call_instance_start(node_current, instance,
5800
                                            None, None, False)
5801
      msg = result.fail_msg
5802
      if msg:
5803
        _ShutdownInstanceDisks(self, instance)
5804
        raise errors.OpExecError("Could not start instance for"
5805
                                 " full reboot: %s" % msg)
5806

    
5807
    self.cfg.MarkInstanceUp(instance.name)
5808

    
5809

    
5810
class LUInstanceShutdown(LogicalUnit):
5811
  """Shutdown an instance.
5812

5813
  """
5814
  HPATH = "instance-stop"
5815
  HTYPE = constants.HTYPE_INSTANCE
5816
  REQ_BGL = False
5817

    
5818
  def ExpandNames(self):
5819
    self._ExpandAndLockInstance()
5820

    
5821
  def BuildHooksEnv(self):
5822
    """Build hooks env.
5823

5824
    This runs on master, primary and secondary nodes of the instance.
5825

5826
    """
5827
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5828
    env["TIMEOUT"] = self.op.timeout
5829
    return env
5830

    
5831
  def BuildHooksNodes(self):
5832
    """Build hooks nodes.
5833

5834
    """
5835
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5836
    return (nl, nl)
5837

    
5838
  def CheckPrereq(self):
5839
    """Check prerequisites.
5840

5841
    This checks that the instance is in the cluster.
5842

5843
    """
5844
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5845
    assert self.instance is not None, \
5846
      "Cannot retrieve locked instance %s" % self.op.instance_name
5847

    
5848
    self.primary_offline = \
5849
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5850

    
5851
    if self.primary_offline and self.op.ignore_offline_nodes:
5852
      self.proc.LogWarning("Ignoring offline primary node")
5853
    else:
5854
      _CheckNodeOnline(self, self.instance.primary_node)
5855

    
5856
  def Exec(self, feedback_fn):
5857
    """Shutdown the instance.
5858

5859
    """
5860
    instance = self.instance
5861
    node_current = instance.primary_node
5862
    timeout = self.op.timeout
5863

    
5864
    if not self.op.no_remember:
5865
      self.cfg.MarkInstanceDown(instance.name)
5866

    
5867
    if self.primary_offline:
5868
      assert self.op.ignore_offline_nodes
5869
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5870
    else:
5871
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5872
      msg = result.fail_msg
5873
      if msg:
5874
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5875

    
5876
      _ShutdownInstanceDisks(self, instance)
5877

    
5878

    
5879
class LUInstanceReinstall(LogicalUnit):
5880
  """Reinstall an instance.
5881

5882
  """
5883
  HPATH = "instance-reinstall"
5884
  HTYPE = constants.HTYPE_INSTANCE
5885
  REQ_BGL = False
5886

    
5887
  def ExpandNames(self):
5888
    self._ExpandAndLockInstance()
5889

    
5890
  def BuildHooksEnv(self):
5891
    """Build hooks env.
5892

5893
    This runs on master, primary and secondary nodes of the instance.
5894

5895
    """
5896
    return _BuildInstanceHookEnvByObject(self, self.instance)
5897

    
5898
  def BuildHooksNodes(self):
5899
    """Build hooks nodes.
5900

5901
    """
5902
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5903
    return (nl, nl)
5904

    
5905
  def CheckPrereq(self):
5906
    """Check prerequisites.
5907

5908
    This checks that the instance is in the cluster and is not running.
5909

5910
    """
5911
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5912
    assert instance is not None, \
5913
      "Cannot retrieve locked instance %s" % self.op.instance_name
5914
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5915
                     " offline, cannot reinstall")
5916
    for node in instance.secondary_nodes:
5917
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5918
                       " cannot reinstall")
5919

    
5920
    if instance.disk_template == constants.DT_DISKLESS:
5921
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5922
                                 self.op.instance_name,
5923
                                 errors.ECODE_INVAL)
5924
    _CheckInstanceDown(self, instance, "cannot reinstall")
5925

    
5926
    if self.op.os_type is not None:
5927
      # OS verification
5928
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5929
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5930
      instance_os = self.op.os_type
5931
    else:
5932
      instance_os = instance.os
5933

    
5934
    nodelist = list(instance.all_nodes)
5935

    
5936
    if self.op.osparams:
5937
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5938
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5939
      self.os_inst = i_osdict # the new dict (without defaults)
5940
    else:
5941
      self.os_inst = None
5942

    
5943
    self.instance = instance
5944

    
5945
  def Exec(self, feedback_fn):
5946
    """Reinstall the instance.
5947

5948
    """
5949
    inst = self.instance
5950

    
5951
    if self.op.os_type is not None:
5952
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5953
      inst.os = self.op.os_type
5954
      # Write to configuration
5955
      self.cfg.Update(inst, feedback_fn)
5956

    
5957
    _StartInstanceDisks(self, inst, None)
5958
    try:
5959
      feedback_fn("Running the instance OS create scripts...")
5960
      # FIXME: pass debug option from opcode to backend
5961
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5962
                                             self.op.debug_level,
5963
                                             osparams=self.os_inst)
5964
      result.Raise("Could not install OS for instance %s on node %s" %
5965
                   (inst.name, inst.primary_node))
5966
    finally:
5967
      _ShutdownInstanceDisks(self, inst)
5968

    
5969

    
5970
class LUInstanceRecreateDisks(LogicalUnit):
5971
  """Recreate an instance's missing disks.
5972

5973
  """
5974
  HPATH = "instance-recreate-disks"
5975
  HTYPE = constants.HTYPE_INSTANCE
5976
  REQ_BGL = False
5977

    
5978
  def CheckArguments(self):
5979
    # normalise the disk list
5980
    self.op.disks = sorted(frozenset(self.op.disks))
5981

    
5982
  def ExpandNames(self):
5983
    self._ExpandAndLockInstance()
5984
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5985
    if self.op.nodes:
5986
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5987
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5988
    else:
5989
      self.needed_locks[locking.LEVEL_NODE] = []
5990

    
5991
  def DeclareLocks(self, level):
5992
    if level == locking.LEVEL_NODE:
5993
      # if we replace the nodes, we only need to lock the old primary,
5994
      # otherwise we need to lock all nodes for disk re-creation
5995
      primary_only = bool(self.op.nodes)
5996
      self._LockInstancesNodes(primary_only=primary_only)
5997

    
5998
  def BuildHooksEnv(self):
5999
    """Build hooks env.
6000

6001
    This runs on master, primary and secondary nodes of the instance.
6002

6003
    """
6004
    return _BuildInstanceHookEnvByObject(self, self.instance)
6005

    
6006
  def BuildHooksNodes(self):
6007
    """Build hooks nodes.
6008

6009
    """
6010
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6011
    return (nl, nl)
6012

    
6013
  def CheckPrereq(self):
6014
    """Check prerequisites.
6015

6016
    This checks that the instance is in the cluster and is not running.
6017

6018
    """
6019
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6020
    assert instance is not None, \
6021
      "Cannot retrieve locked instance %s" % self.op.instance_name
6022
    if self.op.nodes:
6023
      if len(self.op.nodes) != len(instance.all_nodes):
6024
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
6025
                                   " %d replacement nodes were specified" %
6026
                                   (instance.name, len(instance.all_nodes),
6027
                                    len(self.op.nodes)),
6028
                                   errors.ECODE_INVAL)
6029
      assert instance.disk_template != constants.DT_DRBD8 or \
6030
          len(self.op.nodes) == 2
6031
      assert instance.disk_template != constants.DT_PLAIN or \
6032
          len(self.op.nodes) == 1
6033
      primary_node = self.op.nodes[0]
6034
    else:
6035
      primary_node = instance.primary_node
6036
    _CheckNodeOnline(self, primary_node)
6037

    
6038
    if instance.disk_template == constants.DT_DISKLESS:
6039
      raise errors.OpPrereqError("Instance '%s' has no disks" %
6040
                                 self.op.instance_name, errors.ECODE_INVAL)
6041
    # if we replace nodes *and* the old primary is offline, we don't
6042
    # check
6043
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
6044
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
6045
    if not (self.op.nodes and old_pnode.offline):
6046
      _CheckInstanceDown(self, instance, "cannot recreate disks")
6047

    
6048
    if not self.op.disks:
6049
      self.op.disks = range(len(instance.disks))
6050
    else:
6051
      for idx in self.op.disks:
6052
        if idx >= len(instance.disks):
6053
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
6054
                                     errors.ECODE_INVAL)
6055
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
6056
      raise errors.OpPrereqError("Can't recreate disks partially and"
6057
                                 " change the nodes at the same time",
6058
                                 errors.ECODE_INVAL)
6059
    self.instance = instance
6060

    
6061
  def Exec(self, feedback_fn):
6062
    """Recreate the disks.
6063

6064
    """
6065
    instance = self.instance
6066

    
6067
    to_skip = []
6068
    mods = [] # keeps track of needed logical_id changes
6069

    
6070
    for idx, disk in enumerate(instance.disks):
6071
      if idx not in self.op.disks: # disk idx has not been passed in
6072
        to_skip.append(idx)
6073
        continue
6074
      # update secondaries for disks, if needed
6075
      if self.op.nodes:
6076
        if disk.dev_type == constants.LD_DRBD8:
6077
          # need to update the nodes and minors
6078
          assert len(self.op.nodes) == 2
6079
          assert len(disk.logical_id) == 6 # otherwise disk internals
6080
                                           # have changed
6081
          (_, _, old_port, _, _, old_secret) = disk.logical_id
6082
          new_minors = self.cfg.AllocateDRBDMinor(self.op.nodes, instance.name)
6083
          new_id = (self.op.nodes[0], self.op.nodes[1], old_port,
6084
                    new_minors[0], new_minors[1], old_secret)
6085
          assert len(disk.logical_id) == len(new_id)
6086
          mods.append((idx, new_id))
6087

    
6088
    # now that we have passed all asserts above, we can apply the mods
6089
    # in a single run (to avoid partial changes)
6090
    for idx, new_id in mods:
6091
      instance.disks[idx].logical_id = new_id
6092

    
6093
    # change primary node, if needed
6094
    if self.op.nodes:
6095
      instance.primary_node = self.op.nodes[0]
6096
      self.LogWarning("Changing the instance's nodes, you will have to"
6097
                      " remove any disks left on the older nodes manually")
6098

    
6099
    if self.op.nodes:
6100
      self.cfg.Update(instance, feedback_fn)
6101

    
6102
    _CreateDisks(self, instance, to_skip=to_skip)
6103

    
6104

    
6105
class LUInstanceRename(LogicalUnit):
6106
  """Rename an instance.
6107

6108
  """
6109
  HPATH = "instance-rename"
6110
  HTYPE = constants.HTYPE_INSTANCE
6111

    
6112
  def CheckArguments(self):
6113
    """Check arguments.
6114

6115
    """
6116
    if self.op.ip_check and not self.op.name_check:
6117
      # TODO: make the ip check more flexible and not depend on the name check
6118
      raise errors.OpPrereqError("IP address check requires a name check",
6119
                                 errors.ECODE_INVAL)
6120

    
6121
  def BuildHooksEnv(self):
6122
    """Build hooks env.
6123

6124
    This runs on master, primary and secondary nodes of the instance.
6125

6126
    """
6127
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6128
    env["INSTANCE_NEW_NAME"] = self.op.new_name
6129
    return env
6130

    
6131
  def BuildHooksNodes(self):
6132
    """Build hooks nodes.
6133

6134
    """
6135
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
6136
    return (nl, nl)
6137

    
6138
  def CheckPrereq(self):
6139
    """Check prerequisites.
6140

6141
    This checks that the instance is in the cluster and is not running.
6142

6143
    """
6144
    self.op.instance_name = _ExpandInstanceName(self.cfg,
6145
                                                self.op.instance_name)
6146
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6147
    assert instance is not None
6148
    _CheckNodeOnline(self, instance.primary_node)
6149
    _CheckInstanceDown(self, instance, "cannot rename")
6150
    self.instance = instance
6151

    
6152
    new_name = self.op.new_name
6153
    if self.op.name_check:
6154
      hostname = netutils.GetHostname(name=new_name)
6155
      if hostname != new_name:
6156
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
6157
                     hostname.name)
6158
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
6159
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
6160
                                    " same as given hostname '%s'") %
6161
                                    (hostname.name, self.op.new_name),
6162
                                    errors.ECODE_INVAL)
6163
      new_name = self.op.new_name = hostname.name
6164
      if (self.op.ip_check and
6165
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
6166
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6167
                                   (hostname.ip, new_name),
6168
                                   errors.ECODE_NOTUNIQUE)
6169

    
6170
    instance_list = self.cfg.GetInstanceList()
6171
    if new_name in instance_list and new_name != instance.name:
6172
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6173
                                 new_name, errors.ECODE_EXISTS)
6174

    
6175
  def Exec(self, feedback_fn):
6176
    """Rename the instance.
6177

6178
    """
6179
    inst = self.instance
6180
    old_name = inst.name
6181

    
6182
    rename_file_storage = False
6183
    if (inst.disk_template in constants.DTS_FILEBASED and
6184
        self.op.new_name != inst.name):
6185
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6186
      rename_file_storage = True
6187

    
6188
    self.cfg.RenameInstance(inst.name, self.op.new_name)
6189
    # Change the instance lock. This is definitely safe while we hold the BGL.
6190
    # Otherwise the new lock would have to be added in acquired mode.
6191
    assert self.REQ_BGL
6192
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
6193
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
6194

    
6195
    # re-read the instance from the configuration after rename
6196
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
6197

    
6198
    if rename_file_storage:
6199
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
6200
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
6201
                                                     old_file_storage_dir,
6202
                                                     new_file_storage_dir)
6203
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
6204
                   " (but the instance has been renamed in Ganeti)" %
6205
                   (inst.primary_node, old_file_storage_dir,
6206
                    new_file_storage_dir))
6207

    
6208
    _StartInstanceDisks(self, inst, None)
6209
    try:
6210
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
6211
                                                 old_name, self.op.debug_level)
6212
      msg = result.fail_msg
6213
      if msg:
6214
        msg = ("Could not run OS rename script for instance %s on node %s"
6215
               " (but the instance has been renamed in Ganeti): %s" %
6216
               (inst.name, inst.primary_node, msg))
6217
        self.proc.LogWarning(msg)
6218
    finally:
6219
      _ShutdownInstanceDisks(self, inst)
6220

    
6221
    return inst.name
6222

    
6223

    
6224
class LUInstanceRemove(LogicalUnit):
6225
  """Remove an instance.
6226

6227
  """
6228
  HPATH = "instance-remove"
6229
  HTYPE = constants.HTYPE_INSTANCE
6230
  REQ_BGL = False
6231

    
6232
  def ExpandNames(self):
6233
    self._ExpandAndLockInstance()
6234
    self.needed_locks[locking.LEVEL_NODE] = []
6235
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6236

    
6237
  def DeclareLocks(self, level):
6238
    if level == locking.LEVEL_NODE:
6239
      self._LockInstancesNodes()
6240

    
6241
  def BuildHooksEnv(self):
6242
    """Build hooks env.
6243

6244
    This runs on master, primary and secondary nodes of the instance.
6245

6246
    """
6247
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6248
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6249
    return env
6250

    
6251
  def BuildHooksNodes(self):
6252
    """Build hooks nodes.
6253

6254
    """
6255
    nl = [self.cfg.GetMasterNode()]
6256
    nl_post = list(self.instance.all_nodes) + nl
6257
    return (nl, nl_post)
6258

    
6259
  def CheckPrereq(self):
6260
    """Check prerequisites.
6261

6262
    This checks that the instance is in the cluster.
6263

6264
    """
6265
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6266
    assert self.instance is not None, \
6267
      "Cannot retrieve locked instance %s" % self.op.instance_name
6268

    
6269
  def Exec(self, feedback_fn):
6270
    """Remove the instance.
6271

6272
    """
6273
    instance = self.instance
6274
    logging.info("Shutting down instance %s on node %s",
6275
                 instance.name, instance.primary_node)
6276

    
6277
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6278
                                             self.op.shutdown_timeout)
6279
    msg = result.fail_msg
6280
    if msg:
6281
      if self.op.ignore_failures:
6282
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6283
      else:
6284
        raise errors.OpExecError("Could not shutdown instance %s on"
6285
                                 " node %s: %s" %
6286
                                 (instance.name, instance.primary_node, msg))
6287

    
6288
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6289

    
6290

    
6291
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6292
  """Utility function to remove an instance.
6293

6294
  """
6295
  logging.info("Removing block devices for instance %s", instance.name)
6296

    
6297
  if not _RemoveDisks(lu, instance):
6298
    if not ignore_failures:
6299
      raise errors.OpExecError("Can't remove instance's disks")
6300
    feedback_fn("Warning: can't remove instance's disks")
6301

    
6302
  logging.info("Removing instance %s out of cluster config", instance.name)
6303

    
6304
  lu.cfg.RemoveInstance(instance.name)
6305

    
6306
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6307
    "Instance lock removal conflict"
6308

    
6309
  # Remove lock for the instance
6310
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6311

    
6312

    
6313
class LUInstanceQuery(NoHooksLU):
6314
  """Logical unit for querying instances.
6315

6316
  """
6317
  # pylint: disable-msg=W0142
6318
  REQ_BGL = False
6319

    
6320
  def CheckArguments(self):
6321
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6322
                             self.op.output_fields, self.op.use_locking)
6323

    
6324
  def ExpandNames(self):
6325
    self.iq.ExpandNames(self)
6326

    
6327
  def DeclareLocks(self, level):
6328
    self.iq.DeclareLocks(self, level)
6329

    
6330
  def Exec(self, feedback_fn):
6331
    return self.iq.OldStyleQuery(self)
6332

    
6333

    
6334
class LUInstanceFailover(LogicalUnit):
6335
  """Failover an instance.
6336

6337
  """
6338
  HPATH = "instance-failover"
6339
  HTYPE = constants.HTYPE_INSTANCE
6340
  REQ_BGL = False
6341

    
6342
  def CheckArguments(self):
6343
    """Check the arguments.
6344

6345
    """
6346
    self.iallocator = getattr(self.op, "iallocator", None)
6347
    self.target_node = getattr(self.op, "target_node", None)
6348

    
6349
  def ExpandNames(self):
6350
    self._ExpandAndLockInstance()
6351

    
6352
    if self.op.target_node is not None:
6353
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6354

    
6355
    self.needed_locks[locking.LEVEL_NODE] = []
6356
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6357

    
6358
    ignore_consistency = self.op.ignore_consistency
6359
    shutdown_timeout = self.op.shutdown_timeout
6360
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6361
                                       cleanup=False,
6362
                                       failover=True,
6363
                                       ignore_consistency=ignore_consistency,
6364
                                       shutdown_timeout=shutdown_timeout)
6365
    self.tasklets = [self._migrater]
6366

    
6367
  def DeclareLocks(self, level):
6368
    if level == locking.LEVEL_NODE:
6369
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6370
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6371
        if self.op.target_node is None:
6372
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6373
        else:
6374
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6375
                                                   self.op.target_node]
6376
        del self.recalculate_locks[locking.LEVEL_NODE]
6377
      else:
6378
        self._LockInstancesNodes()
6379

    
6380
  def BuildHooksEnv(self):
6381
    """Build hooks env.
6382

6383
    This runs on master, primary and secondary nodes of the instance.
6384

6385
    """
6386
    instance = self._migrater.instance
6387
    source_node = instance.primary_node
6388
    target_node = self.op.target_node
6389
    env = {
6390
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6391
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6392
      "OLD_PRIMARY": source_node,
6393
      "NEW_PRIMARY": target_node,
6394
      }
6395

    
6396
    if instance.disk_template in constants.DTS_INT_MIRROR:
6397
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6398
      env["NEW_SECONDARY"] = source_node
6399
    else:
6400
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6401

    
6402
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6403

    
6404
    return env
6405

    
6406
  def BuildHooksNodes(self):
6407
    """Build hooks nodes.
6408

6409
    """
6410
    instance = self._migrater.instance
6411
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6412
    return (nl, nl + [instance.primary_node])
6413

    
6414

    
6415
class LUInstanceMigrate(LogicalUnit):
6416
  """Migrate an instance.
6417

6418
  This is migration without shutting down, compared to the failover,
6419
  which is done with shutdown.
6420

6421
  """
6422
  HPATH = "instance-migrate"
6423
  HTYPE = constants.HTYPE_INSTANCE
6424
  REQ_BGL = False
6425

    
6426
  def ExpandNames(self):
6427
    self._ExpandAndLockInstance()
6428

    
6429
    if self.op.target_node is not None:
6430
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6431

    
6432
    self.needed_locks[locking.LEVEL_NODE] = []
6433
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6434

    
6435
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6436
                                       cleanup=self.op.cleanup,
6437
                                       failover=False,
6438
                                       fallback=self.op.allow_failover)
6439
    self.tasklets = [self._migrater]
6440

    
6441
  def DeclareLocks(self, level):
6442
    if level == locking.LEVEL_NODE:
6443
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6444
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6445
        if self.op.target_node is None:
6446
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6447
        else:
6448
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6449
                                                   self.op.target_node]
6450
        del self.recalculate_locks[locking.LEVEL_NODE]
6451
      else:
6452
        self._LockInstancesNodes()
6453

    
6454
  def BuildHooksEnv(self):
6455
    """Build hooks env.
6456

6457
    This runs on master, primary and secondary nodes of the instance.
6458

6459
    """
6460
    instance = self._migrater.instance
6461
    source_node = instance.primary_node
6462
    target_node = self.op.target_node
6463
    env = _BuildInstanceHookEnvByObject(self, instance)
6464
    env.update({
6465
      "MIGRATE_LIVE": self._migrater.live,
6466
      "MIGRATE_CLEANUP": self.op.cleanup,
6467
      "OLD_PRIMARY": source_node,
6468
      "NEW_PRIMARY": target_node,
6469
      })
6470

    
6471
    if instance.disk_template in constants.DTS_INT_MIRROR:
6472
      env["OLD_SECONDARY"] = target_node
6473
      env["NEW_SECONDARY"] = source_node
6474
    else:
6475
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6476

    
6477
    return env
6478

    
6479
  def BuildHooksNodes(self):
6480
    """Build hooks nodes.
6481

6482
    """
6483
    instance = self._migrater.instance
6484
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6485
    return (nl, nl + [instance.primary_node])
6486

    
6487

    
6488
class LUInstanceMove(LogicalUnit):
6489
  """Move an instance by data-copying.
6490

6491
  """
6492
  HPATH = "instance-move"
6493
  HTYPE = constants.HTYPE_INSTANCE
6494
  REQ_BGL = False
6495

    
6496
  def ExpandNames(self):
6497
    self._ExpandAndLockInstance()
6498
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6499
    self.op.target_node = target_node
6500
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6501
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6502

    
6503
  def DeclareLocks(self, level):
6504
    if level == locking.LEVEL_NODE:
6505
      self._LockInstancesNodes(primary_only=True)
6506

    
6507
  def BuildHooksEnv(self):
6508
    """Build hooks env.
6509

6510
    This runs on master, primary and secondary nodes of the instance.
6511

6512
    """
6513
    env = {
6514
      "TARGET_NODE": self.op.target_node,
6515
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6516
      }
6517
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6518
    return env
6519

    
6520
  def BuildHooksNodes(self):
6521
    """Build hooks nodes.
6522

6523
    """
6524
    nl = [
6525
      self.cfg.GetMasterNode(),
6526
      self.instance.primary_node,
6527
      self.op.target_node,
6528
      ]
6529
    return (nl, nl)
6530

    
6531
  def CheckPrereq(self):
6532
    """Check prerequisites.
6533

6534
    This checks that the instance is in the cluster.
6535

6536
    """
6537
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6538
    assert self.instance is not None, \
6539
      "Cannot retrieve locked instance %s" % self.op.instance_name
6540

    
6541
    node = self.cfg.GetNodeInfo(self.op.target_node)
6542
    assert node is not None, \
6543
      "Cannot retrieve locked node %s" % self.op.target_node
6544

    
6545
    self.target_node = target_node = node.name
6546

    
6547
    if target_node == instance.primary_node:
6548
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6549
                                 (instance.name, target_node),
6550
                                 errors.ECODE_STATE)
6551

    
6552
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6553

    
6554
    for idx, dsk in enumerate(instance.disks):
6555
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6556
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6557
                                   " cannot copy" % idx, errors.ECODE_STATE)
6558

    
6559
    _CheckNodeOnline(self, target_node)
6560
    _CheckNodeNotDrained(self, target_node)
6561
    _CheckNodeVmCapable(self, target_node)
6562

    
6563
    if instance.admin_up:
6564
      # check memory requirements on the secondary node
6565
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6566
                           instance.name, bep[constants.BE_MEMORY],
6567
                           instance.hypervisor)
6568
    else:
6569
      self.LogInfo("Not checking memory on the secondary node as"
6570
                   " instance will not be started")
6571

    
6572
    # check bridge existance
6573
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6574

    
6575
  def Exec(self, feedback_fn):
6576
    """Move an instance.
6577

6578
    The move is done by shutting it down on its present node, copying
6579
    the data over (slow) and starting it on the new node.
6580

6581
    """
6582
    instance = self.instance
6583

    
6584
    source_node = instance.primary_node
6585
    target_node = self.target_node
6586

    
6587
    self.LogInfo("Shutting down instance %s on source node %s",
6588
                 instance.name, source_node)
6589

    
6590
    result = self.rpc.call_instance_shutdown(source_node, instance,
6591
                                             self.op.shutdown_timeout)
6592
    msg = result.fail_msg
6593
    if msg:
6594
      if self.op.ignore_consistency:
6595
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6596
                             " Proceeding anyway. Please make sure node"
6597
                             " %s is down. Error details: %s",
6598
                             instance.name, source_node, source_node, msg)
6599
      else:
6600
        raise errors.OpExecError("Could not shutdown instance %s on"
6601
                                 " node %s: %s" %
6602
                                 (instance.name, source_node, msg))
6603

    
6604
    # create the target disks
6605
    try:
6606
      _CreateDisks(self, instance, target_node=target_node)
6607
    except errors.OpExecError:
6608
      self.LogWarning("Device creation failed, reverting...")
6609
      try:
6610
        _RemoveDisks(self, instance, target_node=target_node)
6611
      finally:
6612
        self.cfg.ReleaseDRBDMinors(instance.name)
6613
        raise
6614

    
6615
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6616

    
6617
    errs = []
6618
    # activate, get path, copy the data over
6619
    for idx, disk in enumerate(instance.disks):
6620
      self.LogInfo("Copying data for disk %d", idx)
6621
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6622
                                               instance.name, True, idx)
6623
      if result.fail_msg:
6624
        self.LogWarning("Can't assemble newly created disk %d: %s",
6625
                        idx, result.fail_msg)
6626
        errs.append(result.fail_msg)
6627
        break
6628
      dev_path = result.payload
6629
      result = self.rpc.call_blockdev_export(source_node, disk,
6630
                                             target_node, dev_path,
6631
                                             cluster_name)
6632
      if result.fail_msg:
6633
        self.LogWarning("Can't copy data over for disk %d: %s",
6634
                        idx, result.fail_msg)
6635
        errs.append(result.fail_msg)
6636
        break
6637

    
6638
    if errs:
6639
      self.LogWarning("Some disks failed to copy, aborting")
6640
      try:
6641
        _RemoveDisks(self, instance, target_node=target_node)
6642
      finally:
6643
        self.cfg.ReleaseDRBDMinors(instance.name)
6644
        raise errors.OpExecError("Errors during disk copy: %s" %
6645
                                 (",".join(errs),))
6646

    
6647
    instance.primary_node = target_node
6648
    self.cfg.Update(instance, feedback_fn)
6649

    
6650
    self.LogInfo("Removing the disks on the original node")
6651
    _RemoveDisks(self, instance, target_node=source_node)
6652

    
6653
    # Only start the instance if it's marked as up
6654
    if instance.admin_up:
6655
      self.LogInfo("Starting instance %s on node %s",
6656
                   instance.name, target_node)
6657

    
6658
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6659
                                           ignore_secondaries=True)
6660
      if not disks_ok:
6661
        _ShutdownInstanceDisks(self, instance)
6662
        raise errors.OpExecError("Can't activate the instance's disks")
6663

    
6664
      result = self.rpc.call_instance_start(target_node, instance,
6665
                                            None, None, False)
6666
      msg = result.fail_msg
6667
      if msg:
6668
        _ShutdownInstanceDisks(self, instance)
6669
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6670
                                 (instance.name, target_node, msg))
6671

    
6672

    
6673
class LUNodeMigrate(LogicalUnit):
6674
  """Migrate all instances from a node.
6675

6676
  """
6677
  HPATH = "node-migrate"
6678
  HTYPE = constants.HTYPE_NODE
6679
  REQ_BGL = False
6680

    
6681
  def CheckArguments(self):
6682
    pass
6683

    
6684
  def ExpandNames(self):
6685
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6686

    
6687
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
6688
    self.needed_locks = {
6689
      locking.LEVEL_NODE: [self.op.node_name],
6690
      }
6691

    
6692
  def BuildHooksEnv(self):
6693
    """Build hooks env.
6694

6695
    This runs on the master, the primary and all the secondaries.
6696

6697
    """
6698
    return {
6699
      "NODE_NAME": self.op.node_name,
6700
      }
6701

    
6702
  def BuildHooksNodes(self):
6703
    """Build hooks nodes.
6704

6705
    """
6706
    nl = [self.cfg.GetMasterNode()]
6707
    return (nl, nl)
6708

    
6709
  def CheckPrereq(self):
6710
    pass
6711

    
6712
  def Exec(self, feedback_fn):
6713
    # Prepare jobs for migration instances
6714
    jobs = [
6715
      [opcodes.OpInstanceMigrate(instance_name=inst.name,
6716
                                 mode=self.op.mode,
6717
                                 live=self.op.live,
6718
                                 iallocator=self.op.iallocator,
6719
                                 target_node=self.op.target_node)]
6720
      for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name)
6721
      ]
6722

    
6723
    # TODO: Run iallocator in this opcode and pass correct placement options to
6724
    # OpInstanceMigrate. Since other jobs can modify the cluster between
6725
    # running the iallocator and the actual migration, a good consistency model
6726
    # will have to be found.
6727

    
6728
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
6729
            frozenset([self.op.node_name]))
6730

    
6731
    return ResultWithJobs(jobs)
6732

    
6733

    
6734
class TLMigrateInstance(Tasklet):
6735
  """Tasklet class for instance migration.
6736

6737
  @type live: boolean
6738
  @ivar live: whether the migration will be done live or non-live;
6739
      this variable is initalized only after CheckPrereq has run
6740
  @type cleanup: boolean
6741
  @ivar cleanup: Wheater we cleanup from a failed migration
6742
  @type iallocator: string
6743
  @ivar iallocator: The iallocator used to determine target_node
6744
  @type target_node: string
6745
  @ivar target_node: If given, the target_node to reallocate the instance to
6746
  @type failover: boolean
6747
  @ivar failover: Whether operation results in failover or migration
6748
  @type fallback: boolean
6749
  @ivar fallback: Whether fallback to failover is allowed if migration not
6750
                  possible
6751
  @type ignore_consistency: boolean
6752
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6753
                            and target node
6754
  @type shutdown_timeout: int
6755
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6756

6757
  """
6758
  def __init__(self, lu, instance_name, cleanup=False,
6759
               failover=False, fallback=False,
6760
               ignore_consistency=False,
6761
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6762
    """Initializes this class.
6763

6764
    """
6765
    Tasklet.__init__(self, lu)
6766

    
6767
    # Parameters
6768
    self.instance_name = instance_name
6769
    self.cleanup = cleanup
6770
    self.live = False # will be overridden later
6771
    self.failover = failover
6772
    self.fallback = fallback
6773
    self.ignore_consistency = ignore_consistency
6774
    self.shutdown_timeout = shutdown_timeout
6775

    
6776
  def CheckPrereq(self):
6777
    """Check prerequisites.
6778

6779
    This checks that the instance is in the cluster.
6780

6781
    """
6782
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6783
    instance = self.cfg.GetInstanceInfo(instance_name)
6784
    assert instance is not None
6785
    self.instance = instance
6786

    
6787
    if (not self.cleanup and not instance.admin_up and not self.failover and
6788
        self.fallback):
6789
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6790
                      " to failover")
6791
      self.failover = True
6792

    
6793
    if instance.disk_template not in constants.DTS_MIRRORED:
6794
      if self.failover:
6795
        text = "failovers"
6796
      else:
6797
        text = "migrations"
6798
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6799
                                 " %s" % (instance.disk_template, text),
6800
                                 errors.ECODE_STATE)
6801

    
6802
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6803
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6804

    
6805
      if self.lu.op.iallocator:
6806
        self._RunAllocator()
6807
      else:
6808
        # We set set self.target_node as it is required by
6809
        # BuildHooksEnv
6810
        self.target_node = self.lu.op.target_node
6811

    
6812
      # self.target_node is already populated, either directly or by the
6813
      # iallocator run
6814
      target_node = self.target_node
6815
      if self.target_node == instance.primary_node:
6816
        raise errors.OpPrereqError("Cannot migrate instance %s"
6817
                                   " to its primary (%s)" %
6818
                                   (instance.name, instance.primary_node))
6819

    
6820
      if len(self.lu.tasklets) == 1:
6821
        # It is safe to release locks only when we're the only tasklet
6822
        # in the LU
6823
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6824
                      keep=[instance.primary_node, self.target_node])
6825

    
6826
    else:
6827
      secondary_nodes = instance.secondary_nodes
6828
      if not secondary_nodes:
6829
        raise errors.ConfigurationError("No secondary node but using"
6830
                                        " %s disk template" %
6831
                                        instance.disk_template)
6832
      target_node = secondary_nodes[0]
6833
      if self.lu.op.iallocator or (self.lu.op.target_node and
6834
                                   self.lu.op.target_node != target_node):
6835
        if self.failover:
6836
          text = "failed over"
6837
        else:
6838
          text = "migrated"
6839
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6840
                                   " be %s to arbitrary nodes"
6841
                                   " (neither an iallocator nor a target"
6842
                                   " node can be passed)" %
6843
                                   (instance.disk_template, text),
6844
                                   errors.ECODE_INVAL)
6845

    
6846
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6847

    
6848
    # check memory requirements on the secondary node
6849
    if not self.failover or instance.admin_up:
6850
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6851
                           instance.name, i_be[constants.BE_MEMORY],
6852
                           instance.hypervisor)
6853
    else:
6854
      self.lu.LogInfo("Not checking memory on the secondary node as"
6855
                      " instance will not be started")
6856

    
6857
    # check bridge existance
6858
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6859

    
6860
    if not self.cleanup:
6861
      _CheckNodeNotDrained(self.lu, target_node)
6862
      if not self.failover:
6863
        result = self.rpc.call_instance_migratable(instance.primary_node,
6864
                                                   instance)
6865
        if result.fail_msg and self.fallback:
6866
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6867
                          " failover")
6868
          self.failover = True
6869
        else:
6870
          result.Raise("Can't migrate, please use failover",
6871
                       prereq=True, ecode=errors.ECODE_STATE)
6872

    
6873
    assert not (self.failover and self.cleanup)
6874

    
6875
    if not self.failover:
6876
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6877
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6878
                                   " parameters are accepted",
6879
                                   errors.ECODE_INVAL)
6880
      if self.lu.op.live is not None:
6881
        if self.lu.op.live:
6882
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6883
        else:
6884
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6885
        # reset the 'live' parameter to None so that repeated
6886
        # invocations of CheckPrereq do not raise an exception
6887
        self.lu.op.live = None
6888
      elif self.lu.op.mode is None:
6889
        # read the default value from the hypervisor
6890
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6891
                                                skip_globals=False)
6892
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6893

    
6894
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6895
    else:
6896
      # Failover is never live
6897
      self.live = False
6898

    
6899
  def _RunAllocator(self):
6900
    """Run the allocator based on input opcode.
6901

6902
    """
6903
    ial = IAllocator(self.cfg, self.rpc,
6904
                     mode=constants.IALLOCATOR_MODE_RELOC,
6905
                     name=self.instance_name,
6906
                     # TODO See why hail breaks with a single node below
6907
                     relocate_from=[self.instance.primary_node,
6908
                                    self.instance.primary_node],
6909
                     )
6910

    
6911
    ial.Run(self.lu.op.iallocator)
6912

    
6913
    if not ial.success:
6914
      raise errors.OpPrereqError("Can't compute nodes using"
6915
                                 " iallocator '%s': %s" %
6916
                                 (self.lu.op.iallocator, ial.info),
6917
                                 errors.ECODE_NORES)
6918
    if len(ial.result) != ial.required_nodes:
6919
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6920
                                 " of nodes (%s), required %s" %
6921
                                 (self.lu.op.iallocator, len(ial.result),
6922
                                  ial.required_nodes), errors.ECODE_FAULT)
6923
    self.target_node = ial.result[0]
6924
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6925
                 self.instance_name, self.lu.op.iallocator,
6926
                 utils.CommaJoin(ial.result))
6927

    
6928
  def _WaitUntilSync(self):
6929
    """Poll with custom rpc for disk sync.
6930

6931
    This uses our own step-based rpc call.
6932

6933
    """
6934
    self.feedback_fn("* wait until resync is done")
6935
    all_done = False
6936
    while not all_done:
6937
      all_done = True
6938
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6939
                                            self.nodes_ip,
6940
                                            self.instance.disks)
6941
      min_percent = 100
6942
      for node, nres in result.items():
6943
        nres.Raise("Cannot resync disks on node %s" % node)
6944
        node_done, node_percent = nres.payload
6945
        all_done = all_done and node_done
6946
        if node_percent is not None:
6947
          min_percent = min(min_percent, node_percent)
6948
      if not all_done:
6949
        if min_percent < 100:
6950
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6951
        time.sleep(2)
6952

    
6953
  def _EnsureSecondary(self, node):
6954
    """Demote a node to secondary.
6955

6956
    """
6957
    self.feedback_fn("* switching node %s to secondary mode" % node)
6958

    
6959
    for dev in self.instance.disks:
6960
      self.cfg.SetDiskID(dev, node)
6961

    
6962
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6963
                                          self.instance.disks)
6964
    result.Raise("Cannot change disk to secondary on node %s" % node)
6965

    
6966
  def _GoStandalone(self):
6967
    """Disconnect from the network.
6968

6969
    """
6970
    self.feedback_fn("* changing into standalone mode")
6971
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6972
                                               self.instance.disks)
6973
    for node, nres in result.items():
6974
      nres.Raise("Cannot disconnect disks node %s" % node)
6975

    
6976
  def _GoReconnect(self, multimaster):
6977
    """Reconnect to the network.
6978

6979
    """
6980
    if multimaster:
6981
      msg = "dual-master"
6982
    else:
6983
      msg = "single-master"
6984
    self.feedback_fn("* changing disks into %s mode" % msg)
6985
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6986
                                           self.instance.disks,
6987
                                           self.instance.name, multimaster)
6988
    for node, nres in result.items():
6989
      nres.Raise("Cannot change disks config on node %s" % node)
6990

    
6991
  def _ExecCleanup(self):
6992
    """Try to cleanup after a failed migration.
6993

6994
    The cleanup is done by:
6995
      - check that the instance is running only on one node
6996
        (and update the config if needed)
6997
      - change disks on its secondary node to secondary
6998
      - wait until disks are fully synchronized
6999
      - disconnect from the network
7000
      - change disks into single-master mode
7001
      - wait again until disks are fully synchronized
7002

7003
    """
7004
    instance = self.instance
7005
    target_node = self.target_node
7006
    source_node = self.source_node
7007

    
7008
    # check running on only one node
7009
    self.feedback_fn("* checking where the instance actually runs"
7010
                     " (if this hangs, the hypervisor might be in"
7011
                     " a bad state)")
7012
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
7013
    for node, result in ins_l.items():
7014
      result.Raise("Can't contact node %s" % node)
7015

    
7016
    runningon_source = instance.name in ins_l[source_node].payload
7017
    runningon_target = instance.name in ins_l[target_node].payload
7018

    
7019
    if runningon_source and runningon_target:
7020
      raise errors.OpExecError("Instance seems to be running on two nodes,"
7021
                               " or the hypervisor is confused; you will have"
7022
                               " to ensure manually that it runs only on one"
7023
                               " and restart this operation")
7024

    
7025
    if not (runningon_source or runningon_target):
7026
      raise errors.OpExecError("Instance does not seem to be running at all;"
7027
                               " in this case it's safer to repair by"
7028
                               " running 'gnt-instance stop' to ensure disk"
7029
                               " shutdown, and then restarting it")
7030

    
7031
    if runningon_target:
7032
      # the migration has actually succeeded, we need to update the config
7033
      self.feedback_fn("* instance running on secondary node (%s),"
7034
                       " updating config" % target_node)
7035
      instance.primary_node = target_node
7036
      self.cfg.Update(instance, self.feedback_fn)
7037
      demoted_node = source_node
7038
    else:
7039
      self.feedback_fn("* instance confirmed to be running on its"
7040
                       " primary node (%s)" % source_node)
7041
      demoted_node = target_node
7042

    
7043
    if instance.disk_template in constants.DTS_INT_MIRROR:
7044
      self._EnsureSecondary(demoted_node)
7045
      try:
7046
        self._WaitUntilSync()
7047
      except errors.OpExecError:
7048
        # we ignore here errors, since if the device is standalone, it
7049
        # won't be able to sync
7050
        pass
7051
      self._GoStandalone()
7052
      self._GoReconnect(False)
7053
      self._WaitUntilSync()
7054

    
7055
    self.feedback_fn("* done")
7056

    
7057
  def _RevertDiskStatus(self):
7058
    """Try to revert the disk status after a failed migration.
7059

7060
    """
7061
    target_node = self.target_node
7062
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
7063
      return
7064

    
7065
    try:
7066
      self._EnsureSecondary(target_node)
7067
      self._GoStandalone()
7068
      self._GoReconnect(False)
7069
      self._WaitUntilSync()
7070
    except errors.OpExecError, err:
7071
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
7072
                         " please try to recover the instance manually;"
7073
                         " error '%s'" % str(err))
7074

    
7075
  def _AbortMigration(self):
7076
    """Call the hypervisor code to abort a started migration.
7077

7078
    """
7079
    instance = self.instance
7080
    target_node = self.target_node
7081
    migration_info = self.migration_info
7082

    
7083
    abort_result = self.rpc.call_finalize_migration(target_node,
7084
                                                    instance,
7085
                                                    migration_info,
7086
                                                    False)
7087
    abort_msg = abort_result.fail_msg
7088
    if abort_msg:
7089
      logging.error("Aborting migration failed on target node %s: %s",
7090
                    target_node, abort_msg)
7091
      # Don't raise an exception here, as we stil have to try to revert the
7092
      # disk status, even if this step failed.
7093

    
7094
  def _ExecMigration(self):
7095
    """Migrate an instance.
7096

7097
    The migrate is done by:
7098
      - change the disks into dual-master mode
7099
      - wait until disks are fully synchronized again
7100
      - migrate the instance
7101
      - change disks on the new secondary node (the old primary) to secondary
7102
      - wait until disks are fully synchronized
7103
      - change disks into single-master mode
7104

7105
    """
7106
    instance = self.instance
7107
    target_node = self.target_node
7108
    source_node = self.source_node
7109

    
7110
    self.feedback_fn("* checking disk consistency between source and target")
7111
    for dev in instance.disks:
7112
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
7113
        raise errors.OpExecError("Disk %s is degraded or not fully"
7114
                                 " synchronized on target node,"
7115
                                 " aborting migration" % dev.iv_name)
7116

    
7117
    # First get the migration information from the remote node
7118
    result = self.rpc.call_migration_info(source_node, instance)
7119
    msg = result.fail_msg
7120
    if msg:
7121
      log_err = ("Failed fetching source migration information from %s: %s" %
7122
                 (source_node, msg))
7123
      logging.error(log_err)
7124
      raise errors.OpExecError(log_err)
7125

    
7126
    self.migration_info = migration_info = result.payload
7127

    
7128
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7129
      # Then switch the disks to master/master mode
7130
      self._EnsureSecondary(target_node)
7131
      self._GoStandalone()
7132
      self._GoReconnect(True)
7133
      self._WaitUntilSync()
7134

    
7135
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
7136
    result = self.rpc.call_accept_instance(target_node,
7137
                                           instance,
7138
                                           migration_info,
7139
                                           self.nodes_ip[target_node])
7140

    
7141
    msg = result.fail_msg
7142
    if msg:
7143
      logging.error("Instance pre-migration failed, trying to revert"
7144
                    " disk status: %s", msg)
7145
      self.feedback_fn("Pre-migration failed, aborting")
7146
      self._AbortMigration()
7147
      self._RevertDiskStatus()
7148
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
7149
                               (instance.name, msg))
7150

    
7151
    self.feedback_fn("* migrating instance to %s" % target_node)
7152
    result = self.rpc.call_instance_migrate(source_node, instance,
7153
                                            self.nodes_ip[target_node],
7154
                                            self.live)
7155
    msg = result.fail_msg
7156
    if msg:
7157
      logging.error("Instance migration failed, trying to revert"
7158
                    " disk status: %s", msg)
7159
      self.feedback_fn("Migration failed, aborting")
7160
      self._AbortMigration()
7161
      self._RevertDiskStatus()
7162
      raise errors.OpExecError("Could not migrate instance %s: %s" %
7163
                               (instance.name, msg))
7164

    
7165
    instance.primary_node = target_node
7166
    # distribute new instance config to the other nodes
7167
    self.cfg.Update(instance, self.feedback_fn)
7168

    
7169
    result = self.rpc.call_finalize_migration(target_node,
7170
                                              instance,
7171
                                              migration_info,
7172
                                              True)
7173
    msg = result.fail_msg
7174
    if msg:
7175
      logging.error("Instance migration succeeded, but finalization failed:"
7176
                    " %s", msg)
7177
      raise errors.OpExecError("Could not finalize instance migration: %s" %
7178
                               msg)
7179

    
7180
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
7181
      self._EnsureSecondary(source_node)
7182
      self._WaitUntilSync()
7183
      self._GoStandalone()
7184
      self._GoReconnect(False)
7185
      self._WaitUntilSync()
7186

    
7187
    self.feedback_fn("* done")
7188

    
7189
  def _ExecFailover(self):
7190
    """Failover an instance.
7191

7192
    The failover is done by shutting it down on its present node and
7193
    starting it on the secondary.
7194

7195
    """
7196
    instance = self.instance
7197
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
7198

    
7199
    source_node = instance.primary_node
7200
    target_node = self.target_node
7201

    
7202
    if instance.admin_up:
7203
      self.feedback_fn("* checking disk consistency between source and target")
7204
      for dev in instance.disks:
7205
        # for drbd, these are drbd over lvm
7206
        if not _CheckDiskConsistency(self, dev, target_node, False):
7207
          if not self.ignore_consistency:
7208
            raise errors.OpExecError("Disk %s is degraded on target node,"
7209
                                     " aborting failover" % dev.iv_name)
7210
    else:
7211
      self.feedback_fn("* not checking disk consistency as instance is not"
7212
                       " running")
7213

    
7214
    self.feedback_fn("* shutting down instance on source node")
7215
    logging.info("Shutting down instance %s on node %s",
7216
                 instance.name, source_node)
7217

    
7218
    result = self.rpc.call_instance_shutdown(source_node, instance,
7219
                                             self.shutdown_timeout)
7220
    msg = result.fail_msg
7221
    if msg:
7222
      if self.ignore_consistency or primary_node.offline:
7223
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7224
                           " proceeding anyway; please make sure node"
7225
                           " %s is down; error details: %s",
7226
                           instance.name, source_node, source_node, msg)
7227
      else:
7228
        raise errors.OpExecError("Could not shutdown instance %s on"
7229
                                 " node %s: %s" %
7230
                                 (instance.name, source_node, msg))
7231

    
7232
    self.feedback_fn("* deactivating the instance's disks on source node")
7233
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7234
      raise errors.OpExecError("Can't shut down the instance's disks.")
7235

    
7236
    instance.primary_node = target_node
7237
    # distribute new instance config to the other nodes
7238
    self.cfg.Update(instance, self.feedback_fn)
7239

    
7240
    # Only start the instance if it's marked as up
7241
    if instance.admin_up:
7242
      self.feedback_fn("* activating the instance's disks on target node")
7243
      logging.info("Starting instance %s on node %s",
7244
                   instance.name, target_node)
7245

    
7246
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7247
                                           ignore_secondaries=True)
7248
      if not disks_ok:
7249
        _ShutdownInstanceDisks(self, instance)
7250
        raise errors.OpExecError("Can't activate the instance's disks")
7251

    
7252
      self.feedback_fn("* starting the instance on the target node")
7253
      result = self.rpc.call_instance_start(target_node, instance, None, None,
7254
                                            False)
7255
      msg = result.fail_msg
7256
      if msg:
7257
        _ShutdownInstanceDisks(self, instance)
7258
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7259
                                 (instance.name, target_node, msg))
7260

    
7261
  def Exec(self, feedback_fn):
7262
    """Perform the migration.
7263

7264
    """
7265
    self.feedback_fn = feedback_fn
7266
    self.source_node = self.instance.primary_node
7267

    
7268
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7269
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7270
      self.target_node = self.instance.secondary_nodes[0]
7271
      # Otherwise self.target_node has been populated either
7272
      # directly, or through an iallocator.
7273

    
7274
    self.all_nodes = [self.source_node, self.target_node]
7275
    self.nodes_ip = {
7276
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7277
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7278
      }
7279

    
7280
    if self.failover:
7281
      feedback_fn("Failover instance %s" % self.instance.name)
7282
      self._ExecFailover()
7283
    else:
7284
      feedback_fn("Migrating instance %s" % self.instance.name)
7285

    
7286
      if self.cleanup:
7287
        return self._ExecCleanup()
7288
      else:
7289
        return self._ExecMigration()
7290

    
7291

    
7292
def _CreateBlockDev(lu, node, instance, device, force_create,
7293
                    info, force_open):
7294
  """Create a tree of block devices on a given node.
7295

7296
  If this device type has to be created on secondaries, create it and
7297
  all its children.
7298

7299
  If not, just recurse to children keeping the same 'force' value.
7300

7301
  @param lu: the lu on whose behalf we execute
7302
  @param node: the node on which to create the device
7303
  @type instance: L{objects.Instance}
7304
  @param instance: the instance which owns the device
7305
  @type device: L{objects.Disk}
7306
  @param device: the device to create
7307
  @type force_create: boolean
7308
  @param force_create: whether to force creation of this device; this
7309
      will be change to True whenever we find a device which has
7310
      CreateOnSecondary() attribute
7311
  @param info: the extra 'metadata' we should attach to the device
7312
      (this will be represented as a LVM tag)
7313
  @type force_open: boolean
7314
  @param force_open: this parameter will be passes to the
7315
      L{backend.BlockdevCreate} function where it specifies
7316
      whether we run on primary or not, and it affects both
7317
      the child assembly and the device own Open() execution
7318

7319
  """
7320
  if device.CreateOnSecondary():
7321
    force_create = True
7322

    
7323
  if device.children:
7324
    for child in device.children:
7325
      _CreateBlockDev(lu, node, instance, child, force_create,
7326
                      info, force_open)
7327

    
7328
  if not force_create:
7329
    return
7330

    
7331
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7332

    
7333

    
7334
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7335
  """Create a single block device on a given node.
7336

7337
  This will not recurse over children of the device, so they must be
7338
  created in advance.
7339

7340
  @param lu: the lu on whose behalf we execute
7341
  @param node: the node on which to create the device
7342
  @type instance: L{objects.Instance}
7343
  @param instance: the instance which owns the device
7344
  @type device: L{objects.Disk}
7345
  @param device: the device to create
7346
  @param info: the extra 'metadata' we should attach to the device
7347
      (this will be represented as a LVM tag)
7348
  @type force_open: boolean
7349
  @param force_open: this parameter will be passes to the
7350
      L{backend.BlockdevCreate} function where it specifies
7351
      whether we run on primary or not, and it affects both
7352
      the child assembly and the device own Open() execution
7353

7354
  """
7355
  lu.cfg.SetDiskID(device, node)
7356
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7357
                                       instance.name, force_open, info)
7358
  result.Raise("Can't create block device %s on"
7359
               " node %s for instance %s" % (device, node, instance.name))
7360
  if device.physical_id is None:
7361
    device.physical_id = result.payload
7362

    
7363

    
7364
def _GenerateUniqueNames(lu, exts):
7365
  """Generate a suitable LV name.
7366

7367
  This will generate a logical volume name for the given instance.
7368

7369
  """
7370
  results = []
7371
  for val in exts:
7372
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7373
    results.append("%s%s" % (new_id, val))
7374
  return results
7375

    
7376

    
7377
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7378
                         iv_name, p_minor, s_minor):
7379
  """Generate a drbd8 device complete with its children.
7380

7381
  """
7382
  assert len(vgnames) == len(names) == 2
7383
  port = lu.cfg.AllocatePort()
7384
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7385
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7386
                          logical_id=(vgnames[0], names[0]))
7387
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7388
                          logical_id=(vgnames[1], names[1]))
7389
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7390
                          logical_id=(primary, secondary, port,
7391
                                      p_minor, s_minor,
7392
                                      shared_secret),
7393
                          children=[dev_data, dev_meta],
7394
                          iv_name=iv_name)
7395
  return drbd_dev
7396

    
7397

    
7398
def _GenerateDiskTemplate(lu, template_name,
7399
                          instance_name, primary_node,
7400
                          secondary_nodes, disk_info,
7401
                          file_storage_dir, file_driver,
7402
                          base_index, feedback_fn):
7403
  """Generate the entire disk layout for a given template type.
7404

7405
  """
7406
  #TODO: compute space requirements
7407

    
7408
  vgname = lu.cfg.GetVGName()
7409
  disk_count = len(disk_info)
7410
  disks = []
7411
  if template_name == constants.DT_DISKLESS:
7412
    pass
7413
  elif template_name == constants.DT_PLAIN:
7414
    if len(secondary_nodes) != 0:
7415
      raise errors.ProgrammerError("Wrong template configuration")
7416

    
7417
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7418
                                      for i in range(disk_count)])
7419
    for idx, disk in enumerate(disk_info):
7420
      disk_index = idx + base_index
7421
      vg = disk.get(constants.IDISK_VG, vgname)
7422
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7423
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7424
                              size=disk[constants.IDISK_SIZE],
7425
                              logical_id=(vg, names[idx]),
7426
                              iv_name="disk/%d" % disk_index,
7427
                              mode=disk[constants.IDISK_MODE])
7428
      disks.append(disk_dev)
7429
  elif template_name == constants.DT_DRBD8:
7430
    if len(secondary_nodes) != 1:
7431
      raise errors.ProgrammerError("Wrong template configuration")
7432
    remote_node = secondary_nodes[0]
7433
    minors = lu.cfg.AllocateDRBDMinor(
7434
      [primary_node, remote_node] * len(disk_info), instance_name)
7435

    
7436
    names = []
7437
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7438
                                               for i in range(disk_count)]):
7439
      names.append(lv_prefix + "_data")
7440
      names.append(lv_prefix + "_meta")
7441
    for idx, disk in enumerate(disk_info):
7442
      disk_index = idx + base_index
7443
      data_vg = disk.get(constants.IDISK_VG, vgname)
7444
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7445
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7446
                                      disk[constants.IDISK_SIZE],
7447
                                      [data_vg, meta_vg],
7448
                                      names[idx * 2:idx * 2 + 2],
7449
                                      "disk/%d" % disk_index,
7450
                                      minors[idx * 2], minors[idx * 2 + 1])
7451
      disk_dev.mode = disk[constants.IDISK_MODE]
7452
      disks.append(disk_dev)
7453
  elif template_name == constants.DT_FILE:
7454
    if len(secondary_nodes) != 0:
7455
      raise errors.ProgrammerError("Wrong template configuration")
7456

    
7457
    opcodes.RequireFileStorage()
7458

    
7459
    for idx, disk in enumerate(disk_info):
7460
      disk_index = idx + base_index
7461
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7462
                              size=disk[constants.IDISK_SIZE],
7463
                              iv_name="disk/%d" % disk_index,
7464
                              logical_id=(file_driver,
7465
                                          "%s/disk%d" % (file_storage_dir,
7466
                                                         disk_index)),
7467
                              mode=disk[constants.IDISK_MODE])
7468
      disks.append(disk_dev)
7469
  elif template_name == constants.DT_SHARED_FILE:
7470
    if len(secondary_nodes) != 0:
7471
      raise errors.ProgrammerError("Wrong template configuration")
7472

    
7473
    opcodes.RequireSharedFileStorage()
7474

    
7475
    for idx, disk in enumerate(disk_info):
7476
      disk_index = idx + base_index
7477
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7478
                              size=disk[constants.IDISK_SIZE],
7479
                              iv_name="disk/%d" % disk_index,
7480
                              logical_id=(file_driver,
7481
                                          "%s/disk%d" % (file_storage_dir,
7482
                                                         disk_index)),
7483
                              mode=disk[constants.IDISK_MODE])
7484
      disks.append(disk_dev)
7485
  elif template_name == constants.DT_BLOCK:
7486
    if len(secondary_nodes) != 0:
7487
      raise errors.ProgrammerError("Wrong template configuration")
7488

    
7489
    for idx, disk in enumerate(disk_info):
7490
      disk_index = idx + base_index
7491
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7492
                              size=disk[constants.IDISK_SIZE],
7493
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7494
                                          disk[constants.IDISK_ADOPT]),
7495
                              iv_name="disk/%d" % disk_index,
7496
                              mode=disk[constants.IDISK_MODE])
7497
      disks.append(disk_dev)
7498

    
7499
  else:
7500
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7501
  return disks
7502

    
7503

    
7504
def _GetInstanceInfoText(instance):
7505
  """Compute that text that should be added to the disk's metadata.
7506

7507
  """
7508
  return "originstname+%s" % instance.name
7509

    
7510

    
7511
def _CalcEta(time_taken, written, total_size):
7512
  """Calculates the ETA based on size written and total size.
7513

7514
  @param time_taken: The time taken so far
7515
  @param written: amount written so far
7516
  @param total_size: The total size of data to be written
7517
  @return: The remaining time in seconds
7518

7519
  """
7520
  avg_time = time_taken / float(written)
7521
  return (total_size - written) * avg_time
7522

    
7523

    
7524
def _WipeDisks(lu, instance):
7525
  """Wipes instance disks.
7526

7527
  @type lu: L{LogicalUnit}
7528
  @param lu: the logical unit on whose behalf we execute
7529
  @type instance: L{objects.Instance}
7530
  @param instance: the instance whose disks we should create
7531
  @return: the success of the wipe
7532

7533
  """
7534
  node = instance.primary_node
7535

    
7536
  for device in instance.disks:
7537
    lu.cfg.SetDiskID(device, node)
7538

    
7539
  logging.info("Pause sync of instance %s disks", instance.name)
7540
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7541

    
7542
  for idx, success in enumerate(result.payload):
7543
    if not success:
7544
      logging.warn("pause-sync of instance %s for disks %d failed",
7545
                   instance.name, idx)
7546

    
7547
  try:
7548
    for idx, device in enumerate(instance.disks):
7549
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7550
      # MAX_WIPE_CHUNK at max
7551
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7552
                            constants.MIN_WIPE_CHUNK_PERCENT)
7553
      # we _must_ make this an int, otherwise rounding errors will
7554
      # occur
7555
      wipe_chunk_size = int(wipe_chunk_size)
7556

    
7557
      lu.LogInfo("* Wiping disk %d", idx)
7558
      logging.info("Wiping disk %d for instance %s, node %s using"
7559
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7560

    
7561
      offset = 0
7562
      size = device.size
7563
      last_output = 0
7564
      start_time = time.time()
7565

    
7566
      while offset < size:
7567
        wipe_size = min(wipe_chunk_size, size - offset)
7568
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7569
                      idx, offset, wipe_size)
7570
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7571
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7572
                     (idx, offset, wipe_size))
7573
        now = time.time()
7574
        offset += wipe_size
7575
        if now - last_output >= 60:
7576
          eta = _CalcEta(now - start_time, offset, size)
7577
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7578
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7579
          last_output = now
7580
  finally:
7581
    logging.info("Resume sync of instance %s disks", instance.name)
7582

    
7583
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7584

    
7585
    for idx, success in enumerate(result.payload):
7586
      if not success:
7587
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7588
                      " look at the status and troubleshoot the issue", idx)
7589
        logging.warn("resume-sync of instance %s for disks %d failed",
7590
                     instance.name, idx)
7591

    
7592

    
7593
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7594
  """Create all disks for an instance.
7595

7596
  This abstracts away some work from AddInstance.
7597

7598
  @type lu: L{LogicalUnit}
7599
  @param lu: the logical unit on whose behalf we execute
7600
  @type instance: L{objects.Instance}
7601
  @param instance: the instance whose disks we should create
7602
  @type to_skip: list
7603
  @param to_skip: list of indices to skip
7604
  @type target_node: string
7605
  @param target_node: if passed, overrides the target node for creation
7606
  @rtype: boolean
7607
  @return: the success of the creation
7608

7609
  """
7610
  info = _GetInstanceInfoText(instance)
7611
  if target_node is None:
7612
    pnode = instance.primary_node
7613
    all_nodes = instance.all_nodes
7614
  else:
7615
    pnode = target_node
7616
    all_nodes = [pnode]
7617

    
7618
  if instance.disk_template in constants.DTS_FILEBASED:
7619
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7620
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7621

    
7622
    result.Raise("Failed to create directory '%s' on"
7623
                 " node %s" % (file_storage_dir, pnode))
7624

    
7625
  # Note: this needs to be kept in sync with adding of disks in
7626
  # LUInstanceSetParams
7627
  for idx, device in enumerate(instance.disks):
7628
    if to_skip and idx in to_skip:
7629
      continue
7630
    logging.info("Creating volume %s for instance %s",
7631
                 device.iv_name, instance.name)
7632
    #HARDCODE
7633
    for node in all_nodes:
7634
      f_create = node == pnode
7635
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7636

    
7637

    
7638
def _RemoveDisks(lu, instance, target_node=None):
7639
  """Remove all disks for an instance.
7640

7641
  This abstracts away some work from `AddInstance()` and
7642
  `RemoveInstance()`. Note that in case some of the devices couldn't
7643
  be removed, the removal will continue with the other ones (compare
7644
  with `_CreateDisks()`).
7645

7646
  @type lu: L{LogicalUnit}
7647
  @param lu: the logical unit on whose behalf we execute
7648
  @type instance: L{objects.Instance}
7649
  @param instance: the instance whose disks we should remove
7650
  @type target_node: string
7651
  @param target_node: used to override the node on which to remove the disks
7652
  @rtype: boolean
7653
  @return: the success of the removal
7654

7655
  """
7656
  logging.info("Removing block devices for instance %s", instance.name)
7657

    
7658
  all_result = True
7659
  for device in instance.disks:
7660
    if target_node:
7661
      edata = [(target_node, device)]
7662
    else:
7663
      edata = device.ComputeNodeTree(instance.primary_node)
7664
    for node, disk in edata:
7665
      lu.cfg.SetDiskID(disk, node)
7666
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7667
      if msg:
7668
        lu.LogWarning("Could not remove block device %s on node %s,"
7669
                      " continuing anyway: %s", device.iv_name, node, msg)
7670
        all_result = False
7671

    
7672
  if instance.disk_template == constants.DT_FILE:
7673
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7674
    if target_node:
7675
      tgt = target_node
7676
    else:
7677
      tgt = instance.primary_node
7678
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7679
    if result.fail_msg:
7680
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7681
                    file_storage_dir, instance.primary_node, result.fail_msg)
7682
      all_result = False
7683

    
7684
  return all_result
7685

    
7686

    
7687
def _ComputeDiskSizePerVG(disk_template, disks):
7688
  """Compute disk size requirements in the volume group
7689

7690
  """
7691
  def _compute(disks, payload):
7692
    """Universal algorithm.
7693

7694
    """
7695
    vgs = {}
7696
    for disk in disks:
7697
      vgs[disk[constants.IDISK_VG]] = \
7698
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7699

    
7700
    return vgs
7701

    
7702
  # Required free disk space as a function of disk and swap space
7703
  req_size_dict = {
7704
    constants.DT_DISKLESS: {},
7705
    constants.DT_PLAIN: _compute(disks, 0),
7706
    # 128 MB are added for drbd metadata for each disk
7707
    constants.DT_DRBD8: _compute(disks, 128),
7708
    constants.DT_FILE: {},
7709
    constants.DT_SHARED_FILE: {},
7710
  }
7711

    
7712
  if disk_template not in req_size_dict:
7713
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7714
                                 " is unknown" %  disk_template)
7715

    
7716
  return req_size_dict[disk_template]
7717

    
7718

    
7719
def _ComputeDiskSize(disk_template, disks):
7720
  """Compute disk size requirements in the volume group
7721

7722
  """
7723
  # Required free disk space as a function of disk and swap space
7724
  req_size_dict = {
7725
    constants.DT_DISKLESS: None,
7726
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7727
    # 128 MB are added for drbd metadata for each disk
7728
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7729
    constants.DT_FILE: None,
7730
    constants.DT_SHARED_FILE: 0,
7731
    constants.DT_BLOCK: 0,
7732
  }
7733

    
7734
  if disk_template not in req_size_dict:
7735
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7736
                                 " is unknown" %  disk_template)
7737

    
7738
  return req_size_dict[disk_template]
7739

    
7740

    
7741
def _FilterVmNodes(lu, nodenames):
7742
  """Filters out non-vm_capable nodes from a list.
7743

7744
  @type lu: L{LogicalUnit}
7745
  @param lu: the logical unit for which we check
7746
  @type nodenames: list
7747
  @param nodenames: the list of nodes on which we should check
7748
  @rtype: list
7749
  @return: the list of vm-capable nodes
7750

7751
  """
7752
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7753
  return [name for name in nodenames if name not in vm_nodes]
7754

    
7755

    
7756
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7757
  """Hypervisor parameter validation.
7758

7759
  This function abstract the hypervisor parameter validation to be
7760
  used in both instance create and instance modify.
7761

7762
  @type lu: L{LogicalUnit}
7763
  @param lu: the logical unit for which we check
7764
  @type nodenames: list
7765
  @param nodenames: the list of nodes on which we should check
7766
  @type hvname: string
7767
  @param hvname: the name of the hypervisor we should use
7768
  @type hvparams: dict
7769
  @param hvparams: the parameters which we need to check
7770
  @raise errors.OpPrereqError: if the parameters are not valid
7771

7772
  """
7773
  nodenames = _FilterVmNodes(lu, nodenames)
7774
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7775
                                                  hvname,
7776
                                                  hvparams)
7777
  for node in nodenames:
7778
    info = hvinfo[node]
7779
    if info.offline:
7780
      continue
7781
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7782

    
7783

    
7784
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7785
  """OS parameters validation.
7786

7787
  @type lu: L{LogicalUnit}
7788
  @param lu: the logical unit for which we check
7789
  @type required: boolean
7790
  @param required: whether the validation should fail if the OS is not
7791
      found
7792
  @type nodenames: list
7793
  @param nodenames: the list of nodes on which we should check
7794
  @type osname: string
7795
  @param osname: the name of the hypervisor we should use
7796
  @type osparams: dict
7797
  @param osparams: the parameters which we need to check
7798
  @raise errors.OpPrereqError: if the parameters are not valid
7799

7800
  """
7801
  nodenames = _FilterVmNodes(lu, nodenames)
7802
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7803
                                   [constants.OS_VALIDATE_PARAMETERS],
7804
                                   osparams)
7805
  for node, nres in result.items():
7806
    # we don't check for offline cases since this should be run only
7807
    # against the master node and/or an instance's nodes
7808
    nres.Raise("OS Parameters validation failed on node %s" % node)
7809
    if not nres.payload:
7810
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7811
                 osname, node)
7812

    
7813

    
7814
class LUInstanceCreate(LogicalUnit):
7815
  """Create an instance.
7816

7817
  """
7818
  HPATH = "instance-add"
7819
  HTYPE = constants.HTYPE_INSTANCE
7820
  REQ_BGL = False
7821

    
7822
  def CheckArguments(self):
7823
    """Check arguments.
7824

7825
    """
7826
    # do not require name_check to ease forward/backward compatibility
7827
    # for tools
7828
    if self.op.no_install and self.op.start:
7829
      self.LogInfo("No-installation mode selected, disabling startup")
7830
      self.op.start = False
7831
    # validate/normalize the instance name
7832
    self.op.instance_name = \
7833
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7834

    
7835
    if self.op.ip_check and not self.op.name_check:
7836
      # TODO: make the ip check more flexible and not depend on the name check
7837
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7838
                                 " check", errors.ECODE_INVAL)
7839

    
7840
    # check nics' parameter names
7841
    for nic in self.op.nics:
7842
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7843

    
7844
    # check disks. parameter names and consistent adopt/no-adopt strategy
7845
    has_adopt = has_no_adopt = False
7846
    for disk in self.op.disks:
7847
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7848
      if constants.IDISK_ADOPT in disk:
7849
        has_adopt = True
7850
      else:
7851
        has_no_adopt = True
7852
    if has_adopt and has_no_adopt:
7853
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7854
                                 errors.ECODE_INVAL)
7855
    if has_adopt:
7856
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7857
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7858
                                   " '%s' disk template" %
7859
                                   self.op.disk_template,
7860
                                   errors.ECODE_INVAL)
7861
      if self.op.iallocator is not None:
7862
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7863
                                   " iallocator script", errors.ECODE_INVAL)
7864
      if self.op.mode == constants.INSTANCE_IMPORT:
7865
        raise errors.OpPrereqError("Disk adoption not allowed for"
7866
                                   " instance import", errors.ECODE_INVAL)
7867
    else:
7868
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7869
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7870
                                   " but no 'adopt' parameter given" %
7871
                                   self.op.disk_template,
7872
                                   errors.ECODE_INVAL)
7873

    
7874
    self.adopt_disks = has_adopt
7875

    
7876
    # instance name verification
7877
    if self.op.name_check:
7878
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7879
      self.op.instance_name = self.hostname1.name
7880
      # used in CheckPrereq for ip ping check
7881
      self.check_ip = self.hostname1.ip
7882
    else:
7883
      self.check_ip = None
7884

    
7885
    # file storage checks
7886
    if (self.op.file_driver and
7887
        not self.op.file_driver in constants.FILE_DRIVER):
7888
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7889
                                 self.op.file_driver, errors.ECODE_INVAL)
7890

    
7891
    if self.op.disk_template == constants.DT_FILE:
7892
      opcodes.RequireFileStorage()
7893
    elif self.op.disk_template == constants.DT_SHARED_FILE:
7894
      opcodes.RequireSharedFileStorage()
7895

    
7896
    ### Node/iallocator related checks
7897
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7898

    
7899
    if self.op.pnode is not None:
7900
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7901
        if self.op.snode is None:
7902
          raise errors.OpPrereqError("The networked disk templates need"
7903
                                     " a mirror node", errors.ECODE_INVAL)
7904
      elif self.op.snode:
7905
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7906
                        " template")
7907
        self.op.snode = None
7908

    
7909
    self._cds = _GetClusterDomainSecret()
7910

    
7911
    if self.op.mode == constants.INSTANCE_IMPORT:
7912
      # On import force_variant must be True, because if we forced it at
7913
      # initial install, our only chance when importing it back is that it
7914
      # works again!
7915
      self.op.force_variant = True
7916

    
7917
      if self.op.no_install:
7918
        self.LogInfo("No-installation mode has no effect during import")
7919

    
7920
    elif self.op.mode == constants.INSTANCE_CREATE:
7921
      if self.op.os_type is None:
7922
        raise errors.OpPrereqError("No guest OS specified",
7923
                                   errors.ECODE_INVAL)
7924
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7925
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7926
                                   " installation" % self.op.os_type,
7927
                                   errors.ECODE_STATE)
7928
      if self.op.disk_template is None:
7929
        raise errors.OpPrereqError("No disk template specified",
7930
                                   errors.ECODE_INVAL)
7931

    
7932
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7933
      # Check handshake to ensure both clusters have the same domain secret
7934
      src_handshake = self.op.source_handshake
7935
      if not src_handshake:
7936
        raise errors.OpPrereqError("Missing source handshake",
7937
                                   errors.ECODE_INVAL)
7938

    
7939
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7940
                                                           src_handshake)
7941
      if errmsg:
7942
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7943
                                   errors.ECODE_INVAL)
7944

    
7945
      # Load and check source CA
7946
      self.source_x509_ca_pem = self.op.source_x509_ca
7947
      if not self.source_x509_ca_pem:
7948
        raise errors.OpPrereqError("Missing source X509 CA",
7949
                                   errors.ECODE_INVAL)
7950

    
7951
      try:
7952
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7953
                                                    self._cds)
7954
      except OpenSSL.crypto.Error, err:
7955
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7956
                                   (err, ), errors.ECODE_INVAL)
7957

    
7958
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7959
      if errcode is not None:
7960
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7961
                                   errors.ECODE_INVAL)
7962

    
7963
      self.source_x509_ca = cert
7964

    
7965
      src_instance_name = self.op.source_instance_name
7966
      if not src_instance_name:
7967
        raise errors.OpPrereqError("Missing source instance name",
7968
                                   errors.ECODE_INVAL)
7969

    
7970
      self.source_instance_name = \
7971
          netutils.GetHostname(name=src_instance_name).name
7972

    
7973
    else:
7974
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7975
                                 self.op.mode, errors.ECODE_INVAL)
7976

    
7977
  def ExpandNames(self):
7978
    """ExpandNames for CreateInstance.
7979

7980
    Figure out the right locks for instance creation.
7981

7982
    """
7983
    self.needed_locks = {}
7984

    
7985
    instance_name = self.op.instance_name
7986
    # this is just a preventive check, but someone might still add this
7987
    # instance in the meantime, and creation will fail at lock-add time
7988
    if instance_name in self.cfg.GetInstanceList():
7989
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7990
                                 instance_name, errors.ECODE_EXISTS)
7991

    
7992
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7993

    
7994
    if self.op.iallocator:
7995
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7996
    else:
7997
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7998
      nodelist = [self.op.pnode]
7999
      if self.op.snode is not None:
8000
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
8001
        nodelist.append(self.op.snode)
8002
      self.needed_locks[locking.LEVEL_NODE] = nodelist
8003

    
8004
    # in case of import lock the source node too
8005
    if self.op.mode == constants.INSTANCE_IMPORT:
8006
      src_node = self.op.src_node
8007
      src_path = self.op.src_path
8008

    
8009
      if src_path is None:
8010
        self.op.src_path = src_path = self.op.instance_name
8011

    
8012
      if src_node is None:
8013
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
8014
        self.op.src_node = None
8015
        if os.path.isabs(src_path):
8016
          raise errors.OpPrereqError("Importing an instance from an absolute"
8017
                                     " path requires a source node option",
8018
                                     errors.ECODE_INVAL)
8019
      else:
8020
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
8021
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
8022
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
8023
        if not os.path.isabs(src_path):
8024
          self.op.src_path = src_path = \
8025
            utils.PathJoin(constants.EXPORT_DIR, src_path)
8026

    
8027
  def _RunAllocator(self):
8028
    """Run the allocator based on input opcode.
8029

8030
    """
8031
    nics = [n.ToDict() for n in self.nics]
8032
    ial = IAllocator(self.cfg, self.rpc,
8033
                     mode=constants.IALLOCATOR_MODE_ALLOC,
8034
                     name=self.op.instance_name,
8035
                     disk_template=self.op.disk_template,
8036
                     tags=self.op.tags,
8037
                     os=self.op.os_type,
8038
                     vcpus=self.be_full[constants.BE_VCPUS],
8039
                     memory=self.be_full[constants.BE_MEMORY],
8040
                     disks=self.disks,
8041
                     nics=nics,
8042
                     hypervisor=self.op.hypervisor,
8043
                     )
8044

    
8045
    ial.Run(self.op.iallocator)
8046

    
8047
    if not ial.success:
8048
      raise errors.OpPrereqError("Can't compute nodes using"
8049
                                 " iallocator '%s': %s" %
8050
                                 (self.op.iallocator, ial.info),
8051
                                 errors.ECODE_NORES)
8052
    if len(ial.result) != ial.required_nodes:
8053
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8054
                                 " of nodes (%s), required %s" %
8055
                                 (self.op.iallocator, len(ial.result),
8056
                                  ial.required_nodes), errors.ECODE_FAULT)
8057
    self.op.pnode = ial.result[0]
8058
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
8059
                 self.op.instance_name, self.op.iallocator,
8060
                 utils.CommaJoin(ial.result))
8061
    if ial.required_nodes == 2:
8062
      self.op.snode = ial.result[1]
8063

    
8064
  def BuildHooksEnv(self):
8065
    """Build hooks env.
8066

8067
    This runs on master, primary and secondary nodes of the instance.
8068

8069
    """
8070
    env = {
8071
      "ADD_MODE": self.op.mode,
8072
      }
8073
    if self.op.mode == constants.INSTANCE_IMPORT:
8074
      env["SRC_NODE"] = self.op.src_node
8075
      env["SRC_PATH"] = self.op.src_path
8076
      env["SRC_IMAGES"] = self.src_images
8077

    
8078
    env.update(_BuildInstanceHookEnv(
8079
      name=self.op.instance_name,
8080
      primary_node=self.op.pnode,
8081
      secondary_nodes=self.secondaries,
8082
      status=self.op.start,
8083
      os_type=self.op.os_type,
8084
      memory=self.be_full[constants.BE_MEMORY],
8085
      vcpus=self.be_full[constants.BE_VCPUS],
8086
      nics=_NICListToTuple(self, self.nics),
8087
      disk_template=self.op.disk_template,
8088
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
8089
             for d in self.disks],
8090
      bep=self.be_full,
8091
      hvp=self.hv_full,
8092
      hypervisor_name=self.op.hypervisor,
8093
      tags=self.op.tags,
8094
    ))
8095

    
8096
    return env
8097

    
8098
  def BuildHooksNodes(self):
8099
    """Build hooks nodes.
8100

8101
    """
8102
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
8103
    return nl, nl
8104

    
8105
  def _ReadExportInfo(self):
8106
    """Reads the export information from disk.
8107

8108
    It will override the opcode source node and path with the actual
8109
    information, if these two were not specified before.
8110

8111
    @return: the export information
8112

8113
    """
8114
    assert self.op.mode == constants.INSTANCE_IMPORT
8115

    
8116
    src_node = self.op.src_node
8117
    src_path = self.op.src_path
8118

    
8119
    if src_node is None:
8120
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
8121
      exp_list = self.rpc.call_export_list(locked_nodes)
8122
      found = False
8123
      for node in exp_list:
8124
        if exp_list[node].fail_msg:
8125
          continue
8126
        if src_path in exp_list[node].payload:
8127
          found = True
8128
          self.op.src_node = src_node = node
8129
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
8130
                                                       src_path)
8131
          break
8132
      if not found:
8133
        raise errors.OpPrereqError("No export found for relative path %s" %
8134
                                    src_path, errors.ECODE_INVAL)
8135

    
8136
    _CheckNodeOnline(self, src_node)
8137
    result = self.rpc.call_export_info(src_node, src_path)
8138
    result.Raise("No export or invalid export found in dir %s" % src_path)
8139

    
8140
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
8141
    if not export_info.has_section(constants.INISECT_EXP):
8142
      raise errors.ProgrammerError("Corrupted export config",
8143
                                   errors.ECODE_ENVIRON)
8144

    
8145
    ei_version = export_info.get(constants.INISECT_EXP, "version")
8146
    if (int(ei_version) != constants.EXPORT_VERSION):
8147
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
8148
                                 (ei_version, constants.EXPORT_VERSION),
8149
                                 errors.ECODE_ENVIRON)
8150
    return export_info
8151

    
8152
  def _ReadExportParams(self, einfo):
8153
    """Use export parameters as defaults.
8154

8155
    In case the opcode doesn't specify (as in override) some instance
8156
    parameters, then try to use them from the export information, if
8157
    that declares them.
8158

8159
    """
8160
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
8161

    
8162
    if self.op.disk_template is None:
8163
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
8164
        self.op.disk_template = einfo.get(constants.INISECT_INS,
8165
                                          "disk_template")
8166
      else:
8167
        raise errors.OpPrereqError("No disk template specified and the export"
8168
                                   " is missing the disk_template information",
8169
                                   errors.ECODE_INVAL)
8170

    
8171
    if not self.op.disks:
8172
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
8173
        disks = []
8174
        # TODO: import the disk iv_name too
8175
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
8176
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
8177
          disks.append({constants.IDISK_SIZE: disk_sz})
8178
        self.op.disks = disks
8179
      else:
8180
        raise errors.OpPrereqError("No disk info specified and the export"
8181
                                   " is missing the disk information",
8182
                                   errors.ECODE_INVAL)
8183

    
8184
    if (not self.op.nics and
8185
        einfo.has_option(constants.INISECT_INS, "nic_count")):
8186
      nics = []
8187
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
8188
        ndict = {}
8189
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
8190
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
8191
          ndict[name] = v
8192
        nics.append(ndict)
8193
      self.op.nics = nics
8194

    
8195
    if not self.op.tags and einfo.has_option(constants.INISECT_INS, "tags"):
8196
      self.op.tags = einfo.get(constants.INISECT_INS, "tags").split()
8197

    
8198
    if (self.op.hypervisor is None and
8199
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
8200
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
8201

    
8202
    if einfo.has_section(constants.INISECT_HYP):
8203
      # use the export parameters but do not override the ones
8204
      # specified by the user
8205
      for name, value in einfo.items(constants.INISECT_HYP):
8206
        if name not in self.op.hvparams:
8207
          self.op.hvparams[name] = value
8208

    
8209
    if einfo.has_section(constants.INISECT_BEP):
8210
      # use the parameters, without overriding
8211
      for name, value in einfo.items(constants.INISECT_BEP):
8212
        if name not in self.op.beparams:
8213
          self.op.beparams[name] = value
8214
    else:
8215
      # try to read the parameters old style, from the main section
8216
      for name in constants.BES_PARAMETERS:
8217
        if (name not in self.op.beparams and
8218
            einfo.has_option(constants.INISECT_INS, name)):
8219
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
8220

    
8221
    if einfo.has_section(constants.INISECT_OSP):
8222
      # use the parameters, without overriding
8223
      for name, value in einfo.items(constants.INISECT_OSP):
8224
        if name not in self.op.osparams:
8225
          self.op.osparams[name] = value
8226

    
8227
  def _RevertToDefaults(self, cluster):
8228
    """Revert the instance parameters to the default values.
8229

8230
    """
8231
    # hvparams
8232
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8233
    for name in self.op.hvparams.keys():
8234
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8235
        del self.op.hvparams[name]
8236
    # beparams
8237
    be_defs = cluster.SimpleFillBE({})
8238
    for name in self.op.beparams.keys():
8239
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8240
        del self.op.beparams[name]
8241
    # nic params
8242
    nic_defs = cluster.SimpleFillNIC({})
8243
    for nic in self.op.nics:
8244
      for name in constants.NICS_PARAMETERS:
8245
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8246
          del nic[name]
8247
    # osparams
8248
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8249
    for name in self.op.osparams.keys():
8250
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8251
        del self.op.osparams[name]
8252

    
8253
  def _CalculateFileStorageDir(self):
8254
    """Calculate final instance file storage dir.
8255

8256
    """
8257
    # file storage dir calculation/check
8258
    self.instance_file_storage_dir = None
8259
    if self.op.disk_template in constants.DTS_FILEBASED:
8260
      # build the full file storage dir path
8261
      joinargs = []
8262

    
8263
      if self.op.disk_template == constants.DT_SHARED_FILE:
8264
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8265
      else:
8266
        get_fsd_fn = self.cfg.GetFileStorageDir
8267

    
8268
      cfg_storagedir = get_fsd_fn()
8269
      if not cfg_storagedir:
8270
        raise errors.OpPrereqError("Cluster file storage dir not defined")
8271
      joinargs.append(cfg_storagedir)
8272

    
8273
      if self.op.file_storage_dir is not None:
8274
        joinargs.append(self.op.file_storage_dir)
8275

    
8276
      joinargs.append(self.op.instance_name)
8277

    
8278
      # pylint: disable-msg=W0142
8279
      self.instance_file_storage_dir = utils.PathJoin(*joinargs)
8280

    
8281
  def CheckPrereq(self):
8282
    """Check prerequisites.
8283

8284
    """
8285
    self._CalculateFileStorageDir()
8286

    
8287
    if self.op.mode == constants.INSTANCE_IMPORT:
8288
      export_info = self._ReadExportInfo()
8289
      self._ReadExportParams(export_info)
8290

    
8291
    if (not self.cfg.GetVGName() and
8292
        self.op.disk_template not in constants.DTS_NOT_LVM):
8293
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8294
                                 " instances", errors.ECODE_STATE)
8295

    
8296
    if self.op.hypervisor is None:
8297
      self.op.hypervisor = self.cfg.GetHypervisorType()
8298

    
8299
    cluster = self.cfg.GetClusterInfo()
8300
    enabled_hvs = cluster.enabled_hypervisors
8301
    if self.op.hypervisor not in enabled_hvs:
8302
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8303
                                 " cluster (%s)" % (self.op.hypervisor,
8304
                                  ",".join(enabled_hvs)),
8305
                                 errors.ECODE_STATE)
8306

    
8307
    # Check tag validity
8308
    for tag in self.op.tags:
8309
      objects.TaggableObject.ValidateTag(tag)
8310

    
8311
    # check hypervisor parameter syntax (locally)
8312
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8313
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8314
                                      self.op.hvparams)
8315
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8316
    hv_type.CheckParameterSyntax(filled_hvp)
8317
    self.hv_full = filled_hvp
8318
    # check that we don't specify global parameters on an instance
8319
    _CheckGlobalHvParams(self.op.hvparams)
8320

    
8321
    # fill and remember the beparams dict
8322
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8323
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8324

    
8325
    # build os parameters
8326
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8327

    
8328
    # now that hvp/bep are in final format, let's reset to defaults,
8329
    # if told to do so
8330
    if self.op.identify_defaults:
8331
      self._RevertToDefaults(cluster)
8332

    
8333
    # NIC buildup
8334
    self.nics = []
8335
    for idx, nic in enumerate(self.op.nics):
8336
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8337
      nic_mode = nic_mode_req
8338
      if nic_mode is None:
8339
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8340

    
8341
      # in routed mode, for the first nic, the default ip is 'auto'
8342
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8343
        default_ip_mode = constants.VALUE_AUTO
8344
      else:
8345
        default_ip_mode = constants.VALUE_NONE
8346

    
8347
      # ip validity checks
8348
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8349
      if ip is None or ip.lower() == constants.VALUE_NONE:
8350
        nic_ip = None
8351
      elif ip.lower() == constants.VALUE_AUTO:
8352
        if not self.op.name_check:
8353
          raise errors.OpPrereqError("IP address set to auto but name checks"
8354
                                     " have been skipped",
8355
                                     errors.ECODE_INVAL)
8356
        nic_ip = self.hostname1.ip
8357
      else:
8358
        if not netutils.IPAddress.IsValid(ip):
8359
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8360
                                     errors.ECODE_INVAL)
8361
        nic_ip = ip
8362

    
8363
      # TODO: check the ip address for uniqueness
8364
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8365
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8366
                                   errors.ECODE_INVAL)
8367

    
8368
      # MAC address verification
8369
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8370
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8371
        mac = utils.NormalizeAndValidateMac(mac)
8372

    
8373
        try:
8374
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8375
        except errors.ReservationError:
8376
          raise errors.OpPrereqError("MAC address %s already in use"
8377
                                     " in cluster" % mac,
8378
                                     errors.ECODE_NOTUNIQUE)
8379

    
8380
      #  Build nic parameters
8381
      link = nic.get(constants.INIC_LINK, None)
8382
      nicparams = {}
8383
      if nic_mode_req:
8384
        nicparams[constants.NIC_MODE] = nic_mode_req
8385
      if link:
8386
        nicparams[constants.NIC_LINK] = link
8387

    
8388
      check_params = cluster.SimpleFillNIC(nicparams)
8389
      objects.NIC.CheckParameterSyntax(check_params)
8390
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8391

    
8392
    # disk checks/pre-build
8393
    default_vg = self.cfg.GetVGName()
8394
    self.disks = []
8395
    for disk in self.op.disks:
8396
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8397
      if mode not in constants.DISK_ACCESS_SET:
8398
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8399
                                   mode, errors.ECODE_INVAL)
8400
      size = disk.get(constants.IDISK_SIZE, None)
8401
      if size is None:
8402
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8403
      try:
8404
        size = int(size)
8405
      except (TypeError, ValueError):
8406
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8407
                                   errors.ECODE_INVAL)
8408

    
8409
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8410
      new_disk = {
8411
        constants.IDISK_SIZE: size,
8412
        constants.IDISK_MODE: mode,
8413
        constants.IDISK_VG: data_vg,
8414
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8415
        }
8416
      if constants.IDISK_ADOPT in disk:
8417
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8418
      self.disks.append(new_disk)
8419

    
8420
    if self.op.mode == constants.INSTANCE_IMPORT:
8421

    
8422
      # Check that the new instance doesn't have less disks than the export
8423
      instance_disks = len(self.disks)
8424
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8425
      if instance_disks < export_disks:
8426
        raise errors.OpPrereqError("Not enough disks to import."
8427
                                   " (instance: %d, export: %d)" %
8428
                                   (instance_disks, export_disks),
8429
                                   errors.ECODE_INVAL)
8430

    
8431
      disk_images = []
8432
      for idx in range(export_disks):
8433
        option = 'disk%d_dump' % idx
8434
        if export_info.has_option(constants.INISECT_INS, option):
8435
          # FIXME: are the old os-es, disk sizes, etc. useful?
8436
          export_name = export_info.get(constants.INISECT_INS, option)
8437
          image = utils.PathJoin(self.op.src_path, export_name)
8438
          disk_images.append(image)
8439
        else:
8440
          disk_images.append(False)
8441

    
8442
      self.src_images = disk_images
8443

    
8444
      old_name = export_info.get(constants.INISECT_INS, 'name')
8445
      try:
8446
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8447
      except (TypeError, ValueError), err:
8448
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8449
                                   " an integer: %s" % str(err),
8450
                                   errors.ECODE_STATE)
8451
      if self.op.instance_name == old_name:
8452
        for idx, nic in enumerate(self.nics):
8453
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8454
            nic_mac_ini = 'nic%d_mac' % idx
8455
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8456

    
8457
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8458

    
8459
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8460
    if self.op.ip_check:
8461
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8462
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8463
                                   (self.check_ip, self.op.instance_name),
8464
                                   errors.ECODE_NOTUNIQUE)
8465

    
8466
    #### mac address generation
8467
    # By generating here the mac address both the allocator and the hooks get
8468
    # the real final mac address rather than the 'auto' or 'generate' value.
8469
    # There is a race condition between the generation and the instance object
8470
    # creation, which means that we know the mac is valid now, but we're not
8471
    # sure it will be when we actually add the instance. If things go bad
8472
    # adding the instance will abort because of a duplicate mac, and the
8473
    # creation job will fail.
8474
    for nic in self.nics:
8475
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8476
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8477

    
8478
    #### allocator run
8479

    
8480
    if self.op.iallocator is not None:
8481
      self._RunAllocator()
8482

    
8483
    #### node related checks
8484

    
8485
    # check primary node
8486
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8487
    assert self.pnode is not None, \
8488
      "Cannot retrieve locked node %s" % self.op.pnode
8489
    if pnode.offline:
8490
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8491
                                 pnode.name, errors.ECODE_STATE)
8492
    if pnode.drained:
8493
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8494
                                 pnode.name, errors.ECODE_STATE)
8495
    if not pnode.vm_capable:
8496
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8497
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8498

    
8499
    self.secondaries = []
8500

    
8501
    # mirror node verification
8502
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8503
      if self.op.snode == pnode.name:
8504
        raise errors.OpPrereqError("The secondary node cannot be the"
8505
                                   " primary node", errors.ECODE_INVAL)
8506
      _CheckNodeOnline(self, self.op.snode)
8507
      _CheckNodeNotDrained(self, self.op.snode)
8508
      _CheckNodeVmCapable(self, self.op.snode)
8509
      self.secondaries.append(self.op.snode)
8510

    
8511
    nodenames = [pnode.name] + self.secondaries
8512

    
8513
    if not self.adopt_disks:
8514
      # Check lv size requirements, if not adopting
8515
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8516
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8517

    
8518
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8519
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8520
                                disk[constants.IDISK_ADOPT])
8521
                     for disk in self.disks])
8522
      if len(all_lvs) != len(self.disks):
8523
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8524
                                   errors.ECODE_INVAL)
8525
      for lv_name in all_lvs:
8526
        try:
8527
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8528
          # to ReserveLV uses the same syntax
8529
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8530
        except errors.ReservationError:
8531
          raise errors.OpPrereqError("LV named %s used by another instance" %
8532
                                     lv_name, errors.ECODE_NOTUNIQUE)
8533

    
8534
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8535
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8536

    
8537
      node_lvs = self.rpc.call_lv_list([pnode.name],
8538
                                       vg_names.payload.keys())[pnode.name]
8539
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8540
      node_lvs = node_lvs.payload
8541

    
8542
      delta = all_lvs.difference(node_lvs.keys())
8543
      if delta:
8544
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8545
                                   utils.CommaJoin(delta),
8546
                                   errors.ECODE_INVAL)
8547
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8548
      if online_lvs:
8549
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8550
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8551
                                   errors.ECODE_STATE)
8552
      # update the size of disk based on what is found
8553
      for dsk in self.disks:
8554
        dsk[constants.IDISK_SIZE] = \
8555
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8556
                                        dsk[constants.IDISK_ADOPT])][0]))
8557

    
8558
    elif self.op.disk_template == constants.DT_BLOCK:
8559
      # Normalize and de-duplicate device paths
8560
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8561
                       for disk in self.disks])
8562
      if len(all_disks) != len(self.disks):
8563
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8564
                                   errors.ECODE_INVAL)
8565
      baddisks = [d for d in all_disks
8566
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8567
      if baddisks:
8568
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8569
                                   " cannot be adopted" %
8570
                                   (", ".join(baddisks),
8571
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8572
                                   errors.ECODE_INVAL)
8573

    
8574
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8575
                                            list(all_disks))[pnode.name]
8576
      node_disks.Raise("Cannot get block device information from node %s" %
8577
                       pnode.name)
8578
      node_disks = node_disks.payload
8579
      delta = all_disks.difference(node_disks.keys())
8580
      if delta:
8581
        raise errors.OpPrereqError("Missing block device(s): %s" %
8582
                                   utils.CommaJoin(delta),
8583
                                   errors.ECODE_INVAL)
8584
      for dsk in self.disks:
8585
        dsk[constants.IDISK_SIZE] = \
8586
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8587

    
8588
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8589

    
8590
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8591
    # check OS parameters (remotely)
8592
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8593

    
8594
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8595

    
8596
    # memory check on primary node
8597
    if self.op.start:
8598
      _CheckNodeFreeMemory(self, self.pnode.name,
8599
                           "creating instance %s" % self.op.instance_name,
8600
                           self.be_full[constants.BE_MEMORY],
8601
                           self.op.hypervisor)
8602

    
8603
    self.dry_run_result = list(nodenames)
8604

    
8605
  def Exec(self, feedback_fn):
8606
    """Create and add the instance to the cluster.
8607

8608
    """
8609
    instance = self.op.instance_name
8610
    pnode_name = self.pnode.name
8611

    
8612
    ht_kind = self.op.hypervisor
8613
    if ht_kind in constants.HTS_REQ_PORT:
8614
      network_port = self.cfg.AllocatePort()
8615
    else:
8616
      network_port = None
8617

    
8618
    disks = _GenerateDiskTemplate(self,
8619
                                  self.op.disk_template,
8620
                                  instance, pnode_name,
8621
                                  self.secondaries,
8622
                                  self.disks,
8623
                                  self.instance_file_storage_dir,
8624
                                  self.op.file_driver,
8625
                                  0,
8626
                                  feedback_fn)
8627

    
8628
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8629
                            primary_node=pnode_name,
8630
                            nics=self.nics, disks=disks,
8631
                            disk_template=self.op.disk_template,
8632
                            admin_up=False,
8633
                            network_port=network_port,
8634
                            beparams=self.op.beparams,
8635
                            hvparams=self.op.hvparams,
8636
                            hypervisor=self.op.hypervisor,
8637
                            osparams=self.op.osparams,
8638
                            )
8639

    
8640
    if self.op.tags:
8641
      for tag in self.op.tags:
8642
        iobj.AddTag(tag)
8643

    
8644
    if self.adopt_disks:
8645
      if self.op.disk_template == constants.DT_PLAIN:
8646
        # rename LVs to the newly-generated names; we need to construct
8647
        # 'fake' LV disks with the old data, plus the new unique_id
8648
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8649
        rename_to = []
8650
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8651
          rename_to.append(t_dsk.logical_id)
8652
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8653
          self.cfg.SetDiskID(t_dsk, pnode_name)
8654
        result = self.rpc.call_blockdev_rename(pnode_name,
8655
                                               zip(tmp_disks, rename_to))
8656
        result.Raise("Failed to rename adoped LVs")
8657
    else:
8658
      feedback_fn("* creating instance disks...")
8659
      try:
8660
        _CreateDisks(self, iobj)
8661
      except errors.OpExecError:
8662
        self.LogWarning("Device creation failed, reverting...")
8663
        try:
8664
          _RemoveDisks(self, iobj)
8665
        finally:
8666
          self.cfg.ReleaseDRBDMinors(instance)
8667
          raise
8668

    
8669
    feedback_fn("adding instance %s to cluster config" % instance)
8670

    
8671
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8672

    
8673
    # Declare that we don't want to remove the instance lock anymore, as we've
8674
    # added the instance to the config
8675
    del self.remove_locks[locking.LEVEL_INSTANCE]
8676

    
8677
    if self.op.mode == constants.INSTANCE_IMPORT:
8678
      # Release unused nodes
8679
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8680
    else:
8681
      # Release all nodes
8682
      _ReleaseLocks(self, locking.LEVEL_NODE)
8683

    
8684
    disk_abort = False
8685
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8686
      feedback_fn("* wiping instance disks...")
8687
      try:
8688
        _WipeDisks(self, iobj)
8689
      except errors.OpExecError, err:
8690
        logging.exception("Wiping disks failed")
8691
        self.LogWarning("Wiping instance disks failed (%s)", err)
8692
        disk_abort = True
8693

    
8694
    if disk_abort:
8695
      # Something is already wrong with the disks, don't do anything else
8696
      pass
8697
    elif self.op.wait_for_sync:
8698
      disk_abort = not _WaitForSync(self, iobj)
8699
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8700
      # make sure the disks are not degraded (still sync-ing is ok)
8701
      time.sleep(15)
8702
      feedback_fn("* checking mirrors status")
8703
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8704
    else:
8705
      disk_abort = False
8706

    
8707
    if disk_abort:
8708
      _RemoveDisks(self, iobj)
8709
      self.cfg.RemoveInstance(iobj.name)
8710
      # Make sure the instance lock gets removed
8711
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8712
      raise errors.OpExecError("There are some degraded disks for"
8713
                               " this instance")
8714

    
8715
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8716
      if self.op.mode == constants.INSTANCE_CREATE:
8717
        if not self.op.no_install:
8718
          feedback_fn("* running the instance OS create scripts...")
8719
          # FIXME: pass debug option from opcode to backend
8720
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8721
                                                 self.op.debug_level)
8722
          result.Raise("Could not add os for instance %s"
8723
                       " on node %s" % (instance, pnode_name))
8724

    
8725
      elif self.op.mode == constants.INSTANCE_IMPORT:
8726
        feedback_fn("* running the instance OS import scripts...")
8727

    
8728
        transfers = []
8729

    
8730
        for idx, image in enumerate(self.src_images):
8731
          if not image:
8732
            continue
8733

    
8734
          # FIXME: pass debug option from opcode to backend
8735
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8736
                                             constants.IEIO_FILE, (image, ),
8737
                                             constants.IEIO_SCRIPT,
8738
                                             (iobj.disks[idx], idx),
8739
                                             None)
8740
          transfers.append(dt)
8741

    
8742
        import_result = \
8743
          masterd.instance.TransferInstanceData(self, feedback_fn,
8744
                                                self.op.src_node, pnode_name,
8745
                                                self.pnode.secondary_ip,
8746
                                                iobj, transfers)
8747
        if not compat.all(import_result):
8748
          self.LogWarning("Some disks for instance %s on node %s were not"
8749
                          " imported successfully" % (instance, pnode_name))
8750

    
8751
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8752
        feedback_fn("* preparing remote import...")
8753
        # The source cluster will stop the instance before attempting to make a
8754
        # connection. In some cases stopping an instance can take a long time,
8755
        # hence the shutdown timeout is added to the connection timeout.
8756
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8757
                           self.op.source_shutdown_timeout)
8758
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8759

    
8760
        assert iobj.primary_node == self.pnode.name
8761
        disk_results = \
8762
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8763
                                        self.source_x509_ca,
8764
                                        self._cds, timeouts)
8765
        if not compat.all(disk_results):
8766
          # TODO: Should the instance still be started, even if some disks
8767
          # failed to import (valid for local imports, too)?
8768
          self.LogWarning("Some disks for instance %s on node %s were not"
8769
                          " imported successfully" % (instance, pnode_name))
8770

    
8771
        # Run rename script on newly imported instance
8772
        assert iobj.name == instance
8773
        feedback_fn("Running rename script for %s" % instance)
8774
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8775
                                                   self.source_instance_name,
8776
                                                   self.op.debug_level)
8777
        if result.fail_msg:
8778
          self.LogWarning("Failed to run rename script for %s on node"
8779
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8780

    
8781
      else:
8782
        # also checked in the prereq part
8783
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8784
                                     % self.op.mode)
8785

    
8786
    if self.op.start:
8787
      iobj.admin_up = True
8788
      self.cfg.Update(iobj, feedback_fn)
8789
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8790
      feedback_fn("* starting instance...")
8791
      result = self.rpc.call_instance_start(pnode_name, iobj,
8792
                                            None, None, False)
8793
      result.Raise("Could not start instance")
8794

    
8795
    return list(iobj.all_nodes)
8796

    
8797

    
8798
class LUInstanceConsole(NoHooksLU):
8799
  """Connect to an instance's console.
8800

8801
  This is somewhat special in that it returns the command line that
8802
  you need to run on the master node in order to connect to the
8803
  console.
8804

8805
  """
8806
  REQ_BGL = False
8807

    
8808
  def ExpandNames(self):
8809
    self._ExpandAndLockInstance()
8810

    
8811
  def CheckPrereq(self):
8812
    """Check prerequisites.
8813

8814
    This checks that the instance is in the cluster.
8815

8816
    """
8817
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8818
    assert self.instance is not None, \
8819
      "Cannot retrieve locked instance %s" % self.op.instance_name
8820
    _CheckNodeOnline(self, self.instance.primary_node)
8821

    
8822
  def Exec(self, feedback_fn):
8823
    """Connect to the console of an instance
8824

8825
    """
8826
    instance = self.instance
8827
    node = instance.primary_node
8828

    
8829
    node_insts = self.rpc.call_instance_list([node],
8830
                                             [instance.hypervisor])[node]
8831
    node_insts.Raise("Can't get node information from %s" % node)
8832

    
8833
    if instance.name not in node_insts.payload:
8834
      if instance.admin_up:
8835
        state = constants.INSTST_ERRORDOWN
8836
      else:
8837
        state = constants.INSTST_ADMINDOWN
8838
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8839
                               (instance.name, state))
8840

    
8841
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8842

    
8843
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8844

    
8845

    
8846
def _GetInstanceConsole(cluster, instance):
8847
  """Returns console information for an instance.
8848

8849
  @type cluster: L{objects.Cluster}
8850
  @type instance: L{objects.Instance}
8851
  @rtype: dict
8852

8853
  """
8854
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8855
  # beparams and hvparams are passed separately, to avoid editing the
8856
  # instance and then saving the defaults in the instance itself.
8857
  hvparams = cluster.FillHV(instance)
8858
  beparams = cluster.FillBE(instance)
8859
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8860

    
8861
  assert console.instance == instance.name
8862
  assert console.Validate()
8863

    
8864
  return console.ToDict()
8865

    
8866

    
8867
class LUInstanceReplaceDisks(LogicalUnit):
8868
  """Replace the disks of an instance.
8869

8870
  """
8871
  HPATH = "mirrors-replace"
8872
  HTYPE = constants.HTYPE_INSTANCE
8873
  REQ_BGL = False
8874

    
8875
  def CheckArguments(self):
8876
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8877
                                  self.op.iallocator)
8878

    
8879
  def ExpandNames(self):
8880
    self._ExpandAndLockInstance()
8881

    
8882
    assert locking.LEVEL_NODE not in self.needed_locks
8883
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8884

    
8885
    assert self.op.iallocator is None or self.op.remote_node is None, \
8886
      "Conflicting options"
8887

    
8888
    if self.op.remote_node is not None:
8889
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8890

    
8891
      # Warning: do not remove the locking of the new secondary here
8892
      # unless DRBD8.AddChildren is changed to work in parallel;
8893
      # currently it doesn't since parallel invocations of
8894
      # FindUnusedMinor will conflict
8895
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8896
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8897
    else:
8898
      self.needed_locks[locking.LEVEL_NODE] = []
8899
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8900

    
8901
      if self.op.iallocator is not None:
8902
        # iallocator will select a new node in the same group
8903
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8904

    
8905
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8906
                                   self.op.iallocator, self.op.remote_node,
8907
                                   self.op.disks, False, self.op.early_release)
8908

    
8909
    self.tasklets = [self.replacer]
8910

    
8911
  def DeclareLocks(self, level):
8912
    if level == locking.LEVEL_NODEGROUP:
8913
      assert self.op.remote_node is None
8914
      assert self.op.iallocator is not None
8915
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8916

    
8917
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8918
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8919
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8920

    
8921
    elif level == locking.LEVEL_NODE:
8922
      if self.op.iallocator is not None:
8923
        assert self.op.remote_node is None
8924
        assert not self.needed_locks[locking.LEVEL_NODE]
8925

    
8926
        # Lock member nodes of all locked groups
8927
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8928
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8929
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8930
      else:
8931
        self._LockInstancesNodes()
8932

    
8933
  def BuildHooksEnv(self):
8934
    """Build hooks env.
8935

8936
    This runs on the master, the primary and all the secondaries.
8937

8938
    """
8939
    instance = self.replacer.instance
8940
    env = {
8941
      "MODE": self.op.mode,
8942
      "NEW_SECONDARY": self.op.remote_node,
8943
      "OLD_SECONDARY": instance.secondary_nodes[0],
8944
      }
8945
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8946
    return env
8947

    
8948
  def BuildHooksNodes(self):
8949
    """Build hooks nodes.
8950

8951
    """
8952
    instance = self.replacer.instance
8953
    nl = [
8954
      self.cfg.GetMasterNode(),
8955
      instance.primary_node,
8956
      ]
8957
    if self.op.remote_node is not None:
8958
      nl.append(self.op.remote_node)
8959
    return nl, nl
8960

    
8961
  def CheckPrereq(self):
8962
    """Check prerequisites.
8963

8964
    """
8965
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8966
            self.op.iallocator is None)
8967

    
8968
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8969
    if owned_groups:
8970
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8971
      if owned_groups != groups:
8972
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8973
                                 " since lock was acquired, current list is %r,"
8974
                                 " used to be '%s'" %
8975
                                 (self.op.instance_name,
8976
                                  utils.CommaJoin(groups),
8977
                                  utils.CommaJoin(owned_groups)))
8978

    
8979
    return LogicalUnit.CheckPrereq(self)
8980

    
8981

    
8982
class TLReplaceDisks(Tasklet):
8983
  """Replaces disks for an instance.
8984

8985
  Note: Locking is not within the scope of this class.
8986

8987
  """
8988
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8989
               disks, delay_iallocator, early_release):
8990
    """Initializes this class.
8991

8992
    """
8993
    Tasklet.__init__(self, lu)
8994

    
8995
    # Parameters
8996
    self.instance_name = instance_name
8997
    self.mode = mode
8998
    self.iallocator_name = iallocator_name
8999
    self.remote_node = remote_node
9000
    self.disks = disks
9001
    self.delay_iallocator = delay_iallocator
9002
    self.early_release = early_release
9003

    
9004
    # Runtime data
9005
    self.instance = None
9006
    self.new_node = None
9007
    self.target_node = None
9008
    self.other_node = None
9009
    self.remote_node_info = None
9010
    self.node_secondary_ip = None
9011

    
9012
  @staticmethod
9013
  def CheckArguments(mode, remote_node, iallocator):
9014
    """Helper function for users of this class.
9015

9016
    """
9017
    # check for valid parameter combination
9018
    if mode == constants.REPLACE_DISK_CHG:
9019
      if remote_node is None and iallocator is None:
9020
        raise errors.OpPrereqError("When changing the secondary either an"
9021
                                   " iallocator script must be used or the"
9022
                                   " new node given", errors.ECODE_INVAL)
9023

    
9024
      if remote_node is not None and iallocator is not None:
9025
        raise errors.OpPrereqError("Give either the iallocator or the new"
9026
                                   " secondary, not both", errors.ECODE_INVAL)
9027

    
9028
    elif remote_node is not None or iallocator is not None:
9029
      # Not replacing the secondary
9030
      raise errors.OpPrereqError("The iallocator and new node options can"
9031
                                 " only be used when changing the"
9032
                                 " secondary node", errors.ECODE_INVAL)
9033

    
9034
  @staticmethod
9035
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
9036
    """Compute a new secondary node using an IAllocator.
9037

9038
    """
9039
    ial = IAllocator(lu.cfg, lu.rpc,
9040
                     mode=constants.IALLOCATOR_MODE_RELOC,
9041
                     name=instance_name,
9042
                     relocate_from=relocate_from)
9043

    
9044
    ial.Run(iallocator_name)
9045

    
9046
    if not ial.success:
9047
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
9048
                                 " %s" % (iallocator_name, ial.info),
9049
                                 errors.ECODE_NORES)
9050

    
9051
    if len(ial.result) != ial.required_nodes:
9052
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
9053
                                 " of nodes (%s), required %s" %
9054
                                 (iallocator_name,
9055
                                  len(ial.result), ial.required_nodes),
9056
                                 errors.ECODE_FAULT)
9057

    
9058
    remote_node_name = ial.result[0]
9059

    
9060
    lu.LogInfo("Selected new secondary for instance '%s': %s",
9061
               instance_name, remote_node_name)
9062

    
9063
    return remote_node_name
9064

    
9065
  def _FindFaultyDisks(self, node_name):
9066
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
9067
                                    node_name, True)
9068

    
9069
  def _CheckDisksActivated(self, instance):
9070
    """Checks if the instance disks are activated.
9071

9072
    @param instance: The instance to check disks
9073
    @return: True if they are activated, False otherwise
9074

9075
    """
9076
    nodes = instance.all_nodes
9077

    
9078
    for idx, dev in enumerate(instance.disks):
9079
      for node in nodes:
9080
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
9081
        self.cfg.SetDiskID(dev, node)
9082

    
9083
        result = self.rpc.call_blockdev_find(node, dev)
9084

    
9085
        if result.offline:
9086
          continue
9087
        elif result.fail_msg or not result.payload:
9088
          return False
9089

    
9090
    return True
9091

    
9092
  def CheckPrereq(self):
9093
    """Check prerequisites.
9094

9095
    This checks that the instance is in the cluster.
9096

9097
    """
9098
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
9099
    assert instance is not None, \
9100
      "Cannot retrieve locked instance %s" % self.instance_name
9101

    
9102
    if instance.disk_template != constants.DT_DRBD8:
9103
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
9104
                                 " instances", errors.ECODE_INVAL)
9105

    
9106
    if len(instance.secondary_nodes) != 1:
9107
      raise errors.OpPrereqError("The instance has a strange layout,"
9108
                                 " expected one secondary but found %d" %
9109
                                 len(instance.secondary_nodes),
9110
                                 errors.ECODE_FAULT)
9111

    
9112
    if not self.delay_iallocator:
9113
      self._CheckPrereq2()
9114

    
9115
  def _CheckPrereq2(self):
9116
    """Check prerequisites, second part.
9117

9118
    This function should always be part of CheckPrereq. It was separated and is
9119
    now called from Exec because during node evacuation iallocator was only
9120
    called with an unmodified cluster model, not taking planned changes into
9121
    account.
9122

9123
    """
9124
    instance = self.instance
9125
    secondary_node = instance.secondary_nodes[0]
9126

    
9127
    if self.iallocator_name is None:
9128
      remote_node = self.remote_node
9129
    else:
9130
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
9131
                                       instance.name, instance.secondary_nodes)
9132

    
9133
    if remote_node is None:
9134
      self.remote_node_info = None
9135
    else:
9136
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
9137
             "Remote node '%s' is not locked" % remote_node
9138

    
9139
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
9140
      assert self.remote_node_info is not None, \
9141
        "Cannot retrieve locked node %s" % remote_node
9142

    
9143
    if remote_node == self.instance.primary_node:
9144
      raise errors.OpPrereqError("The specified node is the primary node of"
9145
                                 " the instance", errors.ECODE_INVAL)
9146

    
9147
    if remote_node == secondary_node:
9148
      raise errors.OpPrereqError("The specified node is already the"
9149
                                 " secondary node of the instance",
9150
                                 errors.ECODE_INVAL)
9151

    
9152
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
9153
                                    constants.REPLACE_DISK_CHG):
9154
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
9155
                                 errors.ECODE_INVAL)
9156

    
9157
    if self.mode == constants.REPLACE_DISK_AUTO:
9158
      if not self._CheckDisksActivated(instance):
9159
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
9160
                                   " first" % self.instance_name,
9161
                                   errors.ECODE_STATE)
9162
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
9163
      faulty_secondary = self._FindFaultyDisks(secondary_node)
9164

    
9165
      if faulty_primary and faulty_secondary:
9166
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
9167
                                   " one node and can not be repaired"
9168
                                   " automatically" % self.instance_name,
9169
                                   errors.ECODE_STATE)
9170

    
9171
      if faulty_primary:
9172
        self.disks = faulty_primary
9173
        self.target_node = instance.primary_node
9174
        self.other_node = secondary_node
9175
        check_nodes = [self.target_node, self.other_node]
9176
      elif faulty_secondary:
9177
        self.disks = faulty_secondary
9178
        self.target_node = secondary_node
9179
        self.other_node = instance.primary_node
9180
        check_nodes = [self.target_node, self.other_node]
9181
      else:
9182
        self.disks = []
9183
        check_nodes = []
9184

    
9185
    else:
9186
      # Non-automatic modes
9187
      if self.mode == constants.REPLACE_DISK_PRI:
9188
        self.target_node = instance.primary_node
9189
        self.other_node = secondary_node
9190
        check_nodes = [self.target_node, self.other_node]
9191

    
9192
      elif self.mode == constants.REPLACE_DISK_SEC:
9193
        self.target_node = secondary_node
9194
        self.other_node = instance.primary_node
9195
        check_nodes = [self.target_node, self.other_node]
9196

    
9197
      elif self.mode == constants.REPLACE_DISK_CHG:
9198
        self.new_node = remote_node
9199
        self.other_node = instance.primary_node
9200
        self.target_node = secondary_node
9201
        check_nodes = [self.new_node, self.other_node]
9202

    
9203
        _CheckNodeNotDrained(self.lu, remote_node)
9204
        _CheckNodeVmCapable(self.lu, remote_node)
9205

    
9206
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
9207
        assert old_node_info is not None
9208
        if old_node_info.offline and not self.early_release:
9209
          # doesn't make sense to delay the release
9210
          self.early_release = True
9211
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
9212
                          " early-release mode", secondary_node)
9213

    
9214
      else:
9215
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
9216
                                     self.mode)
9217

    
9218
      # If not specified all disks should be replaced
9219
      if not self.disks:
9220
        self.disks = range(len(self.instance.disks))
9221

    
9222
    for node in check_nodes:
9223
      _CheckNodeOnline(self.lu, node)
9224

    
9225
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
9226
                                                          self.other_node,
9227
                                                          self.target_node]
9228
                              if node_name is not None)
9229

    
9230
    # Release unneeded node locks
9231
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
9232

    
9233
    # Release any owned node group
9234
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
9235
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
9236

    
9237
    # Check whether disks are valid
9238
    for disk_idx in self.disks:
9239
      instance.FindDisk(disk_idx)
9240

    
9241
    # Get secondary node IP addresses
9242
    self.node_secondary_ip = \
9243
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
9244
           for node_name in touched_nodes)
9245

    
9246
  def Exec(self, feedback_fn):
9247
    """Execute disk replacement.
9248

9249
    This dispatches the disk replacement to the appropriate handler.
9250

9251
    """
9252
    if self.delay_iallocator:
9253
      self._CheckPrereq2()
9254

    
9255
    if __debug__:
9256
      # Verify owned locks before starting operation
9257
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9258
      assert set(owned_locks) == set(self.node_secondary_ip), \
9259
          ("Incorrect node locks, owning %s, expected %s" %
9260
           (owned_locks, self.node_secondary_ip.keys()))
9261

    
9262
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9263
      assert list(owned_locks) == [self.instance_name], \
9264
          "Instance '%s' not locked" % self.instance_name
9265

    
9266
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9267
          "Should not own any node group lock at this point"
9268

    
9269
    if not self.disks:
9270
      feedback_fn("No disks need replacement")
9271
      return
9272

    
9273
    feedback_fn("Replacing disk(s) %s for %s" %
9274
                (utils.CommaJoin(self.disks), self.instance.name))
9275

    
9276
    activate_disks = (not self.instance.admin_up)
9277

    
9278
    # Activate the instance disks if we're replacing them on a down instance
9279
    if activate_disks:
9280
      _StartInstanceDisks(self.lu, self.instance, True)
9281

    
9282
    try:
9283
      # Should we replace the secondary node?
9284
      if self.new_node is not None:
9285
        fn = self._ExecDrbd8Secondary
9286
      else:
9287
        fn = self._ExecDrbd8DiskOnly
9288

    
9289
      result = fn(feedback_fn)
9290
    finally:
9291
      # Deactivate the instance disks if we're replacing them on a
9292
      # down instance
9293
      if activate_disks:
9294
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9295

    
9296
    if __debug__:
9297
      # Verify owned locks
9298
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9299
      nodes = frozenset(self.node_secondary_ip)
9300
      assert ((self.early_release and not owned_locks) or
9301
              (not self.early_release and not (set(owned_locks) - nodes))), \
9302
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9303
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9304

    
9305
    return result
9306

    
9307
  def _CheckVolumeGroup(self, nodes):
9308
    self.lu.LogInfo("Checking volume groups")
9309

    
9310
    vgname = self.cfg.GetVGName()
9311

    
9312
    # Make sure volume group exists on all involved nodes
9313
    results = self.rpc.call_vg_list(nodes)
9314
    if not results:
9315
      raise errors.OpExecError("Can't list volume groups on the nodes")
9316

    
9317
    for node in nodes:
9318
      res = results[node]
9319
      res.Raise("Error checking node %s" % node)
9320
      if vgname not in res.payload:
9321
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9322
                                 (vgname, node))
9323

    
9324
  def _CheckDisksExistence(self, nodes):
9325
    # Check disk existence
9326
    for idx, dev in enumerate(self.instance.disks):
9327
      if idx not in self.disks:
9328
        continue
9329

    
9330
      for node in nodes:
9331
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9332
        self.cfg.SetDiskID(dev, node)
9333

    
9334
        result = self.rpc.call_blockdev_find(node, dev)
9335

    
9336
        msg = result.fail_msg
9337
        if msg or not result.payload:
9338
          if not msg:
9339
            msg = "disk not found"
9340
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9341
                                   (idx, node, msg))
9342

    
9343
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9344
    for idx, dev in enumerate(self.instance.disks):
9345
      if idx not in self.disks:
9346
        continue
9347

    
9348
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9349
                      (idx, node_name))
9350

    
9351
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9352
                                   ldisk=ldisk):
9353
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9354
                                 " replace disks for instance %s" %
9355
                                 (node_name, self.instance.name))
9356

    
9357
  def _CreateNewStorage(self, node_name):
9358
    """Create new storage on the primary or secondary node.
9359

9360
    This is only used for same-node replaces, not for changing the
9361
    secondary node, hence we don't want to modify the existing disk.
9362

9363
    """
9364
    iv_names = {}
9365

    
9366
    for idx, dev in enumerate(self.instance.disks):
9367
      if idx not in self.disks:
9368
        continue
9369

    
9370
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9371

    
9372
      self.cfg.SetDiskID(dev, node_name)
9373

    
9374
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9375
      names = _GenerateUniqueNames(self.lu, lv_names)
9376

    
9377
      vg_data = dev.children[0].logical_id[0]
9378
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9379
                             logical_id=(vg_data, names[0]))
9380
      vg_meta = dev.children[1].logical_id[0]
9381
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9382
                             logical_id=(vg_meta, names[1]))
9383

    
9384
      new_lvs = [lv_data, lv_meta]
9385
      old_lvs = [child.Copy() for child in dev.children]
9386
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9387

    
9388
      # we pass force_create=True to force the LVM creation
9389
      for new_lv in new_lvs:
9390
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9391
                        _GetInstanceInfoText(self.instance), False)
9392

    
9393
    return iv_names
9394

    
9395
  def _CheckDevices(self, node_name, iv_names):
9396
    for name, (dev, _, _) in iv_names.iteritems():
9397
      self.cfg.SetDiskID(dev, node_name)
9398

    
9399
      result = self.rpc.call_blockdev_find(node_name, dev)
9400

    
9401
      msg = result.fail_msg
9402
      if msg or not result.payload:
9403
        if not msg:
9404
          msg = "disk not found"
9405
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9406
                                 (name, msg))
9407

    
9408
      if result.payload.is_degraded:
9409
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9410

    
9411
  def _RemoveOldStorage(self, node_name, iv_names):
9412
    for name, (_, old_lvs, _) in iv_names.iteritems():
9413
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9414

    
9415
      for lv in old_lvs:
9416
        self.cfg.SetDiskID(lv, node_name)
9417

    
9418
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9419
        if msg:
9420
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9421
                             hint="remove unused LVs manually")
9422

    
9423
  def _ExecDrbd8DiskOnly(self, feedback_fn): # pylint: disable-msg=W0613
9424
    """Replace a disk on the primary or secondary for DRBD 8.
9425

9426
    The algorithm for replace is quite complicated:
9427

9428
      1. for each disk to be replaced:
9429

9430
        1. create new LVs on the target node with unique names
9431
        1. detach old LVs from the drbd device
9432
        1. rename old LVs to name_replaced.<time_t>
9433
        1. rename new LVs to old LVs
9434
        1. attach the new LVs (with the old names now) to the drbd device
9435

9436
      1. wait for sync across all devices
9437

9438
      1. for each modified disk:
9439

9440
        1. remove old LVs (which have the name name_replaces.<time_t>)
9441

9442
    Failures are not very well handled.
9443

9444
    """
9445
    steps_total = 6
9446

    
9447
    # Step: check device activation
9448
    self.lu.LogStep(1, steps_total, "Check device existence")
9449
    self._CheckDisksExistence([self.other_node, self.target_node])
9450
    self._CheckVolumeGroup([self.target_node, self.other_node])
9451

    
9452
    # Step: check other node consistency
9453
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9454
    self._CheckDisksConsistency(self.other_node,
9455
                                self.other_node == self.instance.primary_node,
9456
                                False)
9457

    
9458
    # Step: create new storage
9459
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9460
    iv_names = self._CreateNewStorage(self.target_node)
9461

    
9462
    # Step: for each lv, detach+rename*2+attach
9463
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9464
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9465
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9466

    
9467
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9468
                                                     old_lvs)
9469
      result.Raise("Can't detach drbd from local storage on node"
9470
                   " %s for device %s" % (self.target_node, dev.iv_name))
9471
      #dev.children = []
9472
      #cfg.Update(instance)
9473

    
9474
      # ok, we created the new LVs, so now we know we have the needed
9475
      # storage; as such, we proceed on the target node to rename
9476
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9477
      # using the assumption that logical_id == physical_id (which in
9478
      # turn is the unique_id on that node)
9479

    
9480
      # FIXME(iustin): use a better name for the replaced LVs
9481
      temp_suffix = int(time.time())
9482
      ren_fn = lambda d, suff: (d.physical_id[0],
9483
                                d.physical_id[1] + "_replaced-%s" % suff)
9484

    
9485
      # Build the rename list based on what LVs exist on the node
9486
      rename_old_to_new = []
9487
      for to_ren in old_lvs:
9488
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9489
        if not result.fail_msg and result.payload:
9490
          # device exists
9491
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9492

    
9493
      self.lu.LogInfo("Renaming the old LVs on the target node")
9494
      result = self.rpc.call_blockdev_rename(self.target_node,
9495
                                             rename_old_to_new)
9496
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9497

    
9498
      # Now we rename the new LVs to the old LVs
9499
      self.lu.LogInfo("Renaming the new LVs on the target node")
9500
      rename_new_to_old = [(new, old.physical_id)
9501
                           for old, new in zip(old_lvs, new_lvs)]
9502
      result = self.rpc.call_blockdev_rename(self.target_node,
9503
                                             rename_new_to_old)
9504
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9505

    
9506
      # Intermediate steps of in memory modifications
9507
      for old, new in zip(old_lvs, new_lvs):
9508
        new.logical_id = old.logical_id
9509
        self.cfg.SetDiskID(new, self.target_node)
9510

    
9511
      # We need to modify old_lvs so that removal later removes the
9512
      # right LVs, not the newly added ones; note that old_lvs is a
9513
      # copy here
9514
      for disk in old_lvs:
9515
        disk.logical_id = ren_fn(disk, temp_suffix)
9516
        self.cfg.SetDiskID(disk, self.target_node)
9517

    
9518
      # Now that the new lvs have the old name, we can add them to the device
9519
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9520
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9521
                                                  new_lvs)
9522
      msg = result.fail_msg
9523
      if msg:
9524
        for new_lv in new_lvs:
9525
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9526
                                               new_lv).fail_msg
9527
          if msg2:
9528
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9529
                               hint=("cleanup manually the unused logical"
9530
                                     "volumes"))
9531
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9532

    
9533
    cstep = 5
9534
    if self.early_release:
9535
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9536
      cstep += 1
9537
      self._RemoveOldStorage(self.target_node, iv_names)
9538
      # WARNING: we release both node locks here, do not do other RPCs
9539
      # than WaitForSync to the primary node
9540
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9541
                    names=[self.target_node, self.other_node])
9542

    
9543
    # Wait for sync
9544
    # This can fail as the old devices are degraded and _WaitForSync
9545
    # does a combined result over all disks, so we don't check its return value
9546
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9547
    cstep += 1
9548
    _WaitForSync(self.lu, self.instance)
9549

    
9550
    # Check all devices manually
9551
    self._CheckDevices(self.instance.primary_node, iv_names)
9552

    
9553
    # Step: remove old storage
9554
    if not self.early_release:
9555
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9556
      cstep += 1
9557
      self._RemoveOldStorage(self.target_node, iv_names)
9558

    
9559
  def _ExecDrbd8Secondary(self, feedback_fn):
9560
    """Replace the secondary node for DRBD 8.
9561

9562
    The algorithm for replace is quite complicated:
9563
      - for all disks of the instance:
9564
        - create new LVs on the new node with same names
9565
        - shutdown the drbd device on the old secondary
9566
        - disconnect the drbd network on the primary
9567
        - create the drbd device on the new secondary
9568
        - network attach the drbd on the primary, using an artifice:
9569
          the drbd code for Attach() will connect to the network if it
9570
          finds a device which is connected to the good local disks but
9571
          not network enabled
9572
      - wait for sync across all devices
9573
      - remove all disks from the old secondary
9574

9575
    Failures are not very well handled.
9576

9577
    """
9578
    steps_total = 6
9579

    
9580
    # Step: check device activation
9581
    self.lu.LogStep(1, steps_total, "Check device existence")
9582
    self._CheckDisksExistence([self.instance.primary_node])
9583
    self._CheckVolumeGroup([self.instance.primary_node])
9584

    
9585
    # Step: check other node consistency
9586
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9587
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9588

    
9589
    # Step: create new storage
9590
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9591
    for idx, dev in enumerate(self.instance.disks):
9592
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9593
                      (self.new_node, idx))
9594
      # we pass force_create=True to force LVM creation
9595
      for new_lv in dev.children:
9596
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9597
                        _GetInstanceInfoText(self.instance), False)
9598

    
9599
    # Step 4: dbrd minors and drbd setups changes
9600
    # after this, we must manually remove the drbd minors on both the
9601
    # error and the success paths
9602
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9603
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9604
                                         for dev in self.instance.disks],
9605
                                        self.instance.name)
9606
    logging.debug("Allocated minors %r", minors)
9607

    
9608
    iv_names = {}
9609
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9610
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9611
                      (self.new_node, idx))
9612
      # create new devices on new_node; note that we create two IDs:
9613
      # one without port, so the drbd will be activated without
9614
      # networking information on the new node at this stage, and one
9615
      # with network, for the latter activation in step 4
9616
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9617
      if self.instance.primary_node == o_node1:
9618
        p_minor = o_minor1
9619
      else:
9620
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9621
        p_minor = o_minor2
9622

    
9623
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9624
                      p_minor, new_minor, o_secret)
9625
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9626
                    p_minor, new_minor, o_secret)
9627

    
9628
      iv_names[idx] = (dev, dev.children, new_net_id)
9629
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9630
                    new_net_id)
9631
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9632
                              logical_id=new_alone_id,
9633
                              children=dev.children,
9634
                              size=dev.size)
9635
      try:
9636
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9637
                              _GetInstanceInfoText(self.instance), False)
9638
      except errors.GenericError:
9639
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9640
        raise
9641

    
9642
    # We have new devices, shutdown the drbd on the old secondary
9643
    for idx, dev in enumerate(self.instance.disks):
9644
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9645
      self.cfg.SetDiskID(dev, self.target_node)
9646
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9647
      if msg:
9648
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9649
                           "node: %s" % (idx, msg),
9650
                           hint=("Please cleanup this device manually as"
9651
                                 " soon as possible"))
9652

    
9653
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9654
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9655
                                               self.node_secondary_ip,
9656
                                               self.instance.disks)\
9657
                                              [self.instance.primary_node]
9658

    
9659
    msg = result.fail_msg
9660
    if msg:
9661
      # detaches didn't succeed (unlikely)
9662
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9663
      raise errors.OpExecError("Can't detach the disks from the network on"
9664
                               " old node: %s" % (msg,))
9665

    
9666
    # if we managed to detach at least one, we update all the disks of
9667
    # the instance to point to the new secondary
9668
    self.lu.LogInfo("Updating instance configuration")
9669
    for dev, _, new_logical_id in iv_names.itervalues():
9670
      dev.logical_id = new_logical_id
9671
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9672

    
9673
    self.cfg.Update(self.instance, feedback_fn)
9674

    
9675
    # and now perform the drbd attach
9676
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9677
                    " (standalone => connected)")
9678
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9679
                                            self.new_node],
9680
                                           self.node_secondary_ip,
9681
                                           self.instance.disks,
9682
                                           self.instance.name,
9683
                                           False)
9684
    for to_node, to_result in result.items():
9685
      msg = to_result.fail_msg
9686
      if msg:
9687
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9688
                           to_node, msg,
9689
                           hint=("please do a gnt-instance info to see the"
9690
                                 " status of disks"))
9691
    cstep = 5
9692
    if self.early_release:
9693
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9694
      cstep += 1
9695
      self._RemoveOldStorage(self.target_node, iv_names)
9696
      # WARNING: we release all node locks here, do not do other RPCs
9697
      # than WaitForSync to the primary node
9698
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9699
                    names=[self.instance.primary_node,
9700
                           self.target_node,
9701
                           self.new_node])
9702

    
9703
    # Wait for sync
9704
    # This can fail as the old devices are degraded and _WaitForSync
9705
    # does a combined result over all disks, so we don't check its return value
9706
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9707
    cstep += 1
9708
    _WaitForSync(self.lu, self.instance)
9709

    
9710
    # Check all devices manually
9711
    self._CheckDevices(self.instance.primary_node, iv_names)
9712

    
9713
    # Step: remove old storage
9714
    if not self.early_release:
9715
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9716
      self._RemoveOldStorage(self.target_node, iv_names)
9717

    
9718

    
9719
class LURepairNodeStorage(NoHooksLU):
9720
  """Repairs the volume group on a node.
9721

9722
  """
9723
  REQ_BGL = False
9724

    
9725
  def CheckArguments(self):
9726
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9727

    
9728
    storage_type = self.op.storage_type
9729

    
9730
    if (constants.SO_FIX_CONSISTENCY not in
9731
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9732
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9733
                                 " repaired" % storage_type,
9734
                                 errors.ECODE_INVAL)
9735

    
9736
  def ExpandNames(self):
9737
    self.needed_locks = {
9738
      locking.LEVEL_NODE: [self.op.node_name],
9739
      }
9740

    
9741
  def _CheckFaultyDisks(self, instance, node_name):
9742
    """Ensure faulty disks abort the opcode or at least warn."""
9743
    try:
9744
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9745
                                  node_name, True):
9746
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9747
                                   " node '%s'" % (instance.name, node_name),
9748
                                   errors.ECODE_STATE)
9749
    except errors.OpPrereqError, err:
9750
      if self.op.ignore_consistency:
9751
        self.proc.LogWarning(str(err.args[0]))
9752
      else:
9753
        raise
9754

    
9755
  def CheckPrereq(self):
9756
    """Check prerequisites.
9757

9758
    """
9759
    # Check whether any instance on this node has faulty disks
9760
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9761
      if not inst.admin_up:
9762
        continue
9763
      check_nodes = set(inst.all_nodes)
9764
      check_nodes.discard(self.op.node_name)
9765
      for inst_node_name in check_nodes:
9766
        self._CheckFaultyDisks(inst, inst_node_name)
9767

    
9768
  def Exec(self, feedback_fn):
9769
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9770
                (self.op.name, self.op.node_name))
9771

    
9772
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9773
    result = self.rpc.call_storage_execute(self.op.node_name,
9774
                                           self.op.storage_type, st_args,
9775
                                           self.op.name,
9776
                                           constants.SO_FIX_CONSISTENCY)
9777
    result.Raise("Failed to repair storage unit '%s' on %s" %
9778
                 (self.op.name, self.op.node_name))
9779

    
9780

    
9781
class LUNodeEvacuate(NoHooksLU):
9782
  """Evacuates instances off a list of nodes.
9783

9784
  """
9785
  REQ_BGL = False
9786

    
9787
  def CheckArguments(self):
9788
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9789

    
9790
  def ExpandNames(self):
9791
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9792

    
9793
    if self.op.remote_node is not None:
9794
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9795
      assert self.op.remote_node
9796

    
9797
      if self.op.remote_node == self.op.node_name:
9798
        raise errors.OpPrereqError("Can not use evacuated node as a new"
9799
                                   " secondary node", errors.ECODE_INVAL)
9800

    
9801
      if self.op.mode != constants.IALLOCATOR_NEVAC_SEC:
9802
        raise errors.OpPrereqError("Without the use of an iallocator only"
9803
                                   " secondary instances can be evacuated",
9804
                                   errors.ECODE_INVAL)
9805

    
9806
    # Declare locks
9807
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9808
    self.needed_locks = {
9809
      locking.LEVEL_INSTANCE: [],
9810
      locking.LEVEL_NODEGROUP: [],
9811
      locking.LEVEL_NODE: [],
9812
      }
9813

    
9814
    if self.op.remote_node is None:
9815
      # Iallocator will choose any node(s) in the same group
9816
      group_nodes = self.cfg.GetNodeGroupMembersByNodes([self.op.node_name])
9817
    else:
9818
      group_nodes = frozenset([self.op.remote_node])
9819

    
9820
    # Determine nodes to be locked
9821
    self.lock_nodes = set([self.op.node_name]) | group_nodes
9822

    
9823
  def _DetermineInstances(self):
9824
    """Builds list of instances to operate on.
9825

9826
    """
9827
    assert self.op.mode in constants.IALLOCATOR_NEVAC_MODES
9828

    
9829
    if self.op.mode == constants.IALLOCATOR_NEVAC_PRI:
9830
      # Primary instances only
9831
      inst_fn = _GetNodePrimaryInstances
9832
      assert self.op.remote_node is None, \
9833
        "Evacuating primary instances requires iallocator"
9834
    elif self.op.mode == constants.IALLOCATOR_NEVAC_SEC:
9835
      # Secondary instances only
9836
      inst_fn = _GetNodeSecondaryInstances
9837
    else:
9838
      # All instances
9839
      assert self.op.mode == constants.IALLOCATOR_NEVAC_ALL
9840
      inst_fn = _GetNodeInstances
9841

    
9842
    return inst_fn(self.cfg, self.op.node_name)
9843

    
9844
  def DeclareLocks(self, level):
9845
    if level == locking.LEVEL_INSTANCE:
9846
      # Lock instances optimistically, needs verification once node and group
9847
      # locks have been acquired
9848
      self.needed_locks[locking.LEVEL_INSTANCE] = \
9849
        set(i.name for i in self._DetermineInstances())
9850

    
9851
    elif level == locking.LEVEL_NODEGROUP:
9852
      # Lock node groups optimistically, needs verification once nodes have
9853
      # been acquired
9854
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
9855
        self.cfg.GetNodeGroupsFromNodes(self.lock_nodes)
9856

    
9857
    elif level == locking.LEVEL_NODE:
9858
      self.needed_locks[locking.LEVEL_NODE] = self.lock_nodes
9859

    
9860
  def CheckPrereq(self):
9861
    # Verify locks
9862
    owned_instances = self.glm.list_owned(locking.LEVEL_INSTANCE)
9863
    owned_nodes = self.glm.list_owned(locking.LEVEL_NODE)
9864
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
9865

    
9866
    assert owned_nodes == self.lock_nodes
9867

    
9868
    wanted_groups = self.cfg.GetNodeGroupsFromNodes(owned_nodes)
9869
    if owned_groups != wanted_groups:
9870
      raise errors.OpExecError("Node groups changed since locks were acquired,"
9871
                               " current groups are '%s', used to be '%s'" %
9872
                               (utils.CommaJoin(wanted_groups),
9873
                                utils.CommaJoin(owned_groups)))
9874

    
9875
    # Determine affected instances
9876
    self.instances = self._DetermineInstances()
9877
    self.instance_names = [i.name for i in self.instances]
9878

    
9879
    if set(self.instance_names) != owned_instances:
9880
      raise errors.OpExecError("Instances on node '%s' changed since locks"
9881
                               " were acquired, current instances are '%s',"
9882
                               " used to be '%s'" %
9883
                               (self.op.node_name,
9884
                                utils.CommaJoin(self.instance_names),
9885
                                utils.CommaJoin(owned_instances)))
9886

    
9887
    if self.instance_names:
9888
      self.LogInfo("Evacuating instances from node '%s': %s",
9889
                   self.op.node_name,
9890
                   utils.CommaJoin(utils.NiceSort(self.instance_names)))
9891
    else:
9892
      self.LogInfo("No instances to evacuate from node '%s'",
9893
                   self.op.node_name)
9894

    
9895
    if self.op.remote_node is not None:
9896
      for i in self.instances:
9897
        if i.primary_node == self.op.remote_node:
9898
          raise errors.OpPrereqError("Node %s is the primary node of"
9899
                                     " instance %s, cannot use it as"
9900
                                     " secondary" %
9901
                                     (self.op.remote_node, i.name),
9902
                                     errors.ECODE_INVAL)
9903

    
9904
  def Exec(self, feedback_fn):
9905
    assert (self.op.iallocator is not None) ^ (self.op.remote_node is not None)
9906

    
9907
    if not self.instance_names:
9908
      # No instances to evacuate
9909
      jobs = []
9910

    
9911
    elif self.op.iallocator is not None:
9912
      # TODO: Implement relocation to other group
9913
      ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_NODE_EVAC,
9914
                       evac_mode=self.op.mode,
9915
                       instances=list(self.instance_names))
9916

    
9917
      ial.Run(self.op.iallocator)
9918

    
9919
      if not ial.success:
9920
        raise errors.OpPrereqError("Can't compute node evacuation using"
9921
                                   " iallocator '%s': %s" %
9922
                                   (self.op.iallocator, ial.info),
9923
                                   errors.ECODE_NORES)
9924

    
9925
      jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, True)
9926

    
9927
    elif self.op.remote_node is not None:
9928
      assert self.op.mode == constants.IALLOCATOR_NEVAC_SEC
9929
      jobs = [
9930
        [opcodes.OpInstanceReplaceDisks(instance_name=instance_name,
9931
                                        remote_node=self.op.remote_node,
9932
                                        disks=[],
9933
                                        mode=constants.REPLACE_DISK_CHG,
9934
                                        early_release=self.op.early_release)]
9935
        for instance_name in self.instance_names
9936
        ]
9937

    
9938
    else:
9939
      raise errors.ProgrammerError("No iallocator or remote node")
9940

    
9941
    return ResultWithJobs(jobs)
9942

    
9943

    
9944
def _SetOpEarlyRelease(early_release, op):
9945
  """Sets C{early_release} flag on opcodes if available.
9946

9947
  """
9948
  try:
9949
    op.early_release = early_release
9950
  except AttributeError:
9951
    assert not isinstance(op, opcodes.OpInstanceReplaceDisks)
9952

    
9953
  return op
9954

    
9955

    
9956
def _NodeEvacDest(use_nodes, group, nodes):
9957
  """Returns group or nodes depending on caller's choice.
9958

9959
  """
9960
  if use_nodes:
9961
    return utils.CommaJoin(nodes)
9962
  else:
9963
    return group
9964

    
9965

    
9966
def _LoadNodeEvacResult(lu, alloc_result, early_release, use_nodes):
9967
  """Unpacks the result of change-group and node-evacuate iallocator requests.
9968

9969
  Iallocator modes L{constants.IALLOCATOR_MODE_NODE_EVAC} and
9970
  L{constants.IALLOCATOR_MODE_CHG_GROUP}.
9971

9972
  @type lu: L{LogicalUnit}
9973
  @param lu: Logical unit instance
9974
  @type alloc_result: tuple/list
9975
  @param alloc_result: Result from iallocator
9976
  @type early_release: bool
9977
  @param early_release: Whether to release locks early if possible
9978
  @type use_nodes: bool
9979
  @param use_nodes: Whether to display node names instead of groups
9980

9981
  """
9982
  (moved, failed, jobs) = alloc_result
9983

    
9984
  if failed:
9985
    lu.LogWarning("Unable to evacuate instances %s",
9986
                  utils.CommaJoin("%s (%s)" % (name, reason)
9987
                                  for (name, reason) in failed))
9988

    
9989
  if moved:
9990
    lu.LogInfo("Instances to be moved: %s",
9991
               utils.CommaJoin("%s (to %s)" %
9992
                               (name, _NodeEvacDest(use_nodes, group, nodes))
9993
                               for (name, group, nodes) in moved))
9994

    
9995
  return [map(compat.partial(_SetOpEarlyRelease, early_release),
9996
              map(opcodes.OpCode.LoadOpCode, ops))
9997
          for ops in jobs]
9998

    
9999

    
10000
class LUInstanceGrowDisk(LogicalUnit):
10001
  """Grow a disk of an instance.
10002

10003
  """
10004
  HPATH = "disk-grow"
10005
  HTYPE = constants.HTYPE_INSTANCE
10006
  REQ_BGL = False
10007

    
10008
  def ExpandNames(self):
10009
    self._ExpandAndLockInstance()
10010
    self.needed_locks[locking.LEVEL_NODE] = []
10011
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10012

    
10013
  def DeclareLocks(self, level):
10014
    if level == locking.LEVEL_NODE:
10015
      self._LockInstancesNodes()
10016

    
10017
  def BuildHooksEnv(self):
10018
    """Build hooks env.
10019

10020
    This runs on the master, the primary and all the secondaries.
10021

10022
    """
10023
    env = {
10024
      "DISK": self.op.disk,
10025
      "AMOUNT": self.op.amount,
10026
      }
10027
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10028
    return env
10029

    
10030
  def BuildHooksNodes(self):
10031
    """Build hooks nodes.
10032

10033
    """
10034
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10035
    return (nl, nl)
10036

    
10037
  def CheckPrereq(self):
10038
    """Check prerequisites.
10039

10040
    This checks that the instance is in the cluster.
10041

10042
    """
10043
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10044
    assert instance is not None, \
10045
      "Cannot retrieve locked instance %s" % self.op.instance_name
10046
    nodenames = list(instance.all_nodes)
10047
    for node in nodenames:
10048
      _CheckNodeOnline(self, node)
10049

    
10050
    self.instance = instance
10051

    
10052
    if instance.disk_template not in constants.DTS_GROWABLE:
10053
      raise errors.OpPrereqError("Instance's disk layout does not support"
10054
                                 " growing", errors.ECODE_INVAL)
10055

    
10056
    self.disk = instance.FindDisk(self.op.disk)
10057

    
10058
    if instance.disk_template not in (constants.DT_FILE,
10059
                                      constants.DT_SHARED_FILE):
10060
      # TODO: check the free disk space for file, when that feature will be
10061
      # supported
10062
      _CheckNodesFreeDiskPerVG(self, nodenames,
10063
                               self.disk.ComputeGrowth(self.op.amount))
10064

    
10065
  def Exec(self, feedback_fn):
10066
    """Execute disk grow.
10067

10068
    """
10069
    instance = self.instance
10070
    disk = self.disk
10071

    
10072
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
10073
    if not disks_ok:
10074
      raise errors.OpExecError("Cannot activate block device to grow")
10075

    
10076
    # First run all grow ops in dry-run mode
10077
    for node in instance.all_nodes:
10078
      self.cfg.SetDiskID(disk, node)
10079
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
10080
      result.Raise("Grow request failed to node %s" % node)
10081

    
10082
    # We know that (as far as we can test) operations across different
10083
    # nodes will succeed, time to run it for real
10084
    for node in instance.all_nodes:
10085
      self.cfg.SetDiskID(disk, node)
10086
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
10087
      result.Raise("Grow request failed to node %s" % node)
10088

    
10089
      # TODO: Rewrite code to work properly
10090
      # DRBD goes into sync mode for a short amount of time after executing the
10091
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
10092
      # calling "resize" in sync mode fails. Sleeping for a short amount of
10093
      # time is a work-around.
10094
      time.sleep(5)
10095

    
10096
    disk.RecordGrow(self.op.amount)
10097
    self.cfg.Update(instance, feedback_fn)
10098
    if self.op.wait_for_sync:
10099
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
10100
      if disk_abort:
10101
        self.proc.LogWarning("Disk sync-ing has not returned a good"
10102
                             " status; please check the instance")
10103
      if not instance.admin_up:
10104
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
10105
    elif not instance.admin_up:
10106
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
10107
                           " not supposed to be running because no wait for"
10108
                           " sync mode was requested")
10109

    
10110

    
10111
class LUInstanceQueryData(NoHooksLU):
10112
  """Query runtime instance data.
10113

10114
  """
10115
  REQ_BGL = False
10116

    
10117
  def ExpandNames(self):
10118
    self.needed_locks = {}
10119

    
10120
    # Use locking if requested or when non-static information is wanted
10121
    if not (self.op.static or self.op.use_locking):
10122
      self.LogWarning("Non-static data requested, locks need to be acquired")
10123
      self.op.use_locking = True
10124

    
10125
    if self.op.instances or not self.op.use_locking:
10126
      # Expand instance names right here
10127
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
10128
    else:
10129
      # Will use acquired locks
10130
      self.wanted_names = None
10131

    
10132
    if self.op.use_locking:
10133
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10134

    
10135
      if self.wanted_names is None:
10136
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
10137
      else:
10138
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
10139

    
10140
      self.needed_locks[locking.LEVEL_NODE] = []
10141
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
10142
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10143

    
10144
  def DeclareLocks(self, level):
10145
    if self.op.use_locking and level == locking.LEVEL_NODE:
10146
      self._LockInstancesNodes()
10147

    
10148
  def CheckPrereq(self):
10149
    """Check prerequisites.
10150

10151
    This only checks the optional instance list against the existing names.
10152

10153
    """
10154
    if self.wanted_names is None:
10155
      assert self.op.use_locking, "Locking was not used"
10156
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
10157

    
10158
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
10159
                             for name in self.wanted_names]
10160

    
10161
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
10162
    """Returns the status of a block device
10163

10164
    """
10165
    if self.op.static or not node:
10166
      return None
10167

    
10168
    self.cfg.SetDiskID(dev, node)
10169

    
10170
    result = self.rpc.call_blockdev_find(node, dev)
10171
    if result.offline:
10172
      return None
10173

    
10174
    result.Raise("Can't compute disk status for %s" % instance_name)
10175

    
10176
    status = result.payload
10177
    if status is None:
10178
      return None
10179

    
10180
    return (status.dev_path, status.major, status.minor,
10181
            status.sync_percent, status.estimated_time,
10182
            status.is_degraded, status.ldisk_status)
10183

    
10184
  def _ComputeDiskStatus(self, instance, snode, dev):
10185
    """Compute block device status.
10186

10187
    """
10188
    if dev.dev_type in constants.LDS_DRBD:
10189
      # we change the snode then (otherwise we use the one passed in)
10190
      if dev.logical_id[0] == instance.primary_node:
10191
        snode = dev.logical_id[1]
10192
      else:
10193
        snode = dev.logical_id[0]
10194

    
10195
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
10196
                                              instance.name, dev)
10197
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
10198

    
10199
    if dev.children:
10200
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
10201
                      for child in dev.children]
10202
    else:
10203
      dev_children = []
10204

    
10205
    return {
10206
      "iv_name": dev.iv_name,
10207
      "dev_type": dev.dev_type,
10208
      "logical_id": dev.logical_id,
10209
      "physical_id": dev.physical_id,
10210
      "pstatus": dev_pstatus,
10211
      "sstatus": dev_sstatus,
10212
      "children": dev_children,
10213
      "mode": dev.mode,
10214
      "size": dev.size,
10215
      }
10216

    
10217
  def Exec(self, feedback_fn):
10218
    """Gather and return data"""
10219
    result = {}
10220

    
10221
    cluster = self.cfg.GetClusterInfo()
10222

    
10223
    for instance in self.wanted_instances:
10224
      if not self.op.static:
10225
        remote_info = self.rpc.call_instance_info(instance.primary_node,
10226
                                                  instance.name,
10227
                                                  instance.hypervisor)
10228
        remote_info.Raise("Error checking node %s" % instance.primary_node)
10229
        remote_info = remote_info.payload
10230
        if remote_info and "state" in remote_info:
10231
          remote_state = "up"
10232
        else:
10233
          remote_state = "down"
10234
      else:
10235
        remote_state = None
10236
      if instance.admin_up:
10237
        config_state = "up"
10238
      else:
10239
        config_state = "down"
10240

    
10241
      disks = [self._ComputeDiskStatus(instance, None, device)
10242
               for device in instance.disks]
10243

    
10244
      result[instance.name] = {
10245
        "name": instance.name,
10246
        "config_state": config_state,
10247
        "run_state": remote_state,
10248
        "pnode": instance.primary_node,
10249
        "snodes": instance.secondary_nodes,
10250
        "os": instance.os,
10251
        # this happens to be the same format used for hooks
10252
        "nics": _NICListToTuple(self, instance.nics),
10253
        "disk_template": instance.disk_template,
10254
        "disks": disks,
10255
        "hypervisor": instance.hypervisor,
10256
        "network_port": instance.network_port,
10257
        "hv_instance": instance.hvparams,
10258
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
10259
        "be_instance": instance.beparams,
10260
        "be_actual": cluster.FillBE(instance),
10261
        "os_instance": instance.osparams,
10262
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
10263
        "serial_no": instance.serial_no,
10264
        "mtime": instance.mtime,
10265
        "ctime": instance.ctime,
10266
        "uuid": instance.uuid,
10267
        }
10268

    
10269
    return result
10270

    
10271

    
10272
class LUInstanceSetParams(LogicalUnit):
10273
  """Modifies an instances's parameters.
10274

10275
  """
10276
  HPATH = "instance-modify"
10277
  HTYPE = constants.HTYPE_INSTANCE
10278
  REQ_BGL = False
10279

    
10280
  def CheckArguments(self):
10281
    if not (self.op.nics or self.op.disks or self.op.disk_template or
10282
            self.op.hvparams or self.op.beparams or self.op.os_name):
10283
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
10284

    
10285
    if self.op.hvparams:
10286
      _CheckGlobalHvParams(self.op.hvparams)
10287

    
10288
    # Disk validation
10289
    disk_addremove = 0
10290
    for disk_op, disk_dict in self.op.disks:
10291
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
10292
      if disk_op == constants.DDM_REMOVE:
10293
        disk_addremove += 1
10294
        continue
10295
      elif disk_op == constants.DDM_ADD:
10296
        disk_addremove += 1
10297
      else:
10298
        if not isinstance(disk_op, int):
10299
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
10300
        if not isinstance(disk_dict, dict):
10301
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
10302
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10303

    
10304
      if disk_op == constants.DDM_ADD:
10305
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
10306
        if mode not in constants.DISK_ACCESS_SET:
10307
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
10308
                                     errors.ECODE_INVAL)
10309
        size = disk_dict.get(constants.IDISK_SIZE, None)
10310
        if size is None:
10311
          raise errors.OpPrereqError("Required disk parameter size missing",
10312
                                     errors.ECODE_INVAL)
10313
        try:
10314
          size = int(size)
10315
        except (TypeError, ValueError), err:
10316
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
10317
                                     str(err), errors.ECODE_INVAL)
10318
        disk_dict[constants.IDISK_SIZE] = size
10319
      else:
10320
        # modification of disk
10321
        if constants.IDISK_SIZE in disk_dict:
10322
          raise errors.OpPrereqError("Disk size change not possible, use"
10323
                                     " grow-disk", errors.ECODE_INVAL)
10324

    
10325
    if disk_addremove > 1:
10326
      raise errors.OpPrereqError("Only one disk add or remove operation"
10327
                                 " supported at a time", errors.ECODE_INVAL)
10328

    
10329
    if self.op.disks and self.op.disk_template is not None:
10330
      raise errors.OpPrereqError("Disk template conversion and other disk"
10331
                                 " changes not supported at the same time",
10332
                                 errors.ECODE_INVAL)
10333

    
10334
    if (self.op.disk_template and
10335
        self.op.disk_template in constants.DTS_INT_MIRROR and
10336
        self.op.remote_node is None):
10337
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
10338
                                 " one requires specifying a secondary node",
10339
                                 errors.ECODE_INVAL)
10340

    
10341
    # NIC validation
10342
    nic_addremove = 0
10343
    for nic_op, nic_dict in self.op.nics:
10344
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
10345
      if nic_op == constants.DDM_REMOVE:
10346
        nic_addremove += 1
10347
        continue
10348
      elif nic_op == constants.DDM_ADD:
10349
        nic_addremove += 1
10350
      else:
10351
        if not isinstance(nic_op, int):
10352
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
10353
        if not isinstance(nic_dict, dict):
10354
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
10355
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
10356

    
10357
      # nic_dict should be a dict
10358
      nic_ip = nic_dict.get(constants.INIC_IP, None)
10359
      if nic_ip is not None:
10360
        if nic_ip.lower() == constants.VALUE_NONE:
10361
          nic_dict[constants.INIC_IP] = None
10362
        else:
10363
          if not netutils.IPAddress.IsValid(nic_ip):
10364
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
10365
                                       errors.ECODE_INVAL)
10366

    
10367
      nic_bridge = nic_dict.get('bridge', None)
10368
      nic_link = nic_dict.get(constants.INIC_LINK, None)
10369
      if nic_bridge and nic_link:
10370
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
10371
                                   " at the same time", errors.ECODE_INVAL)
10372
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
10373
        nic_dict['bridge'] = None
10374
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
10375
        nic_dict[constants.INIC_LINK] = None
10376

    
10377
      if nic_op == constants.DDM_ADD:
10378
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
10379
        if nic_mac is None:
10380
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
10381

    
10382
      if constants.INIC_MAC in nic_dict:
10383
        nic_mac = nic_dict[constants.INIC_MAC]
10384
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10385
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
10386

    
10387
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
10388
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
10389
                                     " modifying an existing nic",
10390
                                     errors.ECODE_INVAL)
10391

    
10392
    if nic_addremove > 1:
10393
      raise errors.OpPrereqError("Only one NIC add or remove operation"
10394
                                 " supported at a time", errors.ECODE_INVAL)
10395

    
10396
  def ExpandNames(self):
10397
    self._ExpandAndLockInstance()
10398
    self.needed_locks[locking.LEVEL_NODE] = []
10399
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
10400

    
10401
  def DeclareLocks(self, level):
10402
    if level == locking.LEVEL_NODE:
10403
      self._LockInstancesNodes()
10404
      if self.op.disk_template and self.op.remote_node:
10405
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
10406
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
10407

    
10408
  def BuildHooksEnv(self):
10409
    """Build hooks env.
10410

10411
    This runs on the master, primary and secondaries.
10412

10413
    """
10414
    args = dict()
10415
    if constants.BE_MEMORY in self.be_new:
10416
      args['memory'] = self.be_new[constants.BE_MEMORY]
10417
    if constants.BE_VCPUS in self.be_new:
10418
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
10419
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
10420
    # information at all.
10421
    if self.op.nics:
10422
      args['nics'] = []
10423
      nic_override = dict(self.op.nics)
10424
      for idx, nic in enumerate(self.instance.nics):
10425
        if idx in nic_override:
10426
          this_nic_override = nic_override[idx]
10427
        else:
10428
          this_nic_override = {}
10429
        if constants.INIC_IP in this_nic_override:
10430
          ip = this_nic_override[constants.INIC_IP]
10431
        else:
10432
          ip = nic.ip
10433
        if constants.INIC_MAC in this_nic_override:
10434
          mac = this_nic_override[constants.INIC_MAC]
10435
        else:
10436
          mac = nic.mac
10437
        if idx in self.nic_pnew:
10438
          nicparams = self.nic_pnew[idx]
10439
        else:
10440
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10441
        mode = nicparams[constants.NIC_MODE]
10442
        link = nicparams[constants.NIC_LINK]
10443
        args['nics'].append((ip, mac, mode, link))
10444
      if constants.DDM_ADD in nic_override:
10445
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10446
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10447
        nicparams = self.nic_pnew[constants.DDM_ADD]
10448
        mode = nicparams[constants.NIC_MODE]
10449
        link = nicparams[constants.NIC_LINK]
10450
        args['nics'].append((ip, mac, mode, link))
10451
      elif constants.DDM_REMOVE in nic_override:
10452
        del args['nics'][-1]
10453

    
10454
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10455
    if self.op.disk_template:
10456
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10457

    
10458
    return env
10459

    
10460
  def BuildHooksNodes(self):
10461
    """Build hooks nodes.
10462

10463
    """
10464
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10465
    return (nl, nl)
10466

    
10467
  def CheckPrereq(self):
10468
    """Check prerequisites.
10469

10470
    This only checks the instance list against the existing names.
10471

10472
    """
10473
    # checking the new params on the primary/secondary nodes
10474

    
10475
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10476
    cluster = self.cluster = self.cfg.GetClusterInfo()
10477
    assert self.instance is not None, \
10478
      "Cannot retrieve locked instance %s" % self.op.instance_name
10479
    pnode = instance.primary_node
10480
    nodelist = list(instance.all_nodes)
10481

    
10482
    # OS change
10483
    if self.op.os_name and not self.op.force:
10484
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10485
                      self.op.force_variant)
10486
      instance_os = self.op.os_name
10487
    else:
10488
      instance_os = instance.os
10489

    
10490
    if self.op.disk_template:
10491
      if instance.disk_template == self.op.disk_template:
10492
        raise errors.OpPrereqError("Instance already has disk template %s" %
10493
                                   instance.disk_template, errors.ECODE_INVAL)
10494

    
10495
      if (instance.disk_template,
10496
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10497
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10498
                                   " %s to %s" % (instance.disk_template,
10499
                                                  self.op.disk_template),
10500
                                   errors.ECODE_INVAL)
10501
      _CheckInstanceDown(self, instance, "cannot change disk template")
10502
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10503
        if self.op.remote_node == pnode:
10504
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10505
                                     " as the primary node of the instance" %
10506
                                     self.op.remote_node, errors.ECODE_STATE)
10507
        _CheckNodeOnline(self, self.op.remote_node)
10508
        _CheckNodeNotDrained(self, self.op.remote_node)
10509
        # FIXME: here we assume that the old instance type is DT_PLAIN
10510
        assert instance.disk_template == constants.DT_PLAIN
10511
        disks = [{constants.IDISK_SIZE: d.size,
10512
                  constants.IDISK_VG: d.logical_id[0]}
10513
                 for d in instance.disks]
10514
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10515
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10516

    
10517
    # hvparams processing
10518
    if self.op.hvparams:
10519
      hv_type = instance.hypervisor
10520
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10521
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10522
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10523

    
10524
      # local check
10525
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10526
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10527
      self.hv_new = hv_new # the new actual values
10528
      self.hv_inst = i_hvdict # the new dict (without defaults)
10529
    else:
10530
      self.hv_new = self.hv_inst = {}
10531

    
10532
    # beparams processing
10533
    if self.op.beparams:
10534
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10535
                                   use_none=True)
10536
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10537
      be_new = cluster.SimpleFillBE(i_bedict)
10538
      self.be_new = be_new # the new actual values
10539
      self.be_inst = i_bedict # the new dict (without defaults)
10540
    else:
10541
      self.be_new = self.be_inst = {}
10542
    be_old = cluster.FillBE(instance)
10543

    
10544
    # osparams processing
10545
    if self.op.osparams:
10546
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10547
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10548
      self.os_inst = i_osdict # the new dict (without defaults)
10549
    else:
10550
      self.os_inst = {}
10551

    
10552
    self.warn = []
10553

    
10554
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10555
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10556
      mem_check_list = [pnode]
10557
      if be_new[constants.BE_AUTO_BALANCE]:
10558
        # either we changed auto_balance to yes or it was from before
10559
        mem_check_list.extend(instance.secondary_nodes)
10560
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10561
                                                  instance.hypervisor)
10562
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10563
                                         instance.hypervisor)
10564
      pninfo = nodeinfo[pnode]
10565
      msg = pninfo.fail_msg
10566
      if msg:
10567
        # Assume the primary node is unreachable and go ahead
10568
        self.warn.append("Can't get info from primary node %s: %s" %
10569
                         (pnode,  msg))
10570
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10571
        self.warn.append("Node data from primary node %s doesn't contain"
10572
                         " free memory information" % pnode)
10573
      elif instance_info.fail_msg:
10574
        self.warn.append("Can't get instance runtime information: %s" %
10575
                        instance_info.fail_msg)
10576
      else:
10577
        if instance_info.payload:
10578
          current_mem = int(instance_info.payload['memory'])
10579
        else:
10580
          # Assume instance not running
10581
          # (there is a slight race condition here, but it's not very probable,
10582
          # and we have no other way to check)
10583
          current_mem = 0
10584
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10585
                    pninfo.payload['memory_free'])
10586
        if miss_mem > 0:
10587
          raise errors.OpPrereqError("This change will prevent the instance"
10588
                                     " from starting, due to %d MB of memory"
10589
                                     " missing on its primary node" % miss_mem,
10590
                                     errors.ECODE_NORES)
10591

    
10592
      if be_new[constants.BE_AUTO_BALANCE]:
10593
        for node, nres in nodeinfo.items():
10594
          if node not in instance.secondary_nodes:
10595
            continue
10596
          nres.Raise("Can't get info from secondary node %s" % node,
10597
                     prereq=True, ecode=errors.ECODE_STATE)
10598
          if not isinstance(nres.payload.get('memory_free', None), int):
10599
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10600
                                       " memory information" % node,
10601
                                       errors.ECODE_STATE)
10602
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10603
            raise errors.OpPrereqError("This change will prevent the instance"
10604
                                       " from failover to its secondary node"
10605
                                       " %s, due to not enough memory" % node,
10606
                                       errors.ECODE_STATE)
10607

    
10608
    # NIC processing
10609
    self.nic_pnew = {}
10610
    self.nic_pinst = {}
10611
    for nic_op, nic_dict in self.op.nics:
10612
      if nic_op == constants.DDM_REMOVE:
10613
        if not instance.nics:
10614
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10615
                                     errors.ECODE_INVAL)
10616
        continue
10617
      if nic_op != constants.DDM_ADD:
10618
        # an existing nic
10619
        if not instance.nics:
10620
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10621
                                     " no NICs" % nic_op,
10622
                                     errors.ECODE_INVAL)
10623
        if nic_op < 0 or nic_op >= len(instance.nics):
10624
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10625
                                     " are 0 to %d" %
10626
                                     (nic_op, len(instance.nics) - 1),
10627
                                     errors.ECODE_INVAL)
10628
        old_nic_params = instance.nics[nic_op].nicparams
10629
        old_nic_ip = instance.nics[nic_op].ip
10630
      else:
10631
        old_nic_params = {}
10632
        old_nic_ip = None
10633

    
10634
      update_params_dict = dict([(key, nic_dict[key])
10635
                                 for key in constants.NICS_PARAMETERS
10636
                                 if key in nic_dict])
10637

    
10638
      if 'bridge' in nic_dict:
10639
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10640

    
10641
      new_nic_params = _GetUpdatedParams(old_nic_params,
10642
                                         update_params_dict)
10643
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10644
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10645
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10646
      self.nic_pinst[nic_op] = new_nic_params
10647
      self.nic_pnew[nic_op] = new_filled_nic_params
10648
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10649

    
10650
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10651
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10652
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10653
        if msg:
10654
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10655
          if self.op.force:
10656
            self.warn.append(msg)
10657
          else:
10658
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10659
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10660
        if constants.INIC_IP in nic_dict:
10661
          nic_ip = nic_dict[constants.INIC_IP]
10662
        else:
10663
          nic_ip = old_nic_ip
10664
        if nic_ip is None:
10665
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10666
                                     ' on a routed nic', errors.ECODE_INVAL)
10667
      if constants.INIC_MAC in nic_dict:
10668
        nic_mac = nic_dict[constants.INIC_MAC]
10669
        if nic_mac is None:
10670
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10671
                                     errors.ECODE_INVAL)
10672
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10673
          # otherwise generate the mac
10674
          nic_dict[constants.INIC_MAC] = \
10675
            self.cfg.GenerateMAC(self.proc.GetECId())
10676
        else:
10677
          # or validate/reserve the current one
10678
          try:
10679
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10680
          except errors.ReservationError:
10681
            raise errors.OpPrereqError("MAC address %s already in use"
10682
                                       " in cluster" % nic_mac,
10683
                                       errors.ECODE_NOTUNIQUE)
10684

    
10685
    # DISK processing
10686
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10687
      raise errors.OpPrereqError("Disk operations not supported for"
10688
                                 " diskless instances",
10689
                                 errors.ECODE_INVAL)
10690
    for disk_op, _ in self.op.disks:
10691
      if disk_op == constants.DDM_REMOVE:
10692
        if len(instance.disks) == 1:
10693
          raise errors.OpPrereqError("Cannot remove the last disk of"
10694
                                     " an instance", errors.ECODE_INVAL)
10695
        _CheckInstanceDown(self, instance, "cannot remove disks")
10696

    
10697
      if (disk_op == constants.DDM_ADD and
10698
          len(instance.disks) >= constants.MAX_DISKS):
10699
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10700
                                   " add more" % constants.MAX_DISKS,
10701
                                   errors.ECODE_STATE)
10702
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10703
        # an existing disk
10704
        if disk_op < 0 or disk_op >= len(instance.disks):
10705
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10706
                                     " are 0 to %d" %
10707
                                     (disk_op, len(instance.disks)),
10708
                                     errors.ECODE_INVAL)
10709

    
10710
    return
10711

    
10712
  def _ConvertPlainToDrbd(self, feedback_fn):
10713
    """Converts an instance from plain to drbd.
10714

10715
    """
10716
    feedback_fn("Converting template to drbd")
10717
    instance = self.instance
10718
    pnode = instance.primary_node
10719
    snode = self.op.remote_node
10720

    
10721
    # create a fake disk info for _GenerateDiskTemplate
10722
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10723
                  constants.IDISK_VG: d.logical_id[0]}
10724
                 for d in instance.disks]
10725
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10726
                                      instance.name, pnode, [snode],
10727
                                      disk_info, None, None, 0, feedback_fn)
10728
    info = _GetInstanceInfoText(instance)
10729
    feedback_fn("Creating aditional volumes...")
10730
    # first, create the missing data and meta devices
10731
    for disk in new_disks:
10732
      # unfortunately this is... not too nice
10733
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10734
                            info, True)
10735
      for child in disk.children:
10736
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10737
    # at this stage, all new LVs have been created, we can rename the
10738
    # old ones
10739
    feedback_fn("Renaming original volumes...")
10740
    rename_list = [(o, n.children[0].logical_id)
10741
                   for (o, n) in zip(instance.disks, new_disks)]
10742
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10743
    result.Raise("Failed to rename original LVs")
10744

    
10745
    feedback_fn("Initializing DRBD devices...")
10746
    # all child devices are in place, we can now create the DRBD devices
10747
    for disk in new_disks:
10748
      for node in [pnode, snode]:
10749
        f_create = node == pnode
10750
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10751

    
10752
    # at this point, the instance has been modified
10753
    instance.disk_template = constants.DT_DRBD8
10754
    instance.disks = new_disks
10755
    self.cfg.Update(instance, feedback_fn)
10756

    
10757
    # disks are created, waiting for sync
10758
    disk_abort = not _WaitForSync(self, instance,
10759
                                  oneshot=not self.op.wait_for_sync)
10760
    if disk_abort:
10761
      raise errors.OpExecError("There are some degraded disks for"
10762
                               " this instance, please cleanup manually")
10763

    
10764
  def _ConvertDrbdToPlain(self, feedback_fn):
10765
    """Converts an instance from drbd to plain.
10766

10767
    """
10768
    instance = self.instance
10769
    assert len(instance.secondary_nodes) == 1
10770
    pnode = instance.primary_node
10771
    snode = instance.secondary_nodes[0]
10772
    feedback_fn("Converting template to plain")
10773

    
10774
    old_disks = instance.disks
10775
    new_disks = [d.children[0] for d in old_disks]
10776

    
10777
    # copy over size and mode
10778
    for parent, child in zip(old_disks, new_disks):
10779
      child.size = parent.size
10780
      child.mode = parent.mode
10781

    
10782
    # update instance structure
10783
    instance.disks = new_disks
10784
    instance.disk_template = constants.DT_PLAIN
10785
    self.cfg.Update(instance, feedback_fn)
10786

    
10787
    feedback_fn("Removing volumes on the secondary node...")
10788
    for disk in old_disks:
10789
      self.cfg.SetDiskID(disk, snode)
10790
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10791
      if msg:
10792
        self.LogWarning("Could not remove block device %s on node %s,"
10793
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10794

    
10795
    feedback_fn("Removing unneeded volumes on the primary node...")
10796
    for idx, disk in enumerate(old_disks):
10797
      meta = disk.children[1]
10798
      self.cfg.SetDiskID(meta, pnode)
10799
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10800
      if msg:
10801
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10802
                        " continuing anyway: %s", idx, pnode, msg)
10803

    
10804
  def Exec(self, feedback_fn):
10805
    """Modifies an instance.
10806

10807
    All parameters take effect only at the next restart of the instance.
10808

10809
    """
10810
    # Process here the warnings from CheckPrereq, as we don't have a
10811
    # feedback_fn there.
10812
    for warn in self.warn:
10813
      feedback_fn("WARNING: %s" % warn)
10814

    
10815
    result = []
10816
    instance = self.instance
10817
    # disk changes
10818
    for disk_op, disk_dict in self.op.disks:
10819
      if disk_op == constants.DDM_REMOVE:
10820
        # remove the last disk
10821
        device = instance.disks.pop()
10822
        device_idx = len(instance.disks)
10823
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10824
          self.cfg.SetDiskID(disk, node)
10825
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10826
          if msg:
10827
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10828
                            " continuing anyway", device_idx, node, msg)
10829
        result.append(("disk/%d" % device_idx, "remove"))
10830
      elif disk_op == constants.DDM_ADD:
10831
        # add a new disk
10832
        if instance.disk_template in (constants.DT_FILE,
10833
                                        constants.DT_SHARED_FILE):
10834
          file_driver, file_path = instance.disks[0].logical_id
10835
          file_path = os.path.dirname(file_path)
10836
        else:
10837
          file_driver = file_path = None
10838
        disk_idx_base = len(instance.disks)
10839
        new_disk = _GenerateDiskTemplate(self,
10840
                                         instance.disk_template,
10841
                                         instance.name, instance.primary_node,
10842
                                         instance.secondary_nodes,
10843
                                         [disk_dict],
10844
                                         file_path,
10845
                                         file_driver,
10846
                                         disk_idx_base, feedback_fn)[0]
10847
        instance.disks.append(new_disk)
10848
        info = _GetInstanceInfoText(instance)
10849

    
10850
        logging.info("Creating volume %s for instance %s",
10851
                     new_disk.iv_name, instance.name)
10852
        # Note: this needs to be kept in sync with _CreateDisks
10853
        #HARDCODE
10854
        for node in instance.all_nodes:
10855
          f_create = node == instance.primary_node
10856
          try:
10857
            _CreateBlockDev(self, node, instance, new_disk,
10858
                            f_create, info, f_create)
10859
          except errors.OpExecError, err:
10860
            self.LogWarning("Failed to create volume %s (%s) on"
10861
                            " node %s: %s",
10862
                            new_disk.iv_name, new_disk, node, err)
10863
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10864
                       (new_disk.size, new_disk.mode)))
10865
      else:
10866
        # change a given disk
10867
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10868
        result.append(("disk.mode/%d" % disk_op,
10869
                       disk_dict[constants.IDISK_MODE]))
10870

    
10871
    if self.op.disk_template:
10872
      r_shut = _ShutdownInstanceDisks(self, instance)
10873
      if not r_shut:
10874
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10875
                                 " proceed with disk template conversion")
10876
      mode = (instance.disk_template, self.op.disk_template)
10877
      try:
10878
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10879
      except:
10880
        self.cfg.ReleaseDRBDMinors(instance.name)
10881
        raise
10882
      result.append(("disk_template", self.op.disk_template))
10883

    
10884
    # NIC changes
10885
    for nic_op, nic_dict in self.op.nics:
10886
      if nic_op == constants.DDM_REMOVE:
10887
        # remove the last nic
10888
        del instance.nics[-1]
10889
        result.append(("nic.%d" % len(instance.nics), "remove"))
10890
      elif nic_op == constants.DDM_ADD:
10891
        # mac and bridge should be set, by now
10892
        mac = nic_dict[constants.INIC_MAC]
10893
        ip = nic_dict.get(constants.INIC_IP, None)
10894
        nicparams = self.nic_pinst[constants.DDM_ADD]
10895
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10896
        instance.nics.append(new_nic)
10897
        result.append(("nic.%d" % (len(instance.nics) - 1),
10898
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10899
                       (new_nic.mac, new_nic.ip,
10900
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10901
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10902
                       )))
10903
      else:
10904
        for key in (constants.INIC_MAC, constants.INIC_IP):
10905
          if key in nic_dict:
10906
            setattr(instance.nics[nic_op], key, nic_dict[key])
10907
        if nic_op in self.nic_pinst:
10908
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10909
        for key, val in nic_dict.iteritems():
10910
          result.append(("nic.%s/%d" % (key, nic_op), val))
10911

    
10912
    # hvparams changes
10913
    if self.op.hvparams:
10914
      instance.hvparams = self.hv_inst
10915
      for key, val in self.op.hvparams.iteritems():
10916
        result.append(("hv/%s" % key, val))
10917

    
10918
    # beparams changes
10919
    if self.op.beparams:
10920
      instance.beparams = self.be_inst
10921
      for key, val in self.op.beparams.iteritems():
10922
        result.append(("be/%s" % key, val))
10923

    
10924
    # OS change
10925
    if self.op.os_name:
10926
      instance.os = self.op.os_name
10927

    
10928
    # osparams changes
10929
    if self.op.osparams:
10930
      instance.osparams = self.os_inst
10931
      for key, val in self.op.osparams.iteritems():
10932
        result.append(("os/%s" % key, val))
10933

    
10934
    self.cfg.Update(instance, feedback_fn)
10935

    
10936
    return result
10937

    
10938
  _DISK_CONVERSIONS = {
10939
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10940
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10941
    }
10942

    
10943

    
10944
class LUBackupQuery(NoHooksLU):
10945
  """Query the exports list
10946

10947
  """
10948
  REQ_BGL = False
10949

    
10950
  def ExpandNames(self):
10951
    self.needed_locks = {}
10952
    self.share_locks[locking.LEVEL_NODE] = 1
10953
    if not self.op.nodes:
10954
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10955
    else:
10956
      self.needed_locks[locking.LEVEL_NODE] = \
10957
        _GetWantedNodes(self, self.op.nodes)
10958

    
10959
  def Exec(self, feedback_fn):
10960
    """Compute the list of all the exported system images.
10961

10962
    @rtype: dict
10963
    @return: a dictionary with the structure node->(export-list)
10964
        where export-list is a list of the instances exported on
10965
        that node.
10966

10967
    """
10968
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10969
    rpcresult = self.rpc.call_export_list(self.nodes)
10970
    result = {}
10971
    for node in rpcresult:
10972
      if rpcresult[node].fail_msg:
10973
        result[node] = False
10974
      else:
10975
        result[node] = rpcresult[node].payload
10976

    
10977
    return result
10978

    
10979

    
10980
class LUBackupPrepare(NoHooksLU):
10981
  """Prepares an instance for an export and returns useful information.
10982

10983
  """
10984
  REQ_BGL = False
10985

    
10986
  def ExpandNames(self):
10987
    self._ExpandAndLockInstance()
10988

    
10989
  def CheckPrereq(self):
10990
    """Check prerequisites.
10991

10992
    """
10993
    instance_name = self.op.instance_name
10994

    
10995
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10996
    assert self.instance is not None, \
10997
          "Cannot retrieve locked instance %s" % self.op.instance_name
10998
    _CheckNodeOnline(self, self.instance.primary_node)
10999

    
11000
    self._cds = _GetClusterDomainSecret()
11001

    
11002
  def Exec(self, feedback_fn):
11003
    """Prepares an instance for an export.
11004

11005
    """
11006
    instance = self.instance
11007

    
11008
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11009
      salt = utils.GenerateSecret(8)
11010

    
11011
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
11012
      result = self.rpc.call_x509_cert_create(instance.primary_node,
11013
                                              constants.RIE_CERT_VALIDITY)
11014
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
11015

    
11016
      (name, cert_pem) = result.payload
11017

    
11018
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
11019
                                             cert_pem)
11020

    
11021
      return {
11022
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
11023
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
11024
                          salt),
11025
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
11026
        }
11027

    
11028
    return None
11029

    
11030

    
11031
class LUBackupExport(LogicalUnit):
11032
  """Export an instance to an image in the cluster.
11033

11034
  """
11035
  HPATH = "instance-export"
11036
  HTYPE = constants.HTYPE_INSTANCE
11037
  REQ_BGL = False
11038

    
11039
  def CheckArguments(self):
11040
    """Check the arguments.
11041

11042
    """
11043
    self.x509_key_name = self.op.x509_key_name
11044
    self.dest_x509_ca_pem = self.op.destination_x509_ca
11045

    
11046
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
11047
      if not self.x509_key_name:
11048
        raise errors.OpPrereqError("Missing X509 key name for encryption",
11049
                                   errors.ECODE_INVAL)
11050

    
11051
      if not self.dest_x509_ca_pem:
11052
        raise errors.OpPrereqError("Missing destination X509 CA",
11053
                                   errors.ECODE_INVAL)
11054

    
11055
  def ExpandNames(self):
11056
    self._ExpandAndLockInstance()
11057

    
11058
    # Lock all nodes for local exports
11059
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11060
      # FIXME: lock only instance primary and destination node
11061
      #
11062
      # Sad but true, for now we have do lock all nodes, as we don't know where
11063
      # the previous export might be, and in this LU we search for it and
11064
      # remove it from its current node. In the future we could fix this by:
11065
      #  - making a tasklet to search (share-lock all), then create the
11066
      #    new one, then one to remove, after
11067
      #  - removing the removal operation altogether
11068
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11069

    
11070
  def DeclareLocks(self, level):
11071
    """Last minute lock declaration."""
11072
    # All nodes are locked anyway, so nothing to do here.
11073

    
11074
  def BuildHooksEnv(self):
11075
    """Build hooks env.
11076

11077
    This will run on the master, primary node and target node.
11078

11079
    """
11080
    env = {
11081
      "EXPORT_MODE": self.op.mode,
11082
      "EXPORT_NODE": self.op.target_node,
11083
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
11084
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
11085
      # TODO: Generic function for boolean env variables
11086
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
11087
      }
11088

    
11089
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
11090

    
11091
    return env
11092

    
11093
  def BuildHooksNodes(self):
11094
    """Build hooks nodes.
11095

11096
    """
11097
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
11098

    
11099
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11100
      nl.append(self.op.target_node)
11101

    
11102
    return (nl, nl)
11103

    
11104
  def CheckPrereq(self):
11105
    """Check prerequisites.
11106

11107
    This checks that the instance and node names are valid.
11108

11109
    """
11110
    instance_name = self.op.instance_name
11111

    
11112
    self.instance = self.cfg.GetInstanceInfo(instance_name)
11113
    assert self.instance is not None, \
11114
          "Cannot retrieve locked instance %s" % self.op.instance_name
11115
    _CheckNodeOnline(self, self.instance.primary_node)
11116

    
11117
    if (self.op.remove_instance and self.instance.admin_up and
11118
        not self.op.shutdown):
11119
      raise errors.OpPrereqError("Can not remove instance without shutting it"
11120
                                 " down before")
11121

    
11122
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11123
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
11124
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
11125
      assert self.dst_node is not None
11126

    
11127
      _CheckNodeOnline(self, self.dst_node.name)
11128
      _CheckNodeNotDrained(self, self.dst_node.name)
11129

    
11130
      self._cds = None
11131
      self.dest_disk_info = None
11132
      self.dest_x509_ca = None
11133

    
11134
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11135
      self.dst_node = None
11136

    
11137
      if len(self.op.target_node) != len(self.instance.disks):
11138
        raise errors.OpPrereqError(("Received destination information for %s"
11139
                                    " disks, but instance %s has %s disks") %
11140
                                   (len(self.op.target_node), instance_name,
11141
                                    len(self.instance.disks)),
11142
                                   errors.ECODE_INVAL)
11143

    
11144
      cds = _GetClusterDomainSecret()
11145

    
11146
      # Check X509 key name
11147
      try:
11148
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
11149
      except (TypeError, ValueError), err:
11150
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
11151

    
11152
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
11153
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
11154
                                   errors.ECODE_INVAL)
11155

    
11156
      # Load and verify CA
11157
      try:
11158
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
11159
      except OpenSSL.crypto.Error, err:
11160
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
11161
                                   (err, ), errors.ECODE_INVAL)
11162

    
11163
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
11164
      if errcode is not None:
11165
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
11166
                                   (msg, ), errors.ECODE_INVAL)
11167

    
11168
      self.dest_x509_ca = cert
11169

    
11170
      # Verify target information
11171
      disk_info = []
11172
      for idx, disk_data in enumerate(self.op.target_node):
11173
        try:
11174
          (host, port, magic) = \
11175
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
11176
        except errors.GenericError, err:
11177
          raise errors.OpPrereqError("Target info for disk %s: %s" %
11178
                                     (idx, err), errors.ECODE_INVAL)
11179

    
11180
        disk_info.append((host, port, magic))
11181

    
11182
      assert len(disk_info) == len(self.op.target_node)
11183
      self.dest_disk_info = disk_info
11184

    
11185
    else:
11186
      raise errors.ProgrammerError("Unhandled export mode %r" %
11187
                                   self.op.mode)
11188

    
11189
    # instance disk type verification
11190
    # TODO: Implement export support for file-based disks
11191
    for disk in self.instance.disks:
11192
      if disk.dev_type == constants.LD_FILE:
11193
        raise errors.OpPrereqError("Export not supported for instances with"
11194
                                   " file-based disks", errors.ECODE_INVAL)
11195

    
11196
  def _CleanupExports(self, feedback_fn):
11197
    """Removes exports of current instance from all other nodes.
11198

11199
    If an instance in a cluster with nodes A..D was exported to node C, its
11200
    exports will be removed from the nodes A, B and D.
11201

11202
    """
11203
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
11204

    
11205
    nodelist = self.cfg.GetNodeList()
11206
    nodelist.remove(self.dst_node.name)
11207

    
11208
    # on one-node clusters nodelist will be empty after the removal
11209
    # if we proceed the backup would be removed because OpBackupQuery
11210
    # substitutes an empty list with the full cluster node list.
11211
    iname = self.instance.name
11212
    if nodelist:
11213
      feedback_fn("Removing old exports for instance %s" % iname)
11214
      exportlist = self.rpc.call_export_list(nodelist)
11215
      for node in exportlist:
11216
        if exportlist[node].fail_msg:
11217
          continue
11218
        if iname in exportlist[node].payload:
11219
          msg = self.rpc.call_export_remove(node, iname).fail_msg
11220
          if msg:
11221
            self.LogWarning("Could not remove older export for instance %s"
11222
                            " on node %s: %s", iname, node, msg)
11223

    
11224
  def Exec(self, feedback_fn):
11225
    """Export an instance to an image in the cluster.
11226

11227
    """
11228
    assert self.op.mode in constants.EXPORT_MODES
11229

    
11230
    instance = self.instance
11231
    src_node = instance.primary_node
11232

    
11233
    if self.op.shutdown:
11234
      # shutdown the instance, but not the disks
11235
      feedback_fn("Shutting down instance %s" % instance.name)
11236
      result = self.rpc.call_instance_shutdown(src_node, instance,
11237
                                               self.op.shutdown_timeout)
11238
      # TODO: Maybe ignore failures if ignore_remove_failures is set
11239
      result.Raise("Could not shutdown instance %s on"
11240
                   " node %s" % (instance.name, src_node))
11241

    
11242
    # set the disks ID correctly since call_instance_start needs the
11243
    # correct drbd minor to create the symlinks
11244
    for disk in instance.disks:
11245
      self.cfg.SetDiskID(disk, src_node)
11246

    
11247
    activate_disks = (not instance.admin_up)
11248

    
11249
    if activate_disks:
11250
      # Activate the instance disks if we'exporting a stopped instance
11251
      feedback_fn("Activating disks for %s" % instance.name)
11252
      _StartInstanceDisks(self, instance, None)
11253

    
11254
    try:
11255
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
11256
                                                     instance)
11257

    
11258
      helper.CreateSnapshots()
11259
      try:
11260
        if (self.op.shutdown and instance.admin_up and
11261
            not self.op.remove_instance):
11262
          assert not activate_disks
11263
          feedback_fn("Starting instance %s" % instance.name)
11264
          result = self.rpc.call_instance_start(src_node, instance,
11265
                                                None, None, False)
11266
          msg = result.fail_msg
11267
          if msg:
11268
            feedback_fn("Failed to start instance: %s" % msg)
11269
            _ShutdownInstanceDisks(self, instance)
11270
            raise errors.OpExecError("Could not start instance: %s" % msg)
11271

    
11272
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
11273
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
11274
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
11275
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
11276
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
11277

    
11278
          (key_name, _, _) = self.x509_key_name
11279

    
11280
          dest_ca_pem = \
11281
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
11282
                                            self.dest_x509_ca)
11283

    
11284
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
11285
                                                     key_name, dest_ca_pem,
11286
                                                     timeouts)
11287
      finally:
11288
        helper.Cleanup()
11289

    
11290
      # Check for backwards compatibility
11291
      assert len(dresults) == len(instance.disks)
11292
      assert compat.all(isinstance(i, bool) for i in dresults), \
11293
             "Not all results are boolean: %r" % dresults
11294

    
11295
    finally:
11296
      if activate_disks:
11297
        feedback_fn("Deactivating disks for %s" % instance.name)
11298
        _ShutdownInstanceDisks(self, instance)
11299

    
11300
    if not (compat.all(dresults) and fin_resu):
11301
      failures = []
11302
      if not fin_resu:
11303
        failures.append("export finalization")
11304
      if not compat.all(dresults):
11305
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
11306
                               if not dsk)
11307
        failures.append("disk export: disk(s) %s" % fdsk)
11308

    
11309
      raise errors.OpExecError("Export failed, errors in %s" %
11310
                               utils.CommaJoin(failures))
11311

    
11312
    # At this point, the export was successful, we can cleanup/finish
11313

    
11314
    # Remove instance if requested
11315
    if self.op.remove_instance:
11316
      feedback_fn("Removing instance %s" % instance.name)
11317
      _RemoveInstance(self, feedback_fn, instance,
11318
                      self.op.ignore_remove_failures)
11319

    
11320
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
11321
      self._CleanupExports(feedback_fn)
11322

    
11323
    return fin_resu, dresults
11324

    
11325

    
11326
class LUBackupRemove(NoHooksLU):
11327
  """Remove exports related to the named instance.
11328

11329
  """
11330
  REQ_BGL = False
11331

    
11332
  def ExpandNames(self):
11333
    self.needed_locks = {}
11334
    # We need all nodes to be locked in order for RemoveExport to work, but we
11335
    # don't need to lock the instance itself, as nothing will happen to it (and
11336
    # we can remove exports also for a removed instance)
11337
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
11338

    
11339
  def Exec(self, feedback_fn):
11340
    """Remove any export.
11341

11342
    """
11343
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
11344
    # If the instance was not found we'll try with the name that was passed in.
11345
    # This will only work if it was an FQDN, though.
11346
    fqdn_warn = False
11347
    if not instance_name:
11348
      fqdn_warn = True
11349
      instance_name = self.op.instance_name
11350

    
11351
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
11352
    exportlist = self.rpc.call_export_list(locked_nodes)
11353
    found = False
11354
    for node in exportlist:
11355
      msg = exportlist[node].fail_msg
11356
      if msg:
11357
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
11358
        continue
11359
      if instance_name in exportlist[node].payload:
11360
        found = True
11361
        result = self.rpc.call_export_remove(node, instance_name)
11362
        msg = result.fail_msg
11363
        if msg:
11364
          logging.error("Could not remove export for instance %s"
11365
                        " on node %s: %s", instance_name, node, msg)
11366

    
11367
    if fqdn_warn and not found:
11368
      feedback_fn("Export not found. If trying to remove an export belonging"
11369
                  " to a deleted instance please use its Fully Qualified"
11370
                  " Domain Name.")
11371

    
11372

    
11373
class LUGroupAdd(LogicalUnit):
11374
  """Logical unit for creating node groups.
11375

11376
  """
11377
  HPATH = "group-add"
11378
  HTYPE = constants.HTYPE_GROUP
11379
  REQ_BGL = False
11380

    
11381
  def ExpandNames(self):
11382
    # We need the new group's UUID here so that we can create and acquire the
11383
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
11384
    # that it should not check whether the UUID exists in the configuration.
11385
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
11386
    self.needed_locks = {}
11387
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11388

    
11389
  def CheckPrereq(self):
11390
    """Check prerequisites.
11391

11392
    This checks that the given group name is not an existing node group
11393
    already.
11394

11395
    """
11396
    try:
11397
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11398
    except errors.OpPrereqError:
11399
      pass
11400
    else:
11401
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
11402
                                 " node group (UUID: %s)" %
11403
                                 (self.op.group_name, existing_uuid),
11404
                                 errors.ECODE_EXISTS)
11405

    
11406
    if self.op.ndparams:
11407
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11408

    
11409
  def BuildHooksEnv(self):
11410
    """Build hooks env.
11411

11412
    """
11413
    return {
11414
      "GROUP_NAME": self.op.group_name,
11415
      }
11416

    
11417
  def BuildHooksNodes(self):
11418
    """Build hooks nodes.
11419

11420
    """
11421
    mn = self.cfg.GetMasterNode()
11422
    return ([mn], [mn])
11423

    
11424
  def Exec(self, feedback_fn):
11425
    """Add the node group to the cluster.
11426

11427
    """
11428
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11429
                                  uuid=self.group_uuid,
11430
                                  alloc_policy=self.op.alloc_policy,
11431
                                  ndparams=self.op.ndparams)
11432

    
11433
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11434
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11435

    
11436

    
11437
class LUGroupAssignNodes(NoHooksLU):
11438
  """Logical unit for assigning nodes to groups.
11439

11440
  """
11441
  REQ_BGL = False
11442

    
11443
  def ExpandNames(self):
11444
    # These raise errors.OpPrereqError on their own:
11445
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11446
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11447

    
11448
    # We want to lock all the affected nodes and groups. We have readily
11449
    # available the list of nodes, and the *destination* group. To gather the
11450
    # list of "source" groups, we need to fetch node information later on.
11451
    self.needed_locks = {
11452
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11453
      locking.LEVEL_NODE: self.op.nodes,
11454
      }
11455

    
11456
  def DeclareLocks(self, level):
11457
    if level == locking.LEVEL_NODEGROUP:
11458
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11459

    
11460
      # Try to get all affected nodes' groups without having the group or node
11461
      # lock yet. Needs verification later in the code flow.
11462
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11463

    
11464
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11465

    
11466
  def CheckPrereq(self):
11467
    """Check prerequisites.
11468

11469
    """
11470
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11471
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11472
            frozenset(self.op.nodes))
11473

    
11474
    expected_locks = (set([self.group_uuid]) |
11475
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11476
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11477
    if actual_locks != expected_locks:
11478
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11479
                               " current groups are '%s', used to be '%s'" %
11480
                               (utils.CommaJoin(expected_locks),
11481
                                utils.CommaJoin(actual_locks)))
11482

    
11483
    self.node_data = self.cfg.GetAllNodesInfo()
11484
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11485
    instance_data = self.cfg.GetAllInstancesInfo()
11486

    
11487
    if self.group is None:
11488
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11489
                               (self.op.group_name, self.group_uuid))
11490

    
11491
    (new_splits, previous_splits) = \
11492
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11493
                                             for node in self.op.nodes],
11494
                                            self.node_data, instance_data)
11495

    
11496
    if new_splits:
11497
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11498

    
11499
      if not self.op.force:
11500
        raise errors.OpExecError("The following instances get split by this"
11501
                                 " change and --force was not given: %s" %
11502
                                 fmt_new_splits)
11503
      else:
11504
        self.LogWarning("This operation will split the following instances: %s",
11505
                        fmt_new_splits)
11506

    
11507
        if previous_splits:
11508
          self.LogWarning("In addition, these already-split instances continue"
11509
                          " to be split across groups: %s",
11510
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11511

    
11512
  def Exec(self, feedback_fn):
11513
    """Assign nodes to a new group.
11514

11515
    """
11516
    for node in self.op.nodes:
11517
      self.node_data[node].group = self.group_uuid
11518

    
11519
    # FIXME: Depends on side-effects of modifying the result of
11520
    # C{cfg.GetAllNodesInfo}
11521

    
11522
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11523

    
11524
  @staticmethod
11525
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11526
    """Check for split instances after a node assignment.
11527

11528
    This method considers a series of node assignments as an atomic operation,
11529
    and returns information about split instances after applying the set of
11530
    changes.
11531

11532
    In particular, it returns information about newly split instances, and
11533
    instances that were already split, and remain so after the change.
11534

11535
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11536
    considered.
11537

11538
    @type changes: list of (node_name, new_group_uuid) pairs.
11539
    @param changes: list of node assignments to consider.
11540
    @param node_data: a dict with data for all nodes
11541
    @param instance_data: a dict with all instances to consider
11542
    @rtype: a two-tuple
11543
    @return: a list of instances that were previously okay and result split as a
11544
      consequence of this change, and a list of instances that were previously
11545
      split and this change does not fix.
11546

11547
    """
11548
    changed_nodes = dict((node, group) for node, group in changes
11549
                         if node_data[node].group != group)
11550

    
11551
    all_split_instances = set()
11552
    previously_split_instances = set()
11553

    
11554
    def InstanceNodes(instance):
11555
      return [instance.primary_node] + list(instance.secondary_nodes)
11556

    
11557
    for inst in instance_data.values():
11558
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11559
        continue
11560

    
11561
      instance_nodes = InstanceNodes(inst)
11562

    
11563
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11564
        previously_split_instances.add(inst.name)
11565

    
11566
      if len(set(changed_nodes.get(node, node_data[node].group)
11567
                 for node in instance_nodes)) > 1:
11568
        all_split_instances.add(inst.name)
11569

    
11570
    return (list(all_split_instances - previously_split_instances),
11571
            list(previously_split_instances & all_split_instances))
11572

    
11573

    
11574
class _GroupQuery(_QueryBase):
11575
  FIELDS = query.GROUP_FIELDS
11576

    
11577
  def ExpandNames(self, lu):
11578
    lu.needed_locks = {}
11579

    
11580
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11581
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11582

    
11583
    if not self.names:
11584
      self.wanted = [name_to_uuid[name]
11585
                     for name in utils.NiceSort(name_to_uuid.keys())]
11586
    else:
11587
      # Accept names to be either names or UUIDs.
11588
      missing = []
11589
      self.wanted = []
11590
      all_uuid = frozenset(self._all_groups.keys())
11591

    
11592
      for name in self.names:
11593
        if name in all_uuid:
11594
          self.wanted.append(name)
11595
        elif name in name_to_uuid:
11596
          self.wanted.append(name_to_uuid[name])
11597
        else:
11598
          missing.append(name)
11599

    
11600
      if missing:
11601
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11602
                                   utils.CommaJoin(missing),
11603
                                   errors.ECODE_NOENT)
11604

    
11605
  def DeclareLocks(self, lu, level):
11606
    pass
11607

    
11608
  def _GetQueryData(self, lu):
11609
    """Computes the list of node groups and their attributes.
11610

11611
    """
11612
    do_nodes = query.GQ_NODE in self.requested_data
11613
    do_instances = query.GQ_INST in self.requested_data
11614

    
11615
    group_to_nodes = None
11616
    group_to_instances = None
11617

    
11618
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11619
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11620
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11621
    # instance->node. Hence, we will need to process nodes even if we only need
11622
    # instance information.
11623
    if do_nodes or do_instances:
11624
      all_nodes = lu.cfg.GetAllNodesInfo()
11625
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11626
      node_to_group = {}
11627

    
11628
      for node in all_nodes.values():
11629
        if node.group in group_to_nodes:
11630
          group_to_nodes[node.group].append(node.name)
11631
          node_to_group[node.name] = node.group
11632

    
11633
      if do_instances:
11634
        all_instances = lu.cfg.GetAllInstancesInfo()
11635
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11636

    
11637
        for instance in all_instances.values():
11638
          node = instance.primary_node
11639
          if node in node_to_group:
11640
            group_to_instances[node_to_group[node]].append(instance.name)
11641

    
11642
        if not do_nodes:
11643
          # Do not pass on node information if it was not requested.
11644
          group_to_nodes = None
11645

    
11646
    return query.GroupQueryData([self._all_groups[uuid]
11647
                                 for uuid in self.wanted],
11648
                                group_to_nodes, group_to_instances)
11649

    
11650

    
11651
class LUGroupQuery(NoHooksLU):
11652
  """Logical unit for querying node groups.
11653

11654
  """
11655
  REQ_BGL = False
11656

    
11657
  def CheckArguments(self):
11658
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11659
                          self.op.output_fields, False)
11660

    
11661
  def ExpandNames(self):
11662
    self.gq.ExpandNames(self)
11663

    
11664
  def Exec(self, feedback_fn):
11665
    return self.gq.OldStyleQuery(self)
11666

    
11667

    
11668
class LUGroupSetParams(LogicalUnit):
11669
  """Modifies the parameters of a node group.
11670

11671
  """
11672
  HPATH = "group-modify"
11673
  HTYPE = constants.HTYPE_GROUP
11674
  REQ_BGL = False
11675

    
11676
  def CheckArguments(self):
11677
    all_changes = [
11678
      self.op.ndparams,
11679
      self.op.alloc_policy,
11680
      ]
11681

    
11682
    if all_changes.count(None) == len(all_changes):
11683
      raise errors.OpPrereqError("Please pass at least one modification",
11684
                                 errors.ECODE_INVAL)
11685

    
11686
  def ExpandNames(self):
11687
    # This raises errors.OpPrereqError on its own:
11688
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11689

    
11690
    self.needed_locks = {
11691
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11692
      }
11693

    
11694
  def CheckPrereq(self):
11695
    """Check prerequisites.
11696

11697
    """
11698
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11699

    
11700
    if self.group is None:
11701
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11702
                               (self.op.group_name, self.group_uuid))
11703

    
11704
    if self.op.ndparams:
11705
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11706
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11707
      self.new_ndparams = new_ndparams
11708

    
11709
  def BuildHooksEnv(self):
11710
    """Build hooks env.
11711

11712
    """
11713
    return {
11714
      "GROUP_NAME": self.op.group_name,
11715
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11716
      }
11717

    
11718
  def BuildHooksNodes(self):
11719
    """Build hooks nodes.
11720

11721
    """
11722
    mn = self.cfg.GetMasterNode()
11723
    return ([mn], [mn])
11724

    
11725
  def Exec(self, feedback_fn):
11726
    """Modifies the node group.
11727

11728
    """
11729
    result = []
11730

    
11731
    if self.op.ndparams:
11732
      self.group.ndparams = self.new_ndparams
11733
      result.append(("ndparams", str(self.group.ndparams)))
11734

    
11735
    if self.op.alloc_policy:
11736
      self.group.alloc_policy = self.op.alloc_policy
11737

    
11738
    self.cfg.Update(self.group, feedback_fn)
11739
    return result
11740

    
11741

    
11742

    
11743
class LUGroupRemove(LogicalUnit):
11744
  HPATH = "group-remove"
11745
  HTYPE = constants.HTYPE_GROUP
11746
  REQ_BGL = False
11747

    
11748
  def ExpandNames(self):
11749
    # This will raises errors.OpPrereqError on its own:
11750
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11751
    self.needed_locks = {
11752
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11753
      }
11754

    
11755
  def CheckPrereq(self):
11756
    """Check prerequisites.
11757

11758
    This checks that the given group name exists as a node group, that is
11759
    empty (i.e., contains no nodes), and that is not the last group of the
11760
    cluster.
11761

11762
    """
11763
    # Verify that the group is empty.
11764
    group_nodes = [node.name
11765
                   for node in self.cfg.GetAllNodesInfo().values()
11766
                   if node.group == self.group_uuid]
11767

    
11768
    if group_nodes:
11769
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11770
                                 " nodes: %s" %
11771
                                 (self.op.group_name,
11772
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11773
                                 errors.ECODE_STATE)
11774

    
11775
    # Verify the cluster would not be left group-less.
11776
    if len(self.cfg.GetNodeGroupList()) == 1:
11777
      raise errors.OpPrereqError("Group '%s' is the only group,"
11778
                                 " cannot be removed" %
11779
                                 self.op.group_name,
11780
                                 errors.ECODE_STATE)
11781

    
11782
  def BuildHooksEnv(self):
11783
    """Build hooks env.
11784

11785
    """
11786
    return {
11787
      "GROUP_NAME": self.op.group_name,
11788
      }
11789

    
11790
  def BuildHooksNodes(self):
11791
    """Build hooks nodes.
11792

11793
    """
11794
    mn = self.cfg.GetMasterNode()
11795
    return ([mn], [mn])
11796

    
11797
  def Exec(self, feedback_fn):
11798
    """Remove the node group.
11799

11800
    """
11801
    try:
11802
      self.cfg.RemoveNodeGroup(self.group_uuid)
11803
    except errors.ConfigurationError:
11804
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11805
                               (self.op.group_name, self.group_uuid))
11806

    
11807
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11808

    
11809

    
11810
class LUGroupRename(LogicalUnit):
11811
  HPATH = "group-rename"
11812
  HTYPE = constants.HTYPE_GROUP
11813
  REQ_BGL = False
11814

    
11815
  def ExpandNames(self):
11816
    # This raises errors.OpPrereqError on its own:
11817
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11818

    
11819
    self.needed_locks = {
11820
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11821
      }
11822

    
11823
  def CheckPrereq(self):
11824
    """Check prerequisites.
11825

11826
    Ensures requested new name is not yet used.
11827

11828
    """
11829
    try:
11830
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11831
    except errors.OpPrereqError:
11832
      pass
11833
    else:
11834
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11835
                                 " node group (UUID: %s)" %
11836
                                 (self.op.new_name, new_name_uuid),
11837
                                 errors.ECODE_EXISTS)
11838

    
11839
  def BuildHooksEnv(self):
11840
    """Build hooks env.
11841

11842
    """
11843
    return {
11844
      "OLD_NAME": self.op.group_name,
11845
      "NEW_NAME": self.op.new_name,
11846
      }
11847

    
11848
  def BuildHooksNodes(self):
11849
    """Build hooks nodes.
11850

11851
    """
11852
    mn = self.cfg.GetMasterNode()
11853

    
11854
    all_nodes = self.cfg.GetAllNodesInfo()
11855
    all_nodes.pop(mn, None)
11856

    
11857
    run_nodes = [mn]
11858
    run_nodes.extend(node.name for node in all_nodes.values()
11859
                     if node.group == self.group_uuid)
11860

    
11861
    return (run_nodes, run_nodes)
11862

    
11863
  def Exec(self, feedback_fn):
11864
    """Rename the node group.
11865

11866
    """
11867
    group = self.cfg.GetNodeGroup(self.group_uuid)
11868

    
11869
    if group is None:
11870
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11871
                               (self.op.group_name, self.group_uuid))
11872

    
11873
    group.name = self.op.new_name
11874
    self.cfg.Update(group, feedback_fn)
11875

    
11876
    return self.op.new_name
11877

    
11878

    
11879
class LUGroupEvacuate(LogicalUnit):
11880
  HPATH = "group-evacuate"
11881
  HTYPE = constants.HTYPE_GROUP
11882
  REQ_BGL = False
11883

    
11884
  def ExpandNames(self):
11885
    # This raises errors.OpPrereqError on its own:
11886
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11887

    
11888
    if self.op.target_groups:
11889
      self.req_target_uuids = map(self.cfg.LookupNodeGroup,
11890
                                  self.op.target_groups)
11891
    else:
11892
      self.req_target_uuids = []
11893

    
11894
    if self.group_uuid in self.req_target_uuids:
11895
      raise errors.OpPrereqError("Group to be evacuated (%s) can not be used"
11896
                                 " as a target group (targets are %s)" %
11897
                                 (self.group_uuid,
11898
                                  utils.CommaJoin(self.req_target_uuids)),
11899
                                 errors.ECODE_INVAL)
11900

    
11901
    if not self.op.iallocator:
11902
      # Use default iallocator
11903
      self.op.iallocator = self.cfg.GetDefaultIAllocator()
11904

    
11905
    if not self.op.iallocator:
11906
      raise errors.OpPrereqError("No iallocator was specified, neither in the"
11907
                                 " opcode nor as a cluster-wide default",
11908
                                 errors.ECODE_INVAL)
11909

    
11910
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11911
    self.needed_locks = {
11912
      locking.LEVEL_INSTANCE: [],
11913
      locking.LEVEL_NODEGROUP: [],
11914
      locking.LEVEL_NODE: [],
11915
      }
11916

    
11917
  def DeclareLocks(self, level):
11918
    if level == locking.LEVEL_INSTANCE:
11919
      assert not self.needed_locks[locking.LEVEL_INSTANCE]
11920

    
11921
      # Lock instances optimistically, needs verification once node and group
11922
      # locks have been acquired
11923
      self.needed_locks[locking.LEVEL_INSTANCE] = \
11924
        self.cfg.GetNodeGroupInstances(self.group_uuid)
11925

    
11926
    elif level == locking.LEVEL_NODEGROUP:
11927
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
11928

    
11929
      if self.req_target_uuids:
11930
        lock_groups = set([self.group_uuid] + self.req_target_uuids)
11931

    
11932
        # Lock all groups used by instances optimistically; this requires going
11933
        # via the node before it's locked, requiring verification later on
11934
        lock_groups.update(group_uuid
11935
                           for instance_name in
11936
                             self.glm.list_owned(locking.LEVEL_INSTANCE)
11937
                           for group_uuid in
11938
                             self.cfg.GetInstanceNodeGroups(instance_name))
11939
      else:
11940
        # No target groups, need to lock all of them
11941
        lock_groups = locking.ALL_SET
11942

    
11943
      self.needed_locks[locking.LEVEL_NODEGROUP] = lock_groups
11944

    
11945
    elif level == locking.LEVEL_NODE:
11946
      # This will only lock the nodes in the group to be evacuated which
11947
      # contain actual instances
11948
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
11949
      self._LockInstancesNodes()
11950

    
11951
      # Lock all nodes in group to be evacuated
11952
      assert self.group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
11953
      member_nodes = self.cfg.GetNodeGroup(self.group_uuid).members
11954
      self.needed_locks[locking.LEVEL_NODE].extend(member_nodes)
11955

    
11956
  def CheckPrereq(self):
11957
    owned_instances = frozenset(self.glm.list_owned(locking.LEVEL_INSTANCE))
11958
    owned_groups = frozenset(self.glm.list_owned(locking.LEVEL_NODEGROUP))
11959
    owned_nodes = frozenset(self.glm.list_owned(locking.LEVEL_NODE))
11960

    
11961
    assert owned_groups.issuperset(self.req_target_uuids)
11962
    assert self.group_uuid in owned_groups
11963

    
11964
    # Check if locked instances are still correct
11965
    wanted_instances = self.cfg.GetNodeGroupInstances(self.group_uuid)
11966
    if owned_instances != wanted_instances:
11967
      raise errors.OpPrereqError("Instances in node group to be evacuated (%s)"
11968
                                 " changed since locks were acquired, wanted"
11969
                                 " %s, have %s; retry the operation" %
11970
                                 (self.group_uuid,
11971
                                  utils.CommaJoin(wanted_instances),
11972
                                  utils.CommaJoin(owned_instances)),
11973
                                 errors.ECODE_STATE)
11974

    
11975
    # Get instance information
11976
    self.instances = dict((name, self.cfg.GetInstanceInfo(name))
11977
                          for name in owned_instances)
11978

    
11979
    # Check if node groups for locked instances are still correct
11980
    for instance_name in owned_instances:
11981
      inst = self.instances[instance_name]
11982
      assert self.group_uuid in self.cfg.GetInstanceNodeGroups(instance_name), \
11983
        "Instance %s has no node in group %s" % (instance_name, self.group_uuid)
11984
      assert owned_nodes.issuperset(inst.all_nodes), \
11985
        "Instance %s's nodes changed while we kept the lock" % instance_name
11986

    
11987
      inst_groups = self.cfg.GetInstanceNodeGroups(instance_name)
11988
      if not owned_groups.issuperset(inst_groups):
11989
        raise errors.OpPrereqError("Instance's node groups changed since locks"
11990
                                   " were acquired, current groups are '%s',"
11991
                                   " owning groups '%s'; retry the operation" %
11992
                                   (utils.CommaJoin(inst_groups),
11993
                                    utils.CommaJoin(owned_groups)),
11994
                                   errors.ECODE_STATE)
11995

    
11996
    if self.req_target_uuids:
11997
      # User requested specific target groups
11998
      self.target_uuids = self.req_target_uuids
11999
    else:
12000
      # All groups except the one to be evacuated are potential targets
12001
      self.target_uuids = [group_uuid for group_uuid in owned_groups
12002
                           if group_uuid != self.group_uuid]
12003

    
12004
      if not self.target_uuids:
12005
        raise errors.OpExecError("There are no possible target groups")
12006

    
12007
  def BuildHooksEnv(self):
12008
    """Build hooks env.
12009

12010
    """
12011
    return {
12012
      "GROUP_NAME": self.op.group_name,
12013
      "TARGET_GROUPS": " ".join(self.target_uuids),
12014
      }
12015

    
12016
  def BuildHooksNodes(self):
12017
    """Build hooks nodes.
12018

12019
    """
12020
    mn = self.cfg.GetMasterNode()
12021

    
12022
    assert self.group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
12023

    
12024
    run_nodes = [mn] + self.cfg.GetNodeGroup(self.group_uuid).members
12025

    
12026
    return (run_nodes, run_nodes)
12027

    
12028
  def Exec(self, feedback_fn):
12029
    instances = list(self.glm.list_owned(locking.LEVEL_INSTANCE))
12030

    
12031
    assert self.group_uuid not in self.target_uuids
12032

    
12033
    ial = IAllocator(self.cfg, self.rpc, constants.IALLOCATOR_MODE_CHG_GROUP,
12034
                     instances=instances, target_groups=self.target_uuids)
12035

    
12036
    ial.Run(self.op.iallocator)
12037

    
12038
    if not ial.success:
12039
      raise errors.OpPrereqError("Can't compute group evacuation using"
12040
                                 " iallocator '%s': %s" %
12041
                                 (self.op.iallocator, ial.info),
12042
                                 errors.ECODE_NORES)
12043

    
12044
    jobs = _LoadNodeEvacResult(self, ial.result, self.op.early_release, False)
12045

    
12046
    self.LogInfo("Iallocator returned %s job(s) for evacuating node group %s",
12047
                 len(jobs), self.op.group_name)
12048

    
12049
    return ResultWithJobs(jobs)
12050

    
12051

    
12052
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
12053
  """Generic tags LU.
12054

12055
  This is an abstract class which is the parent of all the other tags LUs.
12056

12057
  """
12058
  def ExpandNames(self):
12059
    self.group_uuid = None
12060
    self.needed_locks = {}
12061
    if self.op.kind == constants.TAG_NODE:
12062
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
12063
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
12064
    elif self.op.kind == constants.TAG_INSTANCE:
12065
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
12066
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
12067
    elif self.op.kind == constants.TAG_NODEGROUP:
12068
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
12069

    
12070
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
12071
    # not possible to acquire the BGL based on opcode parameters)
12072

    
12073
  def CheckPrereq(self):
12074
    """Check prerequisites.
12075

12076
    """
12077
    if self.op.kind == constants.TAG_CLUSTER:
12078
      self.target = self.cfg.GetClusterInfo()
12079
    elif self.op.kind == constants.TAG_NODE:
12080
      self.target = self.cfg.GetNodeInfo(self.op.name)
12081
    elif self.op.kind == constants.TAG_INSTANCE:
12082
      self.target = self.cfg.GetInstanceInfo(self.op.name)
12083
    elif self.op.kind == constants.TAG_NODEGROUP:
12084
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
12085
    else:
12086
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
12087
                                 str(self.op.kind), errors.ECODE_INVAL)
12088

    
12089

    
12090
class LUTagsGet(TagsLU):
12091
  """Returns the tags of a given object.
12092

12093
  """
12094
  REQ_BGL = False
12095

    
12096
  def ExpandNames(self):
12097
    TagsLU.ExpandNames(self)
12098

    
12099
    # Share locks as this is only a read operation
12100
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
12101

    
12102
  def Exec(self, feedback_fn):
12103
    """Returns the tag list.
12104

12105
    """
12106
    return list(self.target.GetTags())
12107

    
12108

    
12109
class LUTagsSearch(NoHooksLU):
12110
  """Searches the tags for a given pattern.
12111

12112
  """
12113
  REQ_BGL = False
12114

    
12115
  def ExpandNames(self):
12116
    self.needed_locks = {}
12117

    
12118
  def CheckPrereq(self):
12119
    """Check prerequisites.
12120

12121
    This checks the pattern passed for validity by compiling it.
12122

12123
    """
12124
    try:
12125
      self.re = re.compile(self.op.pattern)
12126
    except re.error, err:
12127
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
12128
                                 (self.op.pattern, err), errors.ECODE_INVAL)
12129

    
12130
  def Exec(self, feedback_fn):
12131
    """Returns the tag list.
12132

12133
    """
12134
    cfg = self.cfg
12135
    tgts = [("/cluster", cfg.GetClusterInfo())]
12136
    ilist = cfg.GetAllInstancesInfo().values()
12137
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
12138
    nlist = cfg.GetAllNodesInfo().values()
12139
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
12140
    tgts.extend(("/nodegroup/%s" % n.name, n)
12141
                for n in cfg.GetAllNodeGroupsInfo().values())
12142
    results = []
12143
    for path, target in tgts:
12144
      for tag in target.GetTags():
12145
        if self.re.search(tag):
12146
          results.append((path, tag))
12147
    return results
12148

    
12149

    
12150
class LUTagsSet(TagsLU):
12151
  """Sets a tag on a given object.
12152

12153
  """
12154
  REQ_BGL = False
12155

    
12156
  def CheckPrereq(self):
12157
    """Check prerequisites.
12158

12159
    This checks the type and length of the tag name and value.
12160

12161
    """
12162
    TagsLU.CheckPrereq(self)
12163
    for tag in self.op.tags:
12164
      objects.TaggableObject.ValidateTag(tag)
12165

    
12166
  def Exec(self, feedback_fn):
12167
    """Sets the tag.
12168

12169
    """
12170
    try:
12171
      for tag in self.op.tags:
12172
        self.target.AddTag(tag)
12173
    except errors.TagError, err:
12174
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
12175
    self.cfg.Update(self.target, feedback_fn)
12176

    
12177

    
12178
class LUTagsDel(TagsLU):
12179
  """Delete a list of tags from a given object.
12180

12181
  """
12182
  REQ_BGL = False
12183

    
12184
  def CheckPrereq(self):
12185
    """Check prerequisites.
12186

12187
    This checks that we have the given tag.
12188

12189
    """
12190
    TagsLU.CheckPrereq(self)
12191
    for tag in self.op.tags:
12192
      objects.TaggableObject.ValidateTag(tag)
12193
    del_tags = frozenset(self.op.tags)
12194
    cur_tags = self.target.GetTags()
12195

    
12196
    diff_tags = del_tags - cur_tags
12197
    if diff_tags:
12198
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
12199
      raise errors.OpPrereqError("Tag(s) %s not found" %
12200
                                 (utils.CommaJoin(diff_names), ),
12201
                                 errors.ECODE_NOENT)
12202

    
12203
  def Exec(self, feedback_fn):
12204
    """Remove the tag from the object.
12205

12206
    """
12207
    for tag in self.op.tags:
12208
      self.target.RemoveTag(tag)
12209
    self.cfg.Update(self.target, feedback_fn)
12210

    
12211

    
12212
class LUTestDelay(NoHooksLU):
12213
  """Sleep for a specified amount of time.
12214

12215
  This LU sleeps on the master and/or nodes for a specified amount of
12216
  time.
12217

12218
  """
12219
  REQ_BGL = False
12220

    
12221
  def ExpandNames(self):
12222
    """Expand names and set required locks.
12223

12224
    This expands the node list, if any.
12225

12226
    """
12227
    self.needed_locks = {}
12228
    if self.op.on_nodes:
12229
      # _GetWantedNodes can be used here, but is not always appropriate to use
12230
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
12231
      # more information.
12232
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
12233
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
12234

    
12235
  def _TestDelay(self):
12236
    """Do the actual sleep.
12237

12238
    """
12239
    if self.op.on_master:
12240
      if not utils.TestDelay(self.op.duration):
12241
        raise errors.OpExecError("Error during master delay test")
12242
    if self.op.on_nodes:
12243
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
12244
      for node, node_result in result.items():
12245
        node_result.Raise("Failure during rpc call to node %s" % node)
12246

    
12247
  def Exec(self, feedback_fn):
12248
    """Execute the test delay opcode, with the wanted repetitions.
12249

12250
    """
12251
    if self.op.repeat == 0:
12252
      self._TestDelay()
12253
    else:
12254
      top_value = self.op.repeat - 1
12255
      for i in range(self.op.repeat):
12256
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
12257
        self._TestDelay()
12258

    
12259

    
12260
class LUTestJqueue(NoHooksLU):
12261
  """Utility LU to test some aspects of the job queue.
12262

12263
  """
12264
  REQ_BGL = False
12265

    
12266
  # Must be lower than default timeout for WaitForJobChange to see whether it
12267
  # notices changed jobs
12268
  _CLIENT_CONNECT_TIMEOUT = 20.0
12269
  _CLIENT_CONFIRM_TIMEOUT = 60.0
12270

    
12271
  @classmethod
12272
  def _NotifyUsingSocket(cls, cb, errcls):
12273
    """Opens a Unix socket and waits for another program to connect.
12274

12275
    @type cb: callable
12276
    @param cb: Callback to send socket name to client
12277
    @type errcls: class
12278
    @param errcls: Exception class to use for errors
12279

12280
    """
12281
    # Using a temporary directory as there's no easy way to create temporary
12282
    # sockets without writing a custom loop around tempfile.mktemp and
12283
    # socket.bind
12284
    tmpdir = tempfile.mkdtemp()
12285
    try:
12286
      tmpsock = utils.PathJoin(tmpdir, "sock")
12287

    
12288
      logging.debug("Creating temporary socket at %s", tmpsock)
12289
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
12290
      try:
12291
        sock.bind(tmpsock)
12292
        sock.listen(1)
12293

    
12294
        # Send details to client
12295
        cb(tmpsock)
12296

    
12297
        # Wait for client to connect before continuing
12298
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
12299
        try:
12300
          (conn, _) = sock.accept()
12301
        except socket.error, err:
12302
          raise errcls("Client didn't connect in time (%s)" % err)
12303
      finally:
12304
        sock.close()
12305
    finally:
12306
      # Remove as soon as client is connected
12307
      shutil.rmtree(tmpdir)
12308

    
12309
    # Wait for client to close
12310
    try:
12311
      try:
12312
        # pylint: disable-msg=E1101
12313
        # Instance of '_socketobject' has no ... member
12314
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
12315
        conn.recv(1)
12316
      except socket.error, err:
12317
        raise errcls("Client failed to confirm notification (%s)" % err)
12318
    finally:
12319
      conn.close()
12320

    
12321
  def _SendNotification(self, test, arg, sockname):
12322
    """Sends a notification to the client.
12323

12324
    @type test: string
12325
    @param test: Test name
12326
    @param arg: Test argument (depends on test)
12327
    @type sockname: string
12328
    @param sockname: Socket path
12329

12330
    """
12331
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
12332

    
12333
  def _Notify(self, prereq, test, arg):
12334
    """Notifies the client of a test.
12335

12336
    @type prereq: bool
12337
    @param prereq: Whether this is a prereq-phase test
12338
    @type test: string
12339
    @param test: Test name
12340
    @param arg: Test argument (depends on test)
12341

12342
    """
12343
    if prereq:
12344
      errcls = errors.OpPrereqError
12345
    else:
12346
      errcls = errors.OpExecError
12347

    
12348
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
12349
                                                  test, arg),
12350
                                   errcls)
12351

    
12352
  def CheckArguments(self):
12353
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
12354
    self.expandnames_calls = 0
12355

    
12356
  def ExpandNames(self):
12357
    checkargs_calls = getattr(self, "checkargs_calls", 0)
12358
    if checkargs_calls < 1:
12359
      raise errors.ProgrammerError("CheckArguments was not called")
12360

    
12361
    self.expandnames_calls += 1
12362

    
12363
    if self.op.notify_waitlock:
12364
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
12365

    
12366
    self.LogInfo("Expanding names")
12367

    
12368
    # Get lock on master node (just to get a lock, not for a particular reason)
12369
    self.needed_locks = {
12370
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
12371
      }
12372

    
12373
  def Exec(self, feedback_fn):
12374
    if self.expandnames_calls < 1:
12375
      raise errors.ProgrammerError("ExpandNames was not called")
12376

    
12377
    if self.op.notify_exec:
12378
      self._Notify(False, constants.JQT_EXEC, None)
12379

    
12380
    self.LogInfo("Executing")
12381

    
12382
    if self.op.log_messages:
12383
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
12384
      for idx, msg in enumerate(self.op.log_messages):
12385
        self.LogInfo("Sending log message %s", idx + 1)
12386
        feedback_fn(constants.JQT_MSGPREFIX + msg)
12387
        # Report how many test messages have been sent
12388
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
12389

    
12390
    if self.op.fail:
12391
      raise errors.OpExecError("Opcode failure was requested")
12392

    
12393
    return True
12394

    
12395

    
12396
class IAllocator(object):
12397
  """IAllocator framework.
12398

12399
  An IAllocator instance has three sets of attributes:
12400
    - cfg that is needed to query the cluster
12401
    - input data (all members of the _KEYS class attribute are required)
12402
    - four buffer attributes (in|out_data|text), that represent the
12403
      input (to the external script) in text and data structure format,
12404
      and the output from it, again in two formats
12405
    - the result variables from the script (success, info, nodes) for
12406
      easy usage
12407

12408
  """
12409
  # pylint: disable-msg=R0902
12410
  # lots of instance attributes
12411

    
12412
  def __init__(self, cfg, rpc, mode, **kwargs):
12413
    self.cfg = cfg
12414
    self.rpc = rpc
12415
    # init buffer variables
12416
    self.in_text = self.out_text = self.in_data = self.out_data = None
12417
    # init all input fields so that pylint is happy
12418
    self.mode = mode
12419
    self.memory = self.disks = self.disk_template = None
12420
    self.os = self.tags = self.nics = self.vcpus = None
12421
    self.hypervisor = None
12422
    self.relocate_from = None
12423
    self.name = None
12424
    self.evac_nodes = None
12425
    self.instances = None
12426
    self.evac_mode = None
12427
    self.target_groups = []
12428
    # computed fields
12429
    self.required_nodes = None
12430
    # init result fields
12431
    self.success = self.info = self.result = None
12432

    
12433
    try:
12434
      (fn, keydata, self._result_check) = self._MODE_DATA[self.mode]
12435
    except KeyError:
12436
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
12437
                                   " IAllocator" % self.mode)
12438

    
12439
    keyset = [n for (n, _) in keydata]
12440

    
12441
    for key in kwargs:
12442
      if key not in keyset:
12443
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
12444
                                     " IAllocator" % key)
12445
      setattr(self, key, kwargs[key])
12446

    
12447
    for key in keyset:
12448
      if key not in kwargs:
12449
        raise errors.ProgrammerError("Missing input parameter '%s' to"
12450
                                     " IAllocator" % key)
12451
    self._BuildInputData(compat.partial(fn, self), keydata)
12452

    
12453
  def _ComputeClusterData(self):
12454
    """Compute the generic allocator input data.
12455

12456
    This is the data that is independent of the actual operation.
12457

12458
    """
12459
    cfg = self.cfg
12460
    cluster_info = cfg.GetClusterInfo()
12461
    # cluster data
12462
    data = {
12463
      "version": constants.IALLOCATOR_VERSION,
12464
      "cluster_name": cfg.GetClusterName(),
12465
      "cluster_tags": list(cluster_info.GetTags()),
12466
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
12467
      # we don't have job IDs
12468
      }
12469
    ninfo = cfg.GetAllNodesInfo()
12470
    iinfo = cfg.GetAllInstancesInfo().values()
12471
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
12472

    
12473
    # node data
12474
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
12475

    
12476
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
12477
      hypervisor_name = self.hypervisor
12478
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
12479
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
12480
    else:
12481
      hypervisor_name = cluster_info.enabled_hypervisors[0]
12482

    
12483
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
12484
                                        hypervisor_name)
12485
    node_iinfo = \
12486
      self.rpc.call_all_instances_info(node_list,
12487
                                       cluster_info.enabled_hypervisors)
12488

    
12489
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
12490

    
12491
    config_ndata = self._ComputeBasicNodeData(ninfo)
12492
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
12493
                                                 i_list, config_ndata)
12494
    assert len(data["nodes"]) == len(ninfo), \
12495
        "Incomplete node data computed"
12496

    
12497
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
12498

    
12499
    self.in_data = data
12500

    
12501
  @staticmethod
12502
  def _ComputeNodeGroupData(cfg):
12503
    """Compute node groups data.
12504

12505
    """
12506
    ng = dict((guuid, {
12507
      "name": gdata.name,
12508
      "alloc_policy": gdata.alloc_policy,
12509
      })
12510
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
12511

    
12512
    return ng
12513

    
12514
  @staticmethod
12515
  def _ComputeBasicNodeData(node_cfg):
12516
    """Compute global node data.
12517

12518
    @rtype: dict
12519
    @returns: a dict of name: (node dict, node config)
12520

12521
    """
12522
    # fill in static (config-based) values
12523
    node_results = dict((ninfo.name, {
12524
      "tags": list(ninfo.GetTags()),
12525
      "primary_ip": ninfo.primary_ip,
12526
      "secondary_ip": ninfo.secondary_ip,
12527
      "offline": ninfo.offline,
12528
      "drained": ninfo.drained,
12529
      "master_candidate": ninfo.master_candidate,
12530
      "group": ninfo.group,
12531
      "master_capable": ninfo.master_capable,
12532
      "vm_capable": ninfo.vm_capable,
12533
      })
12534
      for ninfo in node_cfg.values())
12535

    
12536
    return node_results
12537

    
12538
  @staticmethod
12539
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
12540
                              node_results):
12541
    """Compute global node data.
12542

12543
    @param node_results: the basic node structures as filled from the config
12544

12545
    """
12546
    # make a copy of the current dict
12547
    node_results = dict(node_results)
12548
    for nname, nresult in node_data.items():
12549
      assert nname in node_results, "Missing basic data for node %s" % nname
12550
      ninfo = node_cfg[nname]
12551

    
12552
      if not (ninfo.offline or ninfo.drained):
12553
        nresult.Raise("Can't get data for node %s" % nname)
12554
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
12555
                                nname)
12556
        remote_info = nresult.payload
12557

    
12558
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
12559
                     'vg_size', 'vg_free', 'cpu_total']:
12560
          if attr not in remote_info:
12561
            raise errors.OpExecError("Node '%s' didn't return attribute"
12562
                                     " '%s'" % (nname, attr))
12563
          if not isinstance(remote_info[attr], int):
12564
            raise errors.OpExecError("Node '%s' returned invalid value"
12565
                                     " for '%s': %s" %
12566
                                     (nname, attr, remote_info[attr]))
12567
        # compute memory used by primary instances
12568
        i_p_mem = i_p_up_mem = 0
12569
        for iinfo, beinfo in i_list:
12570
          if iinfo.primary_node == nname:
12571
            i_p_mem += beinfo[constants.BE_MEMORY]
12572
            if iinfo.name not in node_iinfo[nname].payload:
12573
              i_used_mem = 0
12574
            else:
12575
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
12576
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
12577
            remote_info['memory_free'] -= max(0, i_mem_diff)
12578

    
12579
            if iinfo.admin_up:
12580
              i_p_up_mem += beinfo[constants.BE_MEMORY]
12581

    
12582
        # compute memory used by instances
12583
        pnr_dyn = {
12584
          "total_memory": remote_info['memory_total'],
12585
          "reserved_memory": remote_info['memory_dom0'],
12586
          "free_memory": remote_info['memory_free'],
12587
          "total_disk": remote_info['vg_size'],
12588
          "free_disk": remote_info['vg_free'],
12589
          "total_cpus": remote_info['cpu_total'],
12590
          "i_pri_memory": i_p_mem,
12591
          "i_pri_up_memory": i_p_up_mem,
12592
          }
12593
        pnr_dyn.update(node_results[nname])
12594
        node_results[nname] = pnr_dyn
12595

    
12596
    return node_results
12597

    
12598
  @staticmethod
12599
  def _ComputeInstanceData(cluster_info, i_list):
12600
    """Compute global instance data.
12601

12602
    """
12603
    instance_data = {}
12604
    for iinfo, beinfo in i_list:
12605
      nic_data = []
12606
      for nic in iinfo.nics:
12607
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12608
        nic_dict = {
12609
          "mac": nic.mac,
12610
          "ip": nic.ip,
12611
          "mode": filled_params[constants.NIC_MODE],
12612
          "link": filled_params[constants.NIC_LINK],
12613
          }
12614
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12615
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12616
        nic_data.append(nic_dict)
12617
      pir = {
12618
        "tags": list(iinfo.GetTags()),
12619
        "admin_up": iinfo.admin_up,
12620
        "vcpus": beinfo[constants.BE_VCPUS],
12621
        "memory": beinfo[constants.BE_MEMORY],
12622
        "os": iinfo.os,
12623
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12624
        "nics": nic_data,
12625
        "disks": [{constants.IDISK_SIZE: dsk.size,
12626
                   constants.IDISK_MODE: dsk.mode}
12627
                  for dsk in iinfo.disks],
12628
        "disk_template": iinfo.disk_template,
12629
        "hypervisor": iinfo.hypervisor,
12630
        }
12631
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12632
                                                 pir["disks"])
12633
      instance_data[iinfo.name] = pir
12634

    
12635
    return instance_data
12636

    
12637
  def _AddNewInstance(self):
12638
    """Add new instance data to allocator structure.
12639

12640
    This in combination with _AllocatorGetClusterData will create the
12641
    correct structure needed as input for the allocator.
12642

12643
    The checks for the completeness of the opcode must have already been
12644
    done.
12645

12646
    """
12647
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12648

    
12649
    if self.disk_template in constants.DTS_INT_MIRROR:
12650
      self.required_nodes = 2
12651
    else:
12652
      self.required_nodes = 1
12653

    
12654
    request = {
12655
      "name": self.name,
12656
      "disk_template": self.disk_template,
12657
      "tags": self.tags,
12658
      "os": self.os,
12659
      "vcpus": self.vcpus,
12660
      "memory": self.memory,
12661
      "disks": self.disks,
12662
      "disk_space_total": disk_space,
12663
      "nics": self.nics,
12664
      "required_nodes": self.required_nodes,
12665
      "hypervisor": self.hypervisor,
12666
      }
12667

    
12668
    return request
12669

    
12670
  def _AddRelocateInstance(self):
12671
    """Add relocate instance data to allocator structure.
12672

12673
    This in combination with _IAllocatorGetClusterData will create the
12674
    correct structure needed as input for the allocator.
12675

12676
    The checks for the completeness of the opcode must have already been
12677
    done.
12678

12679
    """
12680
    instance = self.cfg.GetInstanceInfo(self.name)
12681
    if instance is None:
12682
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12683
                                   " IAllocator" % self.name)
12684

    
12685
    if instance.disk_template not in constants.DTS_MIRRORED:
12686
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12687
                                 errors.ECODE_INVAL)
12688

    
12689
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12690
        len(instance.secondary_nodes) != 1:
12691
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12692
                                 errors.ECODE_STATE)
12693

    
12694
    self.required_nodes = 1
12695
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12696
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12697

    
12698
    request = {
12699
      "name": self.name,
12700
      "disk_space_total": disk_space,
12701
      "required_nodes": self.required_nodes,
12702
      "relocate_from": self.relocate_from,
12703
      }
12704
    return request
12705

    
12706
  def _AddEvacuateNodes(self):
12707
    """Add evacuate nodes data to allocator structure.
12708

12709
    """
12710
    request = {
12711
      "evac_nodes": self.evac_nodes
12712
      }
12713
    return request
12714

    
12715
  def _AddNodeEvacuate(self):
12716
    """Get data for node-evacuate requests.
12717

12718
    """
12719
    return {
12720
      "instances": self.instances,
12721
      "evac_mode": self.evac_mode,
12722
      }
12723

    
12724
  def _AddChangeGroup(self):
12725
    """Get data for node-evacuate requests.
12726

12727
    """
12728
    return {
12729
      "instances": self.instances,
12730
      "target_groups": self.target_groups,
12731
      }
12732

    
12733
  def _BuildInputData(self, fn, keydata):
12734
    """Build input data structures.
12735

12736
    """
12737
    self._ComputeClusterData()
12738

    
12739
    request = fn()
12740
    request["type"] = self.mode
12741
    for keyname, keytype in keydata:
12742
      if keyname not in request:
12743
        raise errors.ProgrammerError("Request parameter %s is missing" %
12744
                                     keyname)
12745
      val = request[keyname]
12746
      if not keytype(val):
12747
        raise errors.ProgrammerError("Request parameter %s doesn't pass"
12748
                                     " validation, value %s, expected"
12749
                                     " type %s" % (keyname, val, keytype))
12750
    self.in_data["request"] = request
12751

    
12752
    self.in_text = serializer.Dump(self.in_data)
12753

    
12754
  _STRING_LIST = ht.TListOf(ht.TString)
12755
  _JOB_LIST = ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12756
     # pylint: disable-msg=E1101
12757
     # Class '...' has no 'OP_ID' member
12758
     "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12759
                          opcodes.OpInstanceMigrate.OP_ID,
12760
                          opcodes.OpInstanceReplaceDisks.OP_ID])
12761
     })))
12762

    
12763
  _NEVAC_MOVED = \
12764
    ht.TListOf(ht.TAnd(ht.TIsLength(3),
12765
                       ht.TItems([ht.TNonEmptyString,
12766
                                  ht.TNonEmptyString,
12767
                                  ht.TListOf(ht.TNonEmptyString),
12768
                                 ])))
12769
  _NEVAC_FAILED = \
12770
    ht.TListOf(ht.TAnd(ht.TIsLength(2),
12771
                       ht.TItems([ht.TNonEmptyString,
12772
                                  ht.TMaybeString,
12773
                                 ])))
12774
  _NEVAC_RESULT = ht.TAnd(ht.TIsLength(3),
12775
                          ht.TItems([_NEVAC_MOVED, _NEVAC_FAILED, _JOB_LIST]))
12776

    
12777
  _MODE_DATA = {
12778
    constants.IALLOCATOR_MODE_ALLOC:
12779
      (_AddNewInstance,
12780
       [
12781
        ("name", ht.TString),
12782
        ("memory", ht.TInt),
12783
        ("disks", ht.TListOf(ht.TDict)),
12784
        ("disk_template", ht.TString),
12785
        ("os", ht.TString),
12786
        ("tags", _STRING_LIST),
12787
        ("nics", ht.TListOf(ht.TDict)),
12788
        ("vcpus", ht.TInt),
12789
        ("hypervisor", ht.TString),
12790
        ], ht.TList),
12791
    constants.IALLOCATOR_MODE_RELOC:
12792
      (_AddRelocateInstance,
12793
       [("name", ht.TString), ("relocate_from", _STRING_LIST)],
12794
       ht.TList),
12795
    constants.IALLOCATOR_MODE_MEVAC:
12796
      (_AddEvacuateNodes, [("evac_nodes", _STRING_LIST)],
12797
       ht.TListOf(ht.TAnd(ht.TIsLength(2), _STRING_LIST))),
12798
     constants.IALLOCATOR_MODE_NODE_EVAC:
12799
      (_AddNodeEvacuate, [
12800
        ("instances", _STRING_LIST),
12801
        ("evac_mode", ht.TElemOf(constants.IALLOCATOR_NEVAC_MODES)),
12802
        ], _NEVAC_RESULT),
12803
     constants.IALLOCATOR_MODE_CHG_GROUP:
12804
      (_AddChangeGroup, [
12805
        ("instances", _STRING_LIST),
12806
        ("target_groups", _STRING_LIST),
12807
        ], _NEVAC_RESULT),
12808
    }
12809

    
12810
  def Run(self, name, validate=True, call_fn=None):
12811
    """Run an instance allocator and return the results.
12812

12813
    """
12814
    if call_fn is None:
12815
      call_fn = self.rpc.call_iallocator_runner
12816

    
12817
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12818
    result.Raise("Failure while running the iallocator script")
12819

    
12820
    self.out_text = result.payload
12821
    if validate:
12822
      self._ValidateResult()
12823

    
12824
  def _ValidateResult(self):
12825
    """Process the allocator results.
12826

12827
    This will process and if successful save the result in
12828
    self.out_data and the other parameters.
12829

12830
    """
12831
    try:
12832
      rdict = serializer.Load(self.out_text)
12833
    except Exception, err:
12834
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12835

    
12836
    if not isinstance(rdict, dict):
12837
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12838

    
12839
    # TODO: remove backwards compatiblity in later versions
12840
    if "nodes" in rdict and "result" not in rdict:
12841
      rdict["result"] = rdict["nodes"]
12842
      del rdict["nodes"]
12843

    
12844
    for key in "success", "info", "result":
12845
      if key not in rdict:
12846
        raise errors.OpExecError("Can't parse iallocator results:"
12847
                                 " missing key '%s'" % key)
12848
      setattr(self, key, rdict[key])
12849

    
12850
    if not self._result_check(self.result):
12851
      raise errors.OpExecError("Iallocator returned invalid result,"
12852
                               " expected %s, got %s" %
12853
                               (self._result_check, self.result),
12854
                               errors.ECODE_INVAL)
12855

    
12856
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12857
                     constants.IALLOCATOR_MODE_MEVAC):
12858
      node2group = dict((name, ndata["group"])
12859
                        for (name, ndata) in self.in_data["nodes"].items())
12860

    
12861
      fn = compat.partial(self._NodesToGroups, node2group,
12862
                          self.in_data["nodegroups"])
12863

    
12864
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12865
        assert self.relocate_from is not None
12866
        assert self.required_nodes == 1
12867

    
12868
        request_groups = fn(self.relocate_from)
12869
        result_groups = fn(rdict["result"])
12870

    
12871
        if result_groups != request_groups:
12872
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12873
                                   " differ from original groups (%s)" %
12874
                                   (utils.CommaJoin(result_groups),
12875
                                    utils.CommaJoin(request_groups)))
12876
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12877
        request_groups = fn(self.evac_nodes)
12878
        for (instance_name, secnode) in self.result:
12879
          result_groups = fn([secnode])
12880
          if result_groups != request_groups:
12881
            raise errors.OpExecError("Iallocator returned new secondary node"
12882
                                     " '%s' (group '%s') for instance '%s'"
12883
                                     " which is not in original group '%s'" %
12884
                                     (secnode, utils.CommaJoin(result_groups),
12885
                                      instance_name,
12886
                                      utils.CommaJoin(request_groups)))
12887
      else:
12888
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12889

    
12890
    elif self.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
12891
      assert self.evac_mode in constants.IALLOCATOR_NEVAC_MODES
12892

    
12893
    self.out_data = rdict
12894

    
12895
  @staticmethod
12896
  def _NodesToGroups(node2group, groups, nodes):
12897
    """Returns a list of unique group names for a list of nodes.
12898

12899
    @type node2group: dict
12900
    @param node2group: Map from node name to group UUID
12901
    @type groups: dict
12902
    @param groups: Group information
12903
    @type nodes: list
12904
    @param nodes: Node names
12905

12906
    """
12907
    result = set()
12908

    
12909
    for node in nodes:
12910
      try:
12911
        group_uuid = node2group[node]
12912
      except KeyError:
12913
        # Ignore unknown node
12914
        pass
12915
      else:
12916
        try:
12917
          group = groups[group_uuid]
12918
        except KeyError:
12919
          # Can't find group, let's use UUID
12920
          group_name = group_uuid
12921
        else:
12922
          group_name = group["name"]
12923

    
12924
        result.add(group_name)
12925

    
12926
    return sorted(result)
12927

    
12928

    
12929
class LUTestAllocator(NoHooksLU):
12930
  """Run allocator tests.
12931

12932
  This LU runs the allocator tests
12933

12934
  """
12935
  def CheckPrereq(self):
12936
    """Check prerequisites.
12937

12938
    This checks the opcode parameters depending on the director and mode test.
12939

12940
    """
12941
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12942
      for attr in ["memory", "disks", "disk_template",
12943
                   "os", "tags", "nics", "vcpus"]:
12944
        if not hasattr(self.op, attr):
12945
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12946
                                     attr, errors.ECODE_INVAL)
12947
      iname = self.cfg.ExpandInstanceName(self.op.name)
12948
      if iname is not None:
12949
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12950
                                   iname, errors.ECODE_EXISTS)
12951
      if not isinstance(self.op.nics, list):
12952
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12953
                                   errors.ECODE_INVAL)
12954
      if not isinstance(self.op.disks, list):
12955
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12956
                                   errors.ECODE_INVAL)
12957
      for row in self.op.disks:
12958
        if (not isinstance(row, dict) or
12959
            constants.IDISK_SIZE not in row or
12960
            not isinstance(row[constants.IDISK_SIZE], int) or
12961
            constants.IDISK_MODE not in row or
12962
            row[constants.IDISK_MODE] not in constants.DISK_ACCESS_SET):
12963
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12964
                                     " parameter", errors.ECODE_INVAL)
12965
      if self.op.hypervisor is None:
12966
        self.op.hypervisor = self.cfg.GetHypervisorType()
12967
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12968
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12969
      self.op.name = fname
12970
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12971
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12972
      if not hasattr(self.op, "evac_nodes"):
12973
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12974
                                   " opcode input", errors.ECODE_INVAL)
12975
    elif self.op.mode in (constants.IALLOCATOR_MODE_CHG_GROUP,
12976
                          constants.IALLOCATOR_MODE_NODE_EVAC):
12977
      if not self.op.instances:
12978
        raise errors.OpPrereqError("Missing instances", errors.ECODE_INVAL)
12979
      self.op.instances = _GetWantedInstances(self, self.op.instances)
12980
    else:
12981
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12982
                                 self.op.mode, errors.ECODE_INVAL)
12983

    
12984
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12985
      if self.op.allocator is None:
12986
        raise errors.OpPrereqError("Missing allocator name",
12987
                                   errors.ECODE_INVAL)
12988
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12989
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12990
                                 self.op.direction, errors.ECODE_INVAL)
12991

    
12992
  def Exec(self, feedback_fn):
12993
    """Run the allocator test.
12994

12995
    """
12996
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12997
      ial = IAllocator(self.cfg, self.rpc,
12998
                       mode=self.op.mode,
12999
                       name=self.op.name,
13000
                       memory=self.op.memory,
13001
                       disks=self.op.disks,
13002
                       disk_template=self.op.disk_template,
13003
                       os=self.op.os,
13004
                       tags=self.op.tags,
13005
                       nics=self.op.nics,
13006
                       vcpus=self.op.vcpus,
13007
                       hypervisor=self.op.hypervisor,
13008
                       )
13009
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
13010
      ial = IAllocator(self.cfg, self.rpc,
13011
                       mode=self.op.mode,
13012
                       name=self.op.name,
13013
                       relocate_from=list(self.relocate_from),
13014
                       )
13015
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
13016
      ial = IAllocator(self.cfg, self.rpc,
13017
                       mode=self.op.mode,
13018
                       evac_nodes=self.op.evac_nodes)
13019
    elif self.op.mode == constants.IALLOCATOR_MODE_CHG_GROUP:
13020
      ial = IAllocator(self.cfg, self.rpc,
13021
                       mode=self.op.mode,
13022
                       instances=self.op.instances,
13023
                       target_groups=self.op.target_groups)
13024
    elif self.op.mode == constants.IALLOCATOR_MODE_NODE_EVAC:
13025
      ial = IAllocator(self.cfg, self.rpc,
13026
                       mode=self.op.mode,
13027
                       instances=self.op.instances,
13028
                       evac_mode=self.op.evac_mode)
13029
    else:
13030
      raise errors.ProgrammerError("Uncatched mode %s in"
13031
                                   " LUTestAllocator.Exec", self.op.mode)
13032

    
13033
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
13034
      result = ial.in_text
13035
    else:
13036
      ial.Run(self.op.allocator, validate=False)
13037
      result = ial.out_text
13038
    return result
13039

    
13040

    
13041
#: Query type implementations
13042
_QUERY_IMPL = {
13043
  constants.QR_INSTANCE: _InstanceQuery,
13044
  constants.QR_NODE: _NodeQuery,
13045
  constants.QR_GROUP: _GroupQuery,
13046
  constants.QR_OS: _OsQuery,
13047
  }
13048

    
13049
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
13050

    
13051

    
13052
def _GetQueryImplementation(name):
13053
  """Returns the implemtnation for a query type.
13054

13055
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
13056

13057
  """
13058
  try:
13059
    return _QUERY_IMPL[name]
13060
  except KeyError:
13061
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
13062
                               errors.ECODE_INVAL)