Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 14970c32

History | View | Annotate | Download (435.7 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
64

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

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

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

    
77

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

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

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

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

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

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

    
99

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

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

113
  Note that all commands require root permissions.
114

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

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

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

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

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

    
155
    # Tasklets
156
    self.tasklets = None
157

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

    
161
    self.CheckArguments()
162

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

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

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

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

178
    """
179
    pass
180

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

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

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

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

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

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

206
    Examples::
207

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

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

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

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

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

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

245
    """
246

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

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

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

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

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

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

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

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

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

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

297
    """
298
    raise NotImplementedError
299

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

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

311
    """
312
    raise NotImplementedError
313

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
400
    del self.recalculate_locks[locking.LEVEL_NODE]
401

    
402

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

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

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

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

416
    This just raises an error.
417

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

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

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

    
427

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

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

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

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

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

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

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

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

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

460
    """
461
    pass
462

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

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

470
    """
471
    raise NotImplementedError
472

    
473

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

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

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

484
    """
485
    self.use_locking = use_locking
486

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

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

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

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

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

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

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

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

    
521
    # Return expanded names
522
    return self.wanted
523

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

527
    See L{LogicalUnit.ExpandNames}.
528

529
    """
530
    raise NotImplementedError()
531

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

535
    See L{LogicalUnit.DeclareLocks}.
536

537
    """
538
    raise NotImplementedError()
539

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

543
    @return: Query data object
544

545
    """
546
    raise NotImplementedError()
547

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

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

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

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

    
562

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

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

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

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

    
580

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

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

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

    
600

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

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

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

    
633

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

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

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

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

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

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

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

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

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

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

    
678

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

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

    
690

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

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

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

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

    
709

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

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

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

    
724

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

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

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

    
739

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

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

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

    
752

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

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

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

    
765

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

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

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

    
783

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

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

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

    
810

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

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

    
818

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

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

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

    
834

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

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

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

    
851

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

    
856

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

    
861

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

867
  This builds the hook environment from individual variables.
868

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

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

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

    
931
  env["INSTANCE_NIC_COUNT"] = nic_count
932

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

    
941
  env["INSTANCE_DISK_COUNT"] = disk_count
942

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

    
947
  return env
948

    
949

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

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

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

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

    
973

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

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

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

    
1011

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

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

    
1027

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

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

    
1038

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

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

    
1052

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

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

    
1061

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

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

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

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

    
1081

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

    
1085

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

1089
  """
1090

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

    
1093

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

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

    
1101

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

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

    
1109

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

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

    
1119
  return []
1120

    
1121

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

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

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

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

    
1136
  return faulty
1137

    
1138

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

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

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

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

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

    
1170

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

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

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

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

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

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

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

1195
    """
1196
    return True
1197

    
1198

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

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

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

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

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

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

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

1223
    This checks whether the cluster is empty.
1224

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

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

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

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

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

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

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

    
1253
    return master
1254

    
1255

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

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

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

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

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

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

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

    
1288

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1508
    return True
1509

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1675
    diskdata = [(nname, success, status, idx)
1676
                for (nname, disks) in diskstatus.items()
1677
                for idx, (success, status) in enumerate(disks)]
1678

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

    
1693
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1694
    """Verify if there are any unknown volumes in the cluster.
1695

1696
    The .os, .swap and backup volumes are ignored. All other volumes are
1697
    reported as unknown.
1698

1699
    @type reserved: L{ganeti.utils.FieldSet}
1700
    @param reserved: a FieldSet of reserved volume names
1701

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

    
1714
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1715
    """Verify N+1 Memory Resilience.
1716

1717
    Check that if one single node dies we can still start all the
1718
    instances it was primary for.
1719

1720
    """
1721
    cluster_info = self.cfg.GetClusterInfo()
1722
    for node, n_img in node_image.items():
1723
      # This code checks that every node which is now listed as
1724
      # secondary has enough memory to host all instances it is
1725
      # supposed to should a single other node in the cluster fail.
1726
      # FIXME: not ready for failover to an arbitrary node
1727
      # FIXME: does not support file-backed instances
1728
      # WARNING: we currently take into account down instances as well
1729
      # as up ones, considering that even if they're down someone
1730
      # might want to start them even in the event of a node failure.
1731
      if n_img.offline:
1732
        # we're skipping offline nodes from the N+1 warning, since
1733
        # most likely we don't have good memory infromation from them;
1734
        # we already list instances living on such nodes, and that's
1735
        # enough warning
1736
        continue
1737
      for prinode, instances in n_img.sbp.items():
1738
        needed_mem = 0
1739
        for instance in instances:
1740
          bep = cluster_info.FillBE(instance_cfg[instance])
1741
          if bep[constants.BE_AUTO_BALANCE]:
1742
            needed_mem += bep[constants.BE_MEMORY]
1743
        test = n_img.mfree < needed_mem
1744
        self._ErrorIf(test, self.ENODEN1, node,
1745
                      "not enough memory to accomodate instance failovers"
1746
                      " should node %s fail (%dMiB needed, %dMiB available)",
1747
                      prinode, needed_mem, n_img.mfree)
1748

    
1749
  @classmethod
1750
  def _VerifyFiles(cls, errorif, nodeinfo, master_node, all_nvinfo,
1751
                   (files_all, files_all_opt, files_mc, files_vm)):
1752
    """Verifies file checksums collected from all nodes.
1753

1754
    @param errorif: Callback for reporting errors
1755
    @param nodeinfo: List of L{objects.Node} objects
1756
    @param master_node: Name of master node
1757
    @param all_nvinfo: RPC results
1758

1759
    """
1760
    node_names = frozenset(node.name for node in nodeinfo)
1761

    
1762
    assert master_node in node_names
1763
    assert (len(files_all | files_all_opt | files_mc | files_vm) ==
1764
            sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
1765
           "Found file listed in more than one file list"
1766

    
1767
    # Define functions determining which nodes to consider for a file
1768
    file2nodefn = dict([(filename, fn)
1769
      for (files, fn) in [(files_all, None),
1770
                          (files_all_opt, None),
1771
                          (files_mc, lambda node: (node.master_candidate or
1772
                                                   node.name == master_node)),
1773
                          (files_vm, lambda node: node.vm_capable)]
1774
      for filename in files])
1775

    
1776
    fileinfo = dict((filename, {}) for filename in file2nodefn.keys())
1777

    
1778
    for node in nodeinfo:
1779
      nresult = all_nvinfo[node.name]
1780

    
1781
      if nresult.fail_msg or not nresult.payload:
1782
        node_files = None
1783
      else:
1784
        node_files = nresult.payload.get(constants.NV_FILELIST, None)
1785

    
1786
      test = not (node_files and isinstance(node_files, dict))
1787
      errorif(test, cls.ENODEFILECHECK, node.name,
1788
              "Node did not return file checksum data")
1789
      if test:
1790
        continue
1791

    
1792
      for (filename, checksum) in node_files.items():
1793
        # Check if the file should be considered for a node
1794
        fn = file2nodefn[filename]
1795
        if fn is None or fn(node):
1796
          fileinfo[filename].setdefault(checksum, set()).add(node.name)
1797

    
1798
    for (filename, checksums) in fileinfo.items():
1799
      assert compat.all(len(i) > 10 for i in checksums), "Invalid checksum"
1800

    
1801
      # Nodes having the file
1802
      with_file = frozenset(node_name
1803
                            for nodes in fileinfo[filename].values()
1804
                            for node_name in nodes)
1805

    
1806
      # Nodes missing file
1807
      missing_file = node_names - with_file
1808

    
1809
      if filename in files_all_opt:
1810
        # All or no nodes
1811
        errorif(missing_file and missing_file != node_names,
1812
                cls.ECLUSTERFILECHECK, None,
1813
                "File %s is optional, but it must exist on all or no nodes (not"
1814
                " found on %s)",
1815
                filename, utils.CommaJoin(utils.NiceSort(missing_file)))
1816
      else:
1817
        errorif(missing_file, cls.ECLUSTERFILECHECK, None,
1818
                "File %s is missing from node(s) %s", filename,
1819
                utils.CommaJoin(utils.NiceSort(missing_file)))
1820

    
1821
      # See if there are multiple versions of the file
1822
      test = len(checksums) > 1
1823
      if test:
1824
        variants = ["variant %s on %s" %
1825
                    (idx + 1, utils.CommaJoin(utils.NiceSort(nodes)))
1826
                    for (idx, (checksum, nodes)) in
1827
                      enumerate(sorted(checksums.items()))]
1828
      else:
1829
        variants = []
1830

    
1831
      errorif(test, cls.ECLUSTERFILECHECK, None,
1832
              "File %s found with %s different checksums (%s)",
1833
              filename, len(checksums), "; ".join(variants))
1834

    
1835
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1836
                      drbd_map):
1837
    """Verifies and the node DRBD status.
1838

1839
    @type ninfo: L{objects.Node}
1840
    @param ninfo: the node to check
1841
    @param nresult: the remote results for the node
1842
    @param instanceinfo: the dict of instances
1843
    @param drbd_helper: the configured DRBD usermode helper
1844
    @param drbd_map: the DRBD map as returned by
1845
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1846

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

    
1851
    if drbd_helper:
1852
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1853
      test = (helper_result == None)
1854
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1855
               "no drbd usermode helper returned")
1856
      if helper_result:
1857
        status, payload = helper_result
1858
        test = not status
1859
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1860
                 "drbd usermode helper check unsuccessful: %s", payload)
1861
        test = status and (payload != drbd_helper)
1862
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1863
                 "wrong drbd usermode helper: %s", payload)
1864

    
1865
    # compute the DRBD minors
1866
    node_drbd = {}
1867
    for minor, instance in drbd_map[node].items():
1868
      test = instance not in instanceinfo
1869
      _ErrorIf(test, self.ECLUSTERCFG, None,
1870
               "ghost instance '%s' in temporary DRBD map", instance)
1871
        # ghost instance should not be running, but otherwise we
1872
        # don't give double warnings (both ghost instance and
1873
        # unallocated minor in use)
1874
      if test:
1875
        node_drbd[minor] = (instance, False)
1876
      else:
1877
        instance = instanceinfo[instance]
1878
        node_drbd[minor] = (instance.name, instance.admin_up)
1879

    
1880
    # and now check them
1881
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1882
    test = not isinstance(used_minors, (tuple, list))
1883
    _ErrorIf(test, self.ENODEDRBD, node,
1884
             "cannot parse drbd status file: %s", str(used_minors))
1885
    if test:
1886
      # we cannot check drbd status
1887
      return
1888

    
1889
    for minor, (iname, must_exist) in node_drbd.items():
1890
      test = minor not in used_minors and must_exist
1891
      _ErrorIf(test, self.ENODEDRBD, node,
1892
               "drbd minor %d of instance %s is not active", minor, iname)
1893
    for minor in used_minors:
1894
      test = minor not in node_drbd
1895
      _ErrorIf(test, self.ENODEDRBD, node,
1896
               "unallocated drbd minor %d is in use", minor)
1897

    
1898
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1899
    """Builds the node OS structures.
1900

1901
    @type ninfo: L{objects.Node}
1902
    @param ninfo: the node to check
1903
    @param nresult: the remote results for the node
1904
    @param nimg: the node image object
1905

1906
    """
1907
    node = ninfo.name
1908
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1909

    
1910
    remote_os = nresult.get(constants.NV_OSLIST, None)
1911
    test = (not isinstance(remote_os, list) or
1912
            not compat.all(isinstance(v, list) and len(v) == 7
1913
                           for v in remote_os))
1914

    
1915
    _ErrorIf(test, self.ENODEOS, node,
1916
             "node hasn't returned valid OS data")
1917

    
1918
    nimg.os_fail = test
1919

    
1920
    if test:
1921
      return
1922

    
1923
    os_dict = {}
1924

    
1925
    for (name, os_path, status, diagnose,
1926
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1927

    
1928
      if name not in os_dict:
1929
        os_dict[name] = []
1930

    
1931
      # parameters is a list of lists instead of list of tuples due to
1932
      # JSON lacking a real tuple type, fix it:
1933
      parameters = [tuple(v) for v in parameters]
1934
      os_dict[name].append((os_path, status, diagnose,
1935
                            set(variants), set(parameters), set(api_ver)))
1936

    
1937
    nimg.oslist = os_dict
1938

    
1939
  def _VerifyNodeOS(self, ninfo, nimg, base):
1940
    """Verifies the node OS list.
1941

1942
    @type ninfo: L{objects.Node}
1943
    @param ninfo: the node to check
1944
    @param nimg: the node image object
1945
    @param base: the 'template' node we match against (e.g. from the master)
1946

1947
    """
1948
    node = ninfo.name
1949
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1950

    
1951
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1952

    
1953
    beautify_params = lambda l: ["%s: %s" % (k, v) for (k, v) in l]
1954
    for os_name, os_data in nimg.oslist.items():
1955
      assert os_data, "Empty OS status for OS %s?!" % os_name
1956
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1957
      _ErrorIf(not f_status, self.ENODEOS, node,
1958
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1959
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1960
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1961
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1962
      # this will catched in backend too
1963
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1964
               and not f_var, self.ENODEOS, node,
1965
               "OS %s with API at least %d does not declare any variant",
1966
               os_name, constants.OS_API_V15)
1967
      # comparisons with the 'base' image
1968
      test = os_name not in base.oslist
1969
      _ErrorIf(test, self.ENODEOS, node,
1970
               "Extra OS %s not present on reference node (%s)",
1971
               os_name, base.name)
1972
      if test:
1973
        continue
1974
      assert base.oslist[os_name], "Base node has empty OS status?"
1975
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1976
      if not b_status:
1977
        # base OS is invalid, skipping
1978
        continue
1979
      for kind, a, b in [("API version", f_api, b_api),
1980
                         ("variants list", f_var, b_var),
1981
                         ("parameters", beautify_params(f_param),
1982
                          beautify_params(b_param))]:
1983
        _ErrorIf(a != b, self.ENODEOS, node,
1984
                 "OS %s for %s differs from reference node %s: [%s] vs. [%s]",
1985
                 kind, os_name, base.name,
1986
                 utils.CommaJoin(sorted(a)), utils.CommaJoin(sorted(b)))
1987

    
1988
    # check any missing OSes
1989
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1990
    _ErrorIf(missing, self.ENODEOS, node,
1991
             "OSes present on reference node %s but missing on this node: %s",
1992
             base.name, utils.CommaJoin(missing))
1993

    
1994
  def _VerifyOob(self, ninfo, nresult):
1995
    """Verifies out of band functionality of a node.
1996

1997
    @type ninfo: L{objects.Node}
1998
    @param ninfo: the node to check
1999
    @param nresult: the remote results for the node
2000

2001
    """
2002
    node = ninfo.name
2003
    # We just have to verify the paths on master and/or master candidates
2004
    # as the oob helper is invoked on the master
2005
    if ((ninfo.master_candidate or ninfo.master_capable) and
2006
        constants.NV_OOB_PATHS in nresult):
2007
      for path_result in nresult[constants.NV_OOB_PATHS]:
2008
        self._ErrorIf(path_result, self.ENODEOOBPATH, node, path_result)
2009

    
2010
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
2011
    """Verifies and updates the node volume data.
2012

2013
    This function will update a L{NodeImage}'s internal structures
2014
    with data from the remote call.
2015

2016
    @type ninfo: L{objects.Node}
2017
    @param ninfo: the node to check
2018
    @param nresult: the remote results for the node
2019
    @param nimg: the node image object
2020
    @param vg_name: the configured VG name
2021

2022
    """
2023
    node = ninfo.name
2024
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2025

    
2026
    nimg.lvm_fail = True
2027
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
2028
    if vg_name is None:
2029
      pass
2030
    elif isinstance(lvdata, basestring):
2031
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
2032
               utils.SafeEncode(lvdata))
2033
    elif not isinstance(lvdata, dict):
2034
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
2035
    else:
2036
      nimg.volumes = lvdata
2037
      nimg.lvm_fail = False
2038

    
2039
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
2040
    """Verifies and updates the node instance list.
2041

2042
    If the listing was successful, then updates this node's instance
2043
    list. Otherwise, it marks the RPC call as failed for the instance
2044
    list key.
2045

2046
    @type ninfo: L{objects.Node}
2047
    @param ninfo: the node to check
2048
    @param nresult: the remote results for the node
2049
    @param nimg: the node image object
2050

2051
    """
2052
    idata = nresult.get(constants.NV_INSTANCELIST, None)
2053
    test = not isinstance(idata, list)
2054
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
2055
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
2056
    if test:
2057
      nimg.hyp_fail = True
2058
    else:
2059
      nimg.instances = idata
2060

    
2061
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
2062
    """Verifies and computes a node information map
2063

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

2070
    """
2071
    node = ninfo.name
2072
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2073

    
2074
    # try to read free memory (from the hypervisor)
2075
    hv_info = nresult.get(constants.NV_HVINFO, None)
2076
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2077
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2078
    if not test:
2079
      try:
2080
        nimg.mfree = int(hv_info["memory_free"])
2081
      except (ValueError, TypeError):
2082
        _ErrorIf(True, self.ENODERPC, node,
2083
                 "node returned invalid nodeinfo, check hypervisor")
2084

    
2085
    # FIXME: devise a free space model for file based instances as well
2086
    if vg_name is not None:
2087
      test = (constants.NV_VGLIST not in nresult or
2088
              vg_name not in nresult[constants.NV_VGLIST])
2089
      _ErrorIf(test, self.ENODELVM, node,
2090
               "node didn't return data for the volume group '%s'"
2091
               " - it is either missing or broken", vg_name)
2092
      if not test:
2093
        try:
2094
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2095
        except (ValueError, TypeError):
2096
          _ErrorIf(True, self.ENODERPC, node,
2097
                   "node returned invalid LVM info, check LVM status")
2098

    
2099
  def _CollectDiskInfo(self, nodelist, node_image, instanceinfo):
2100
    """Gets per-disk status information for all instances.
2101

2102
    @type nodelist: list of strings
2103
    @param nodelist: Node names
2104
    @type node_image: dict of (name, L{objects.Node})
2105
    @param node_image: Node objects
2106
    @type instanceinfo: dict of (name, L{objects.Instance})
2107
    @param instanceinfo: Instance objects
2108
    @rtype: {instance: {node: [(succes, payload)]}}
2109
    @return: a dictionary of per-instance dictionaries with nodes as
2110
        keys and disk information as values; the disk information is a
2111
        list of tuples (success, payload)
2112

2113
    """
2114
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2115

    
2116
    node_disks = {}
2117
    node_disks_devonly = {}
2118
    diskless_instances = set()
2119
    diskless = constants.DT_DISKLESS
2120

    
2121
    for nname in nodelist:
2122
      node_instances = list(itertools.chain(node_image[nname].pinst,
2123
                                            node_image[nname].sinst))
2124
      diskless_instances.update(inst for inst in node_instances
2125
                                if instanceinfo[inst].disk_template == diskless)
2126
      disks = [(inst, disk)
2127
               for inst in node_instances
2128
               for disk in instanceinfo[inst].disks]
2129

    
2130
      if not disks:
2131
        # No need to collect data
2132
        continue
2133

    
2134
      node_disks[nname] = disks
2135

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

    
2140
      for dev in devonly:
2141
        self.cfg.SetDiskID(dev, nname)
2142

    
2143
      node_disks_devonly[nname] = devonly
2144

    
2145
    assert len(node_disks) == len(node_disks_devonly)
2146

    
2147
    # Collect data from all nodes with disks
2148
    result = self.rpc.call_blockdev_getmirrorstatus_multi(node_disks.keys(),
2149
                                                          node_disks_devonly)
2150

    
2151
    assert len(result) == len(node_disks)
2152

    
2153
    instdisk = {}
2154

    
2155
    for (nname, nres) in result.items():
2156
      disks = node_disks[nname]
2157

    
2158
      if nres.offline:
2159
        # No data from this node
2160
        data = len(disks) * [(False, "node offline")]
2161
      else:
2162
        msg = nres.fail_msg
2163
        _ErrorIf(msg, self.ENODERPC, nname,
2164
                 "while getting disk information: %s", msg)
2165
        if msg:
2166
          # No data from this node
2167
          data = len(disks) * [(False, msg)]
2168
        else:
2169
          data = []
2170
          for idx, i in enumerate(nres.payload):
2171
            if isinstance(i, (tuple, list)) and len(i) == 2:
2172
              data.append(i)
2173
            else:
2174
              logging.warning("Invalid result from node %s, entry %d: %s",
2175
                              nname, idx, i)
2176
              data.append((False, "Invalid result from the remote node"))
2177

    
2178
      for ((inst, _), status) in zip(disks, data):
2179
        instdisk.setdefault(inst, {}).setdefault(nname, []).append(status)
2180

    
2181
    # Add empty entries for diskless instances.
2182
    for inst in diskless_instances:
2183
      assert inst not in instdisk
2184
      instdisk[inst] = {}
2185

    
2186
    assert compat.all(len(statuses) == len(instanceinfo[inst].disks) and
2187
                      len(nnames) <= len(instanceinfo[inst].all_nodes) and
2188
                      compat.all(isinstance(s, (tuple, list)) and
2189
                                 len(s) == 2 for s in statuses)
2190
                      for inst, nnames in instdisk.items()
2191
                      for nname, statuses in nnames.items())
2192
    assert set(instdisk) == set(instanceinfo), "instdisk consistency failure"
2193

    
2194
    return instdisk
2195

    
2196
  def _VerifyHVP(self, hvp_data):
2197
    """Verifies locally the syntax of the hypervisor parameters.
2198

2199
    """
2200
    for item, hv_name, hv_params in hvp_data:
2201
      msg = ("hypervisor %s parameters syntax check (source %s): %%s" %
2202
             (item, hv_name))
2203
      try:
2204
        hv_class = hypervisor.GetHypervisor(hv_name)
2205
        utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2206
        hv_class.CheckParameterSyntax(hv_params)
2207
      except errors.GenericError, err:
2208
        self._ErrorIf(True, self.ECLUSTERCFG, None, msg % str(err))
2209

    
2210
  def BuildHooksEnv(self):
2211
    """Build hooks env.
2212

2213
    Cluster-Verify hooks just ran in the post phase and their failure makes
2214
    the output be logged in the verify output and the verification to fail.
2215

2216
    """
2217
    env = {
2218
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2219
      }
2220

    
2221
    env.update(("NODE_TAGS_%s" % node.name, " ".join(node.GetTags()))
2222
               for node in self.my_node_info.values())
2223

    
2224
    return env
2225

    
2226
  def BuildHooksNodes(self):
2227
    """Build hooks nodes.
2228

2229
    """
2230
    assert self.my_node_names, ("Node list not gathered,"
2231
      " has CheckPrereq been executed?")
2232
    return ([], self.my_node_names)
2233

    
2234
  def Exec(self, feedback_fn):
2235
    """Verify integrity of cluster, performing various test on nodes.
2236

2237
    """
2238
    # This method has too many local variables. pylint: disable-msg=R0914
2239
    self.bad = False
2240
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2241
    verbose = self.op.verbose
2242
    self._feedback_fn = feedback_fn
2243
    feedback_fn("* Verifying global settings")
2244
    for msg in self.cfg.VerifyConfig():
2245
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2246

    
2247
    # Check the cluster certificates
2248
    for cert_filename in constants.ALL_CERT_FILES:
2249
      (errcode, msg) = _VerifyCertificate(cert_filename)
2250
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2251

    
2252
    vg_name = self.cfg.GetVGName()
2253
    drbd_helper = self.cfg.GetDRBDHelper()
2254
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2255
    cluster = self.cfg.GetClusterInfo()
2256
    groupinfo = self.cfg.GetAllNodeGroupsInfo()
2257
    node_data_list = [self.my_node_info[name] for name in self.my_node_names]
2258

    
2259
    i_non_redundant = [] # Non redundant instances
2260
    i_non_a_balanced = [] # Non auto-balanced instances
2261
    n_offline = 0 # Count of offline nodes
2262
    n_drained = 0 # Count of nodes being drained
2263
    node_vol_should = {}
2264

    
2265
    # FIXME: verify OS list
2266

    
2267
    # File verification
2268
    filemap = _ComputeAncillaryFiles(cluster, False)
2269

    
2270
    # do local checksums
2271
    master_node = self.master_node = self.cfg.GetMasterNode()
2272
    master_ip = self.cfg.GetMasterIP()
2273

    
2274
    # Compute the set of hypervisor parameters
2275
    hvp_data = []
2276
    for hv_name in hypervisors:
2277
      hvp_data.append(("cluster", hv_name, cluster.GetHVDefaults(hv_name)))
2278
    for os_name, os_hvp in cluster.os_hvp.items():
2279
      for hv_name, hv_params in os_hvp.items():
2280
        if not hv_params:
2281
          continue
2282
        full_params = cluster.GetHVDefaults(hv_name, os_name=os_name)
2283
        hvp_data.append(("os %s" % os_name, hv_name, full_params))
2284
    # TODO: collapse identical parameter values in a single one
2285
    for instance in self.all_inst_info.values():
2286
      if not instance.hvparams:
2287
        continue
2288
      hvp_data.append(("instance %s" % instance.name, instance.hypervisor,
2289
                       cluster.FillHV(instance)))
2290
    # and verify them locally
2291
    self._VerifyHVP(hvp_data)
2292

    
2293
    feedback_fn("* Gathering data (%d nodes)" % len(self.my_node_names))
2294
    node_verify_param = {
2295
      constants.NV_FILELIST:
2296
        utils.UniqueSequence(filename
2297
                             for files in filemap
2298
                             for filename in files),
2299
      constants.NV_NODELIST: [node.name for node in self.all_node_info.values()
2300
                              if not node.offline],
2301
      constants.NV_HYPERVISOR: hypervisors,
2302
      constants.NV_HVPARAMS: hvp_data,
2303
      constants.NV_NODENETTEST: [(node.name, node.primary_ip, node.secondary_ip)
2304
                                 for node in node_data_list
2305
                                 if not node.offline],
2306
      constants.NV_INSTANCELIST: hypervisors,
2307
      constants.NV_VERSION: None,
2308
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2309
      constants.NV_NODESETUP: None,
2310
      constants.NV_TIME: None,
2311
      constants.NV_MASTERIP: (master_node, master_ip),
2312
      constants.NV_OSLIST: None,
2313
      constants.NV_VMNODES: self.cfg.GetNonVmCapableNodeList(),
2314
      }
2315

    
2316
    if vg_name is not None:
2317
      node_verify_param[constants.NV_VGLIST] = None
2318
      node_verify_param[constants.NV_LVLIST] = vg_name
2319
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2320
      node_verify_param[constants.NV_DRBDLIST] = None
2321

    
2322
    if drbd_helper:
2323
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2324

    
2325
    # bridge checks
2326
    # FIXME: this needs to be changed per node-group, not cluster-wide
2327
    bridges = set()
2328
    default_nicpp = cluster.nicparams[constants.PP_DEFAULT]
2329
    if default_nicpp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2330
      bridges.add(default_nicpp[constants.NIC_LINK])
2331
    for instance in self.my_inst_info.values():
2332
      for nic in instance.nics:
2333
        full_nic = cluster.SimpleFillNIC(nic.nicparams)
2334
        if full_nic[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
2335
          bridges.add(full_nic[constants.NIC_LINK])
2336

    
2337
    if bridges:
2338
      node_verify_param[constants.NV_BRIDGES] = list(bridges)
2339

    
2340
    # Build our expected cluster state
2341
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2342
                                                 name=node.name,
2343
                                                 vm_capable=node.vm_capable))
2344
                      for node in node_data_list)
2345

    
2346
    # Gather OOB paths
2347
    oob_paths = []
2348
    for node in self.all_node_info.values():
2349
      path = _SupportsOob(self.cfg, node)
2350
      if path and path not in oob_paths:
2351
        oob_paths.append(path)
2352

    
2353
    if oob_paths:
2354
      node_verify_param[constants.NV_OOB_PATHS] = oob_paths
2355

    
2356
    for instance in self.my_inst_names:
2357
      inst_config = self.my_inst_info[instance]
2358

    
2359
      for nname in inst_config.all_nodes:
2360
        if nname not in node_image:
2361
          # ghost node
2362
          gnode = self.NodeImage(name=nname)
2363
          gnode.ghost = True
2364
          node_image[nname] = gnode
2365

    
2366
      inst_config.MapLVsByNode(node_vol_should)
2367

    
2368
      pnode = inst_config.primary_node
2369
      node_image[pnode].pinst.append(instance)
2370

    
2371
      for snode in inst_config.secondary_nodes:
2372
        nimg = node_image[snode]
2373
        nimg.sinst.append(instance)
2374
        if pnode not in nimg.sbp:
2375
          nimg.sbp[pnode] = []
2376
        nimg.sbp[pnode].append(instance)
2377

    
2378
    # At this point, we have the in-memory data structures complete,
2379
    # except for the runtime information, which we'll gather next
2380

    
2381
    # Due to the way our RPC system works, exact response times cannot be
2382
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2383
    # time before and after executing the request, we can at least have a time
2384
    # window.
2385
    nvinfo_starttime = time.time()
2386
    all_nvinfo = self.rpc.call_node_verify(self.my_node_names,
2387
                                           node_verify_param,
2388
                                           self.cfg.GetClusterName())
2389
    nvinfo_endtime = time.time()
2390

    
2391
    all_drbd_map = self.cfg.ComputeDRBDMap()
2392

    
2393
    feedback_fn("* Gathering disk information (%s nodes)" %
2394
                len(self.my_node_names))
2395
    instdisk = self._CollectDiskInfo(self.my_node_names, node_image,
2396
                                     self.my_inst_info)
2397

    
2398
    feedback_fn("* Verifying configuration file consistency")
2399

    
2400
    # If not all nodes are being checked, we need to make sure the master node
2401
    # and a non-checked vm_capable node are in the list.
2402
    absent_nodes = set(self.all_node_info).difference(self.my_node_info)
2403
    if absent_nodes:
2404
      vf_nvinfo = all_nvinfo.copy()
2405
      vf_node_info = list(self.my_node_info.values())
2406
      additional_nodes = []
2407
      if master_node not in self.my_node_info:
2408
        additional_nodes.append(master_node)
2409
        vf_node_info.append(self.all_node_info[master_node])
2410
      # Add the first vm_capable node we find which is not included
2411
      for node in absent_nodes:
2412
        nodeinfo = self.all_node_info[node]
2413
        if nodeinfo.vm_capable and not nodeinfo.offline:
2414
          additional_nodes.append(node)
2415
          vf_node_info.append(self.all_node_info[node])
2416
          break
2417
      key = constants.NV_FILELIST
2418
      vf_nvinfo.update(self.rpc.call_node_verify(additional_nodes,
2419
                                                 {key: node_verify_param[key]},
2420
                                                 self.cfg.GetClusterName()))
2421
    else:
2422
      vf_nvinfo = all_nvinfo
2423
      vf_node_info = self.my_node_info.values()
2424

    
2425
    self._VerifyFiles(_ErrorIf, vf_node_info, master_node, vf_nvinfo, filemap)
2426

    
2427
    feedback_fn("* Verifying node status")
2428

    
2429
    refos_img = None
2430

    
2431
    for node_i in node_data_list:
2432
      node = node_i.name
2433
      nimg = node_image[node]
2434

    
2435
      if node_i.offline:
2436
        if verbose:
2437
          feedback_fn("* Skipping offline node %s" % (node,))
2438
        n_offline += 1
2439
        continue
2440

    
2441
      if node == master_node:
2442
        ntype = "master"
2443
      elif node_i.master_candidate:
2444
        ntype = "master candidate"
2445
      elif node_i.drained:
2446
        ntype = "drained"
2447
        n_drained += 1
2448
      else:
2449
        ntype = "regular"
2450
      if verbose:
2451
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2452

    
2453
      msg = all_nvinfo[node].fail_msg
2454
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2455
      if msg:
2456
        nimg.rpc_fail = True
2457
        continue
2458

    
2459
      nresult = all_nvinfo[node].payload
2460

    
2461
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2462
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2463
      self._VerifyNodeNetwork(node_i, nresult)
2464
      self._VerifyOob(node_i, nresult)
2465

    
2466
      if nimg.vm_capable:
2467
        self._VerifyNodeLVM(node_i, nresult, vg_name)
2468
        self._VerifyNodeDrbd(node_i, nresult, self.all_inst_info, drbd_helper,
2469
                             all_drbd_map)
2470

    
2471
        self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2472
        self._UpdateNodeInstances(node_i, nresult, nimg)
2473
        self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2474
        self._UpdateNodeOS(node_i, nresult, nimg)
2475

    
2476
        if not nimg.os_fail:
2477
          if refos_img is None:
2478
            refos_img = nimg
2479
          self._VerifyNodeOS(node_i, nimg, refos_img)
2480
        self._VerifyNodeBridges(node_i, nresult, bridges)
2481

    
2482
        # Check whether all running instancies are primary for the node. (This
2483
        # can no longer be done from _VerifyInstance below, since some of the
2484
        # wrong instances could be from other node groups.)
2485
        non_primary_inst = set(nimg.instances).difference(nimg.pinst)
2486

    
2487
        for inst in non_primary_inst:
2488
          test = inst in self.all_inst_info
2489
          _ErrorIf(test, self.EINSTANCEWRONGNODE, inst,
2490
                   "instance should not run on node %s", node_i.name)
2491
          _ErrorIf(not test, self.ENODEORPHANINSTANCE, node_i.name,
2492
                   "node is running unknown instance %s", inst)
2493

    
2494
    feedback_fn("* Verifying instance status")
2495
    for instance in self.my_inst_names:
2496
      if verbose:
2497
        feedback_fn("* Verifying instance %s" % instance)
2498
      inst_config = self.my_inst_info[instance]
2499
      self._VerifyInstance(instance, inst_config, node_image,
2500
                           instdisk[instance])
2501
      inst_nodes_offline = []
2502

    
2503
      pnode = inst_config.primary_node
2504
      pnode_img = node_image[pnode]
2505
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2506
               self.ENODERPC, pnode, "instance %s, connection to"
2507
               " primary node failed", instance)
2508

    
2509
      _ErrorIf(inst_config.admin_up and pnode_img.offline,
2510
               self.EINSTANCEBADNODE, instance,
2511
               "instance is marked as running and lives on offline node %s",
2512
               inst_config.primary_node)
2513

    
2514
      # If the instance is non-redundant we cannot survive losing its primary
2515
      # node, so we are not N+1 compliant. On the other hand we have no disk
2516
      # templates with more than one secondary so that situation is not well
2517
      # supported either.
2518
      # FIXME: does not support file-backed instances
2519
      if not inst_config.secondary_nodes:
2520
        i_non_redundant.append(instance)
2521

    
2522
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2523
               instance, "instance has multiple secondary nodes: %s",
2524
               utils.CommaJoin(inst_config.secondary_nodes),
2525
               code=self.ETYPE_WARNING)
2526

    
2527
      if inst_config.disk_template in constants.DTS_INT_MIRROR:
2528
        pnode = inst_config.primary_node
2529
        instance_nodes = utils.NiceSort(inst_config.all_nodes)
2530
        instance_groups = {}
2531

    
2532
        for node in instance_nodes:
2533
          instance_groups.setdefault(self.all_node_info[node].group,
2534
                                     []).append(node)
2535

    
2536
        pretty_list = [
2537
          "%s (group %s)" % (utils.CommaJoin(nodes), groupinfo[group].name)
2538
          # Sort so that we always list the primary node first.
2539
          for group, nodes in sorted(instance_groups.items(),
2540
                                     key=lambda (_, nodes): pnode in nodes,
2541
                                     reverse=True)]
2542

    
2543
        self._ErrorIf(len(instance_groups) > 1, self.EINSTANCESPLITGROUPS,
2544
                      instance, "instance has primary and secondary nodes in"
2545
                      " different groups: %s", utils.CommaJoin(pretty_list),
2546
                      code=self.ETYPE_WARNING)
2547

    
2548
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2549
        i_non_a_balanced.append(instance)
2550

    
2551
      for snode in inst_config.secondary_nodes:
2552
        s_img = node_image[snode]
2553
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2554
                 "instance %s, connection to secondary node failed", instance)
2555

    
2556
        if s_img.offline:
2557
          inst_nodes_offline.append(snode)
2558

    
2559
      # warn that the instance lives on offline nodes
2560
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2561
               "instance has offline secondary node(s) %s",
2562
               utils.CommaJoin(inst_nodes_offline))
2563
      # ... or ghost/non-vm_capable nodes
2564
      for node in inst_config.all_nodes:
2565
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2566
                 "instance lives on ghost node %s", node)
2567
        _ErrorIf(not node_image[node].vm_capable, self.EINSTANCEBADNODE,
2568
                 instance, "instance lives on non-vm_capable node %s", node)
2569

    
2570
    feedback_fn("* Verifying orphan volumes")
2571
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2572
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2573

    
2574
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2575
      feedback_fn("* Verifying N+1 Memory redundancy")
2576
      self._VerifyNPlusOneMemory(node_image, self.my_inst_info)
2577

    
2578
    feedback_fn("* Other Notes")
2579
    if i_non_redundant:
2580
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2581
                  % len(i_non_redundant))
2582

    
2583
    if i_non_a_balanced:
2584
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2585
                  % len(i_non_a_balanced))
2586

    
2587
    if n_offline:
2588
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2589

    
2590
    if n_drained:
2591
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2592

    
2593
    return not self.bad
2594

    
2595
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2596
    """Analyze the post-hooks' result
2597

2598
    This method analyses the hook result, handles it, and sends some
2599
    nicely-formatted feedback back to the user.
2600

2601
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2602
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2603
    @param hooks_results: the results of the multi-node hooks rpc call
2604
    @param feedback_fn: function used send feedback back to the caller
2605
    @param lu_result: previous Exec result
2606
    @return: the new Exec result, based on the previous result
2607
        and hook results
2608

2609
    """
2610
    # We only really run POST phase hooks, and are only interested in
2611
    # their results
2612
    if phase == constants.HOOKS_PHASE_POST:
2613
      # Used to change hooks' output to proper indentation
2614
      feedback_fn("* Hooks Results")
2615
      assert hooks_results, "invalid result from hooks"
2616

    
2617
      for node_name in hooks_results:
2618
        res = hooks_results[node_name]
2619
        msg = res.fail_msg
2620
        test = msg and not res.offline
2621
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2622
                      "Communication failure in hooks execution: %s", msg)
2623
        if res.offline or msg:
2624
          # No need to investigate payload if node is offline or gave an error.
2625
          # override manually lu_result here as _ErrorIf only
2626
          # overrides self.bad
2627
          lu_result = 1
2628
          continue
2629
        for script, hkr, output in res.payload:
2630
          test = hkr == constants.HKR_FAIL
2631
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2632
                        "Script %s failed, output:", script)
2633
          if test:
2634
            output = self._HOOKS_INDENT_RE.sub('      ', output)
2635
            feedback_fn("%s" % output)
2636
            lu_result = 0
2637

    
2638
      return lu_result
2639

    
2640

    
2641
class LUClusterVerifyDisks(NoHooksLU):
2642
  """Verifies the cluster disks status.
2643

2644
  """
2645
  REQ_BGL = False
2646

    
2647
  def ExpandNames(self):
2648
    self.needed_locks = {
2649
      locking.LEVEL_NODE: locking.ALL_SET,
2650
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2651
    }
2652
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2653

    
2654
  def Exec(self, feedback_fn):
2655
    """Verify integrity of cluster disks.
2656

2657
    @rtype: tuple of three items
2658
    @return: a tuple of (dict of node-to-node_error, list of instances
2659
        which need activate-disks, dict of instance: (node, volume) for
2660
        missing volumes
2661

2662
    """
2663
    result = res_nodes, res_instances, res_missing = {}, [], {}
2664

    
2665
    nodes = utils.NiceSort(self.cfg.GetVmCapableNodeList())
2666
    instances = self.cfg.GetAllInstancesInfo().values()
2667

    
2668
    nv_dict = {}
2669
    for inst in instances:
2670
      inst_lvs = {}
2671
      if not inst.admin_up:
2672
        continue
2673
      inst.MapLVsByNode(inst_lvs)
2674
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2675
      for node, vol_list in inst_lvs.iteritems():
2676
        for vol in vol_list:
2677
          nv_dict[(node, vol)] = inst
2678

    
2679
    if not nv_dict:
2680
      return result
2681

    
2682
    node_lvs = self.rpc.call_lv_list(nodes, [])
2683
    for node, node_res in node_lvs.items():
2684
      if node_res.offline:
2685
        continue
2686
      msg = node_res.fail_msg
2687
      if msg:
2688
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2689
        res_nodes[node] = msg
2690
        continue
2691

    
2692
      lvs = node_res.payload
2693
      for lv_name, (_, _, lv_online) in lvs.items():
2694
        inst = nv_dict.pop((node, lv_name), None)
2695
        if (not lv_online and inst is not None
2696
            and inst.name not in res_instances):
2697
          res_instances.append(inst.name)
2698

    
2699
    # any leftover items in nv_dict are missing LVs, let's arrange the
2700
    # data better
2701
    for key, inst in nv_dict.iteritems():
2702
      if inst.name not in res_missing:
2703
        res_missing[inst.name] = []
2704
      res_missing[inst.name].append(key)
2705

    
2706
    return result
2707

    
2708

    
2709
class LUClusterRepairDiskSizes(NoHooksLU):
2710
  """Verifies the cluster disks sizes.
2711

2712
  """
2713
  REQ_BGL = False
2714

    
2715
  def ExpandNames(self):
2716
    if self.op.instances:
2717
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
2718
      self.needed_locks = {
2719
        locking.LEVEL_NODE: [],
2720
        locking.LEVEL_INSTANCE: self.wanted_names,
2721
        }
2722
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2723
    else:
2724
      self.wanted_names = None
2725
      self.needed_locks = {
2726
        locking.LEVEL_NODE: locking.ALL_SET,
2727
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2728
        }
2729
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2730

    
2731
  def DeclareLocks(self, level):
2732
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2733
      self._LockInstancesNodes(primary_only=True)
2734

    
2735
  def CheckPrereq(self):
2736
    """Check prerequisites.
2737

2738
    This only checks the optional instance list against the existing names.
2739

2740
    """
2741
    if self.wanted_names is None:
2742
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
2743

    
2744
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2745
                             in self.wanted_names]
2746

    
2747
  def _EnsureChildSizes(self, disk):
2748
    """Ensure children of the disk have the needed disk size.
2749

2750
    This is valid mainly for DRBD8 and fixes an issue where the
2751
    children have smaller disk size.
2752

2753
    @param disk: an L{ganeti.objects.Disk} object
2754

2755
    """
2756
    if disk.dev_type == constants.LD_DRBD8:
2757
      assert disk.children, "Empty children for DRBD8?"
2758
      fchild = disk.children[0]
2759
      mismatch = fchild.size < disk.size
2760
      if mismatch:
2761
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2762
                     fchild.size, disk.size)
2763
        fchild.size = disk.size
2764

    
2765
      # and we recurse on this child only, not on the metadev
2766
      return self._EnsureChildSizes(fchild) or mismatch
2767
    else:
2768
      return False
2769

    
2770
  def Exec(self, feedback_fn):
2771
    """Verify the size of cluster disks.
2772

2773
    """
2774
    # TODO: check child disks too
2775
    # TODO: check differences in size between primary/secondary nodes
2776
    per_node_disks = {}
2777
    for instance in self.wanted_instances:
2778
      pnode = instance.primary_node
2779
      if pnode not in per_node_disks:
2780
        per_node_disks[pnode] = []
2781
      for idx, disk in enumerate(instance.disks):
2782
        per_node_disks[pnode].append((instance, idx, disk))
2783

    
2784
    changed = []
2785
    for node, dskl in per_node_disks.items():
2786
      newl = [v[2].Copy() for v in dskl]
2787
      for dsk in newl:
2788
        self.cfg.SetDiskID(dsk, node)
2789
      result = self.rpc.call_blockdev_getsize(node, newl)
2790
      if result.fail_msg:
2791
        self.LogWarning("Failure in blockdev_getsize call to node"
2792
                        " %s, ignoring", node)
2793
        continue
2794
      if len(result.payload) != len(dskl):
2795
        logging.warning("Invalid result from node %s: len(dksl)=%d,"
2796
                        " result.payload=%s", node, len(dskl), result.payload)
2797
        self.LogWarning("Invalid result from node %s, ignoring node results",
2798
                        node)
2799
        continue
2800
      for ((instance, idx, disk), size) in zip(dskl, result.payload):
2801
        if size is None:
2802
          self.LogWarning("Disk %d of instance %s did not return size"
2803
                          " information, ignoring", idx, instance.name)
2804
          continue
2805
        if not isinstance(size, (int, long)):
2806
          self.LogWarning("Disk %d of instance %s did not return valid"
2807
                          " size information, ignoring", idx, instance.name)
2808
          continue
2809
        size = size >> 20
2810
        if size != disk.size:
2811
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2812
                       " correcting: recorded %d, actual %d", idx,
2813
                       instance.name, disk.size, size)
2814
          disk.size = size
2815
          self.cfg.Update(instance, feedback_fn)
2816
          changed.append((instance.name, idx, size))
2817
        if self._EnsureChildSizes(disk):
2818
          self.cfg.Update(instance, feedback_fn)
2819
          changed.append((instance.name, idx, disk.size))
2820
    return changed
2821

    
2822

    
2823
class LUClusterRename(LogicalUnit):
2824
  """Rename the cluster.
2825

2826
  """
2827
  HPATH = "cluster-rename"
2828
  HTYPE = constants.HTYPE_CLUSTER
2829

    
2830
  def BuildHooksEnv(self):
2831
    """Build hooks env.
2832

2833
    """
2834
    return {
2835
      "OP_TARGET": self.cfg.GetClusterName(),
2836
      "NEW_NAME": self.op.name,
2837
      }
2838

    
2839
  def BuildHooksNodes(self):
2840
    """Build hooks nodes.
2841

2842
    """
2843
    return ([self.cfg.GetMasterNode()], self.cfg.GetNodeList())
2844

    
2845
  def CheckPrereq(self):
2846
    """Verify that the passed name is a valid one.
2847

2848
    """
2849
    hostname = netutils.GetHostname(name=self.op.name,
2850
                                    family=self.cfg.GetPrimaryIPFamily())
2851

    
2852
    new_name = hostname.name
2853
    self.ip = new_ip = hostname.ip
2854
    old_name = self.cfg.GetClusterName()
2855
    old_ip = self.cfg.GetMasterIP()
2856
    if new_name == old_name and new_ip == old_ip:
2857
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2858
                                 " cluster has changed",
2859
                                 errors.ECODE_INVAL)
2860
    if new_ip != old_ip:
2861
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2862
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2863
                                   " reachable on the network" %
2864
                                   new_ip, errors.ECODE_NOTUNIQUE)
2865

    
2866
    self.op.name = new_name
2867

    
2868
  def Exec(self, feedback_fn):
2869
    """Rename the cluster.
2870

2871
    """
2872
    clustername = self.op.name
2873
    ip = self.ip
2874

    
2875
    # shutdown the master IP
2876
    master = self.cfg.GetMasterNode()
2877
    result = self.rpc.call_node_stop_master(master, False)
2878
    result.Raise("Could not disable the master role")
2879

    
2880
    try:
2881
      cluster = self.cfg.GetClusterInfo()
2882
      cluster.cluster_name = clustername
2883
      cluster.master_ip = ip
2884
      self.cfg.Update(cluster, feedback_fn)
2885

    
2886
      # update the known hosts file
2887
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2888
      node_list = self.cfg.GetOnlineNodeList()
2889
      try:
2890
        node_list.remove(master)
2891
      except ValueError:
2892
        pass
2893
      _UploadHelper(self, node_list, constants.SSH_KNOWN_HOSTS_FILE)
2894
    finally:
2895
      result = self.rpc.call_node_start_master(master, False, False)
2896
      msg = result.fail_msg
2897
      if msg:
2898
        self.LogWarning("Could not re-enable the master role on"
2899
                        " the master, please restart manually: %s", msg)
2900

    
2901
    return clustername
2902

    
2903

    
2904
class LUClusterSetParams(LogicalUnit):
2905
  """Change the parameters of the cluster.
2906

2907
  """
2908
  HPATH = "cluster-modify"
2909
  HTYPE = constants.HTYPE_CLUSTER
2910
  REQ_BGL = False
2911

    
2912
  def CheckArguments(self):
2913
    """Check parameters
2914

2915
    """
2916
    if self.op.uid_pool:
2917
      uidpool.CheckUidPool(self.op.uid_pool)
2918

    
2919
    if self.op.add_uids:
2920
      uidpool.CheckUidPool(self.op.add_uids)
2921

    
2922
    if self.op.remove_uids:
2923
      uidpool.CheckUidPool(self.op.remove_uids)
2924

    
2925
  def ExpandNames(self):
2926
    # FIXME: in the future maybe other cluster params won't require checking on
2927
    # all nodes to be modified.
2928
    self.needed_locks = {
2929
      locking.LEVEL_NODE: locking.ALL_SET,
2930
    }
2931
    self.share_locks[locking.LEVEL_NODE] = 1
2932

    
2933
  def BuildHooksEnv(self):
2934
    """Build hooks env.
2935

2936
    """
2937
    return {
2938
      "OP_TARGET": self.cfg.GetClusterName(),
2939
      "NEW_VG_NAME": self.op.vg_name,
2940
      }
2941

    
2942
  def BuildHooksNodes(self):
2943
    """Build hooks nodes.
2944

2945
    """
2946
    mn = self.cfg.GetMasterNode()
2947
    return ([mn], [mn])
2948

    
2949
  def CheckPrereq(self):
2950
    """Check prerequisites.
2951

2952
    This checks whether the given params don't conflict and
2953
    if the given volume group is valid.
2954

2955
    """
2956
    if self.op.vg_name is not None and not self.op.vg_name:
2957
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2958
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2959
                                   " instances exist", errors.ECODE_INVAL)
2960

    
2961
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2962
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2963
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2964
                                   " drbd-based instances exist",
2965
                                   errors.ECODE_INVAL)
2966

    
2967
    node_list = self.glm.list_owned(locking.LEVEL_NODE)
2968

    
2969
    # if vg_name not None, checks given volume group on all nodes
2970
    if self.op.vg_name:
2971
      vglist = self.rpc.call_vg_list(node_list)
2972
      for node in node_list:
2973
        msg = vglist[node].fail_msg
2974
        if msg:
2975
          # ignoring down node
2976
          self.LogWarning("Error while gathering data on node %s"
2977
                          " (ignoring node): %s", node, msg)
2978
          continue
2979
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2980
                                              self.op.vg_name,
2981
                                              constants.MIN_VG_SIZE)
2982
        if vgstatus:
2983
          raise errors.OpPrereqError("Error on node '%s': %s" %
2984
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2985

    
2986
    if self.op.drbd_helper:
2987
      # checks given drbd helper on all nodes
2988
      helpers = self.rpc.call_drbd_helper(node_list)
2989
      for node in node_list:
2990
        ninfo = self.cfg.GetNodeInfo(node)
2991
        if ninfo.offline:
2992
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2993
          continue
2994
        msg = helpers[node].fail_msg
2995
        if msg:
2996
          raise errors.OpPrereqError("Error checking drbd helper on node"
2997
                                     " '%s': %s" % (node, msg),
2998
                                     errors.ECODE_ENVIRON)
2999
        node_helper = helpers[node].payload
3000
        if node_helper != self.op.drbd_helper:
3001
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
3002
                                     (node, node_helper), errors.ECODE_ENVIRON)
3003

    
3004
    self.cluster = cluster = self.cfg.GetClusterInfo()
3005
    # validate params changes
3006
    if self.op.beparams:
3007
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
3008
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
3009

    
3010
    if self.op.ndparams:
3011
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
3012
      self.new_ndparams = cluster.SimpleFillND(self.op.ndparams)
3013

    
3014
      # TODO: we need a more general way to handle resetting
3015
      # cluster-level parameters to default values
3016
      if self.new_ndparams["oob_program"] == "":
3017
        self.new_ndparams["oob_program"] = \
3018
            constants.NDC_DEFAULTS[constants.ND_OOB_PROGRAM]
3019

    
3020
    if self.op.nicparams:
3021
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
3022
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
3023
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
3024
      nic_errors = []
3025

    
3026
      # check all instances for consistency
3027
      for instance in self.cfg.GetAllInstancesInfo().values():
3028
        for nic_idx, nic in enumerate(instance.nics):
3029
          params_copy = copy.deepcopy(nic.nicparams)
3030
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
3031

    
3032
          # check parameter syntax
3033
          try:
3034
            objects.NIC.CheckParameterSyntax(params_filled)
3035
          except errors.ConfigurationError, err:
3036
            nic_errors.append("Instance %s, nic/%d: %s" %
3037
                              (instance.name, nic_idx, err))
3038

    
3039
          # if we're moving instances to routed, check that they have an ip
3040
          target_mode = params_filled[constants.NIC_MODE]
3041
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
3042
            nic_errors.append("Instance %s, nic/%d: routed NIC with no ip"
3043
                              " address" % (instance.name, nic_idx))
3044
      if nic_errors:
3045
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
3046
                                   "\n".join(nic_errors))
3047

    
3048
    # hypervisor list/parameters
3049
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
3050
    if self.op.hvparams:
3051
      for hv_name, hv_dict in self.op.hvparams.items():
3052
        if hv_name not in self.new_hvparams:
3053
          self.new_hvparams[hv_name] = hv_dict
3054
        else:
3055
          self.new_hvparams[hv_name].update(hv_dict)
3056

    
3057
    # os hypervisor parameters
3058
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
3059
    if self.op.os_hvp:
3060
      for os_name, hvs in self.op.os_hvp.items():
3061
        if os_name not in self.new_os_hvp:
3062
          self.new_os_hvp[os_name] = hvs
3063
        else:
3064
          for hv_name, hv_dict in hvs.items():
3065
            if hv_name not in self.new_os_hvp[os_name]:
3066
              self.new_os_hvp[os_name][hv_name] = hv_dict
3067
            else:
3068
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
3069

    
3070
    # os parameters
3071
    self.new_osp = objects.FillDict(cluster.osparams, {})
3072
    if self.op.osparams:
3073
      for os_name, osp in self.op.osparams.items():
3074
        if os_name not in self.new_osp:
3075
          self.new_osp[os_name] = {}
3076

    
3077
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
3078
                                                  use_none=True)
3079

    
3080
        if not self.new_osp[os_name]:
3081
          # we removed all parameters
3082
          del self.new_osp[os_name]
3083
        else:
3084
          # check the parameter validity (remote check)
3085
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
3086
                         os_name, self.new_osp[os_name])
3087

    
3088
    # changes to the hypervisor list
3089
    if self.op.enabled_hypervisors is not None:
3090
      self.hv_list = self.op.enabled_hypervisors
3091
      for hv in self.hv_list:
3092
        # if the hypervisor doesn't already exist in the cluster
3093
        # hvparams, we initialize it to empty, and then (in both
3094
        # cases) we make sure to fill the defaults, as we might not
3095
        # have a complete defaults list if the hypervisor wasn't
3096
        # enabled before
3097
        if hv not in new_hvp:
3098
          new_hvp[hv] = {}
3099
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
3100
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
3101
    else:
3102
      self.hv_list = cluster.enabled_hypervisors
3103

    
3104
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
3105
      # either the enabled list has changed, or the parameters have, validate
3106
      for hv_name, hv_params in self.new_hvparams.items():
3107
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
3108
            (self.op.enabled_hypervisors and
3109
             hv_name in self.op.enabled_hypervisors)):
3110
          # either this is a new hypervisor, or its parameters have changed
3111
          hv_class = hypervisor.GetHypervisor(hv_name)
3112
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3113
          hv_class.CheckParameterSyntax(hv_params)
3114
          _CheckHVParams(self, node_list, hv_name, hv_params)
3115

    
3116
    if self.op.os_hvp:
3117
      # no need to check any newly-enabled hypervisors, since the
3118
      # defaults have already been checked in the above code-block
3119
      for os_name, os_hvp in self.new_os_hvp.items():
3120
        for hv_name, hv_params in os_hvp.items():
3121
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
3122
          # we need to fill in the new os_hvp on top of the actual hv_p
3123
          cluster_defaults = self.new_hvparams.get(hv_name, {})
3124
          new_osp = objects.FillDict(cluster_defaults, hv_params)
3125
          hv_class = hypervisor.GetHypervisor(hv_name)
3126
          hv_class.CheckParameterSyntax(new_osp)
3127
          _CheckHVParams(self, node_list, hv_name, new_osp)
3128

    
3129
    if self.op.default_iallocator:
3130
      alloc_script = utils.FindFile(self.op.default_iallocator,
3131
                                    constants.IALLOCATOR_SEARCH_PATH,
3132
                                    os.path.isfile)
3133
      if alloc_script is None:
3134
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
3135
                                   " specified" % self.op.default_iallocator,
3136
                                   errors.ECODE_INVAL)
3137

    
3138
  def Exec(self, feedback_fn):
3139
    """Change the parameters of the cluster.
3140

3141
    """
3142
    if self.op.vg_name is not None:
3143
      new_volume = self.op.vg_name
3144
      if not new_volume:
3145
        new_volume = None
3146
      if new_volume != self.cfg.GetVGName():
3147
        self.cfg.SetVGName(new_volume)
3148
      else:
3149
        feedback_fn("Cluster LVM configuration already in desired"
3150
                    " state, not changing")
3151
    if self.op.drbd_helper is not None:
3152
      new_helper = self.op.drbd_helper
3153
      if not new_helper:
3154
        new_helper = None
3155
      if new_helper != self.cfg.GetDRBDHelper():
3156
        self.cfg.SetDRBDHelper(new_helper)
3157
      else:
3158
        feedback_fn("Cluster DRBD helper already in desired state,"
3159
                    " not changing")
3160
    if self.op.hvparams:
3161
      self.cluster.hvparams = self.new_hvparams
3162
    if self.op.os_hvp:
3163
      self.cluster.os_hvp = self.new_os_hvp
3164
    if self.op.enabled_hypervisors is not None:
3165
      self.cluster.hvparams = self.new_hvparams
3166
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
3167
    if self.op.beparams:
3168
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
3169
    if self.op.nicparams:
3170
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
3171
    if self.op.osparams:
3172
      self.cluster.osparams = self.new_osp
3173
    if self.op.ndparams:
3174
      self.cluster.ndparams = self.new_ndparams
3175

    
3176
    if self.op.candidate_pool_size is not None:
3177
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
3178
      # we need to update the pool size here, otherwise the save will fail
3179
      _AdjustCandidatePool(self, [])
3180

    
3181
    if self.op.maintain_node_health is not None:
3182
      self.cluster.maintain_node_health = self.op.maintain_node_health
3183

    
3184
    if self.op.prealloc_wipe_disks is not None:
3185
      self.cluster.prealloc_wipe_disks = self.op.prealloc_wipe_disks
3186

    
3187
    if self.op.add_uids is not None:
3188
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
3189

    
3190
    if self.op.remove_uids is not None:
3191
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
3192

    
3193
    if self.op.uid_pool is not None:
3194
      self.cluster.uid_pool = self.op.uid_pool
3195

    
3196
    if self.op.default_iallocator is not None:
3197
      self.cluster.default_iallocator = self.op.default_iallocator
3198

    
3199
    if self.op.reserved_lvs is not None:
3200
      self.cluster.reserved_lvs = self.op.reserved_lvs
3201

    
3202
    def helper_os(aname, mods, desc):
3203
      desc += " OS list"
3204
      lst = getattr(self.cluster, aname)
3205
      for key, val in mods:
3206
        if key == constants.DDM_ADD:
3207
          if val in lst:
3208
            feedback_fn("OS %s already in %s, ignoring" % (val, desc))
3209
          else:
3210
            lst.append(val)
3211
        elif key == constants.DDM_REMOVE:
3212
          if val in lst:
3213
            lst.remove(val)
3214
          else:
3215
            feedback_fn("OS %s not found in %s, ignoring" % (val, desc))
3216
        else:
3217
          raise errors.ProgrammerError("Invalid modification '%s'" % key)
3218

    
3219
    if self.op.hidden_os:
3220
      helper_os("hidden_os", self.op.hidden_os, "hidden")
3221

    
3222
    if self.op.blacklisted_os:
3223
      helper_os("blacklisted_os", self.op.blacklisted_os, "blacklisted")
3224

    
3225
    if self.op.master_netdev:
3226
      master = self.cfg.GetMasterNode()
3227
      feedback_fn("Shutting down master ip on the current netdev (%s)" %
3228
                  self.cluster.master_netdev)
3229
      result = self.rpc.call_node_stop_master(master, False)
3230
      result.Raise("Could not disable the master ip")
3231
      feedback_fn("Changing master_netdev from %s to %s" %
3232
                  (self.cluster.master_netdev, self.op.master_netdev))
3233
      self.cluster.master_netdev = self.op.master_netdev
3234

    
3235
    self.cfg.Update(self.cluster, feedback_fn)
3236

    
3237
    if self.op.master_netdev:
3238
      feedback_fn("Starting the master ip on the new master netdev (%s)" %
3239
                  self.op.master_netdev)
3240
      result = self.rpc.call_node_start_master(master, False, False)
3241
      if result.fail_msg:
3242
        self.LogWarning("Could not re-enable the master ip on"
3243
                        " the master, please restart manually: %s",
3244
                        result.fail_msg)
3245

    
3246

    
3247
def _UploadHelper(lu, nodes, fname):
3248
  """Helper for uploading a file and showing warnings.
3249

3250
  """
3251
  if os.path.exists(fname):
3252
    result = lu.rpc.call_upload_file(nodes, fname)
3253
    for to_node, to_result in result.items():
3254
      msg = to_result.fail_msg
3255
      if msg:
3256
        msg = ("Copy of file %s to node %s failed: %s" %
3257
               (fname, to_node, msg))
3258
        lu.proc.LogWarning(msg)
3259

    
3260

    
3261
def _ComputeAncillaryFiles(cluster, redist):
3262
  """Compute files external to Ganeti which need to be consistent.
3263

3264
  @type redist: boolean
3265
  @param redist: Whether to include files which need to be redistributed
3266

3267
  """
3268
  # Compute files for all nodes
3269
  files_all = set([
3270
    constants.SSH_KNOWN_HOSTS_FILE,
3271
    constants.CONFD_HMAC_KEY,
3272
    constants.CLUSTER_DOMAIN_SECRET_FILE,
3273
    ])
3274

    
3275
  if not redist:
3276
    files_all.update(constants.ALL_CERT_FILES)
3277
    files_all.update(ssconf.SimpleStore().GetFileList())
3278

    
3279
  if cluster.modify_etc_hosts:
3280
    files_all.add(constants.ETC_HOSTS)
3281

    
3282
  # Files which must either exist on all nodes or on none
3283
  files_all_opt = set([
3284
    constants.RAPI_USERS_FILE,
3285
    ])
3286

    
3287
  # Files which should only be on master candidates
3288
  files_mc = set()
3289
  if not redist:
3290
    files_mc.add(constants.CLUSTER_CONF_FILE)
3291

    
3292
  # Files which should only be on VM-capable nodes
3293
  files_vm = set(filename
3294
    for hv_name in cluster.enabled_hypervisors
3295
    for filename in hypervisor.GetHypervisor(hv_name).GetAncillaryFiles())
3296

    
3297
  # Filenames must be unique
3298
  assert (len(files_all | files_all_opt | files_mc | files_vm) ==
3299
          sum(map(len, [files_all, files_all_opt, files_mc, files_vm]))), \
3300
         "Found file listed in more than one file list"
3301

    
3302
  return (files_all, files_all_opt, files_mc, files_vm)
3303

    
3304

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

3308
  ConfigWriter takes care of distributing the config and ssconf files, but
3309
  there are more files which should be distributed to all nodes. This function
3310
  makes sure those are copied.
3311

3312
  @param lu: calling logical unit
3313
  @param additional_nodes: list of nodes not in the config to distribute to
3314
  @type additional_vm: boolean
3315
  @param additional_vm: whether the additional nodes are vm-capable or not
3316

3317
  """
3318
  # Gather target nodes
3319
  cluster = lu.cfg.GetClusterInfo()
3320
  master_info = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
3321

    
3322
  online_nodes = lu.cfg.GetOnlineNodeList()
3323
  vm_nodes = lu.cfg.GetVmCapableNodeList()
3324

    
3325
  if additional_nodes is not None:
3326
    online_nodes.extend(additional_nodes)
3327
    if additional_vm:
3328
      vm_nodes.extend(additional_nodes)
3329

    
3330
  # Never distribute to master node
3331
  for nodelist in [online_nodes, vm_nodes]:
3332
    if master_info.name in nodelist:
3333
      nodelist.remove(master_info.name)
3334

    
3335
  # Gather file lists
3336
  (files_all, files_all_opt, files_mc, files_vm) = \
3337
    _ComputeAncillaryFiles(cluster, True)
3338

    
3339
  # Never re-distribute configuration file from here
3340
  assert not (constants.CLUSTER_CONF_FILE in files_all or
3341
              constants.CLUSTER_CONF_FILE in files_vm)
3342
  assert not files_mc, "Master candidates not handled in this function"
3343

    
3344
  filemap = [
3345
    (online_nodes, files_all),
3346
    (online_nodes, files_all_opt),
3347
    (vm_nodes, files_vm),
3348
    ]
3349

    
3350
  # Upload the files
3351
  for (node_list, files) in filemap:
3352
    for fname in files:
3353
      _UploadHelper(lu, node_list, fname)
3354

    
3355

    
3356
class LUClusterRedistConf(NoHooksLU):
3357
  """Force the redistribution of cluster configuration.
3358

3359
  This is a very simple LU.
3360

3361
  """
3362
  REQ_BGL = False
3363

    
3364
  def ExpandNames(self):
3365
    self.needed_locks = {
3366
      locking.LEVEL_NODE: locking.ALL_SET,
3367
    }
3368
    self.share_locks[locking.LEVEL_NODE] = 1
3369

    
3370
  def Exec(self, feedback_fn):
3371
    """Redistribute the configuration.
3372

3373
    """
3374
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
3375
    _RedistributeAncillaryFiles(self)
3376

    
3377

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

3381
  """
3382
  if not instance.disks or disks is not None and not disks:
3383
    return True
3384

    
3385
  disks = _ExpandCheckDisks(instance, disks)
3386

    
3387
  if not oneshot:
3388
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
3389

    
3390
  node = instance.primary_node
3391

    
3392
  for dev in disks:
3393
    lu.cfg.SetDiskID(dev, node)
3394

    
3395
  # TODO: Convert to utils.Retry
3396

    
3397
  retries = 0
3398
  degr_retries = 10 # in seconds, as we sleep 1 second each time
3399
  while True:
3400
    max_time = 0
3401
    done = True
3402
    cumul_degraded = False
3403
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
3404
    msg = rstats.fail_msg
3405
    if msg:
3406
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3407
      retries += 1
3408
      if retries >= 10:
3409
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3410
                                 " aborting." % node)
3411
      time.sleep(6)
3412
      continue
3413
    rstats = rstats.payload
3414
    retries = 0
3415
    for i, mstat in enumerate(rstats):
3416
      if mstat is None:
3417
        lu.LogWarning("Can't compute data for node %s/%s",
3418
                           node, disks[i].iv_name)
3419
        continue
3420

    
3421
      cumul_degraded = (cumul_degraded or
3422
                        (mstat.is_degraded and mstat.sync_percent is None))
3423
      if mstat.sync_percent is not None:
3424
        done = False
3425
        if mstat.estimated_time is not None:
3426
          rem_time = ("%s remaining (estimated)" %
3427
                      utils.FormatSeconds(mstat.estimated_time))
3428
          max_time = mstat.estimated_time
3429
        else:
3430
          rem_time = "no time estimate"
3431
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3432
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3433

    
3434
    # if we're done but degraded, let's do a few small retries, to
3435
    # make sure we see a stable and not transient situation; therefore
3436
    # we force restart of the loop
3437
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3438
      logging.info("Degraded disks found, %d retries left", degr_retries)
3439
      degr_retries -= 1
3440
      time.sleep(1)
3441
      continue
3442

    
3443
    if done or oneshot:
3444
      break
3445

    
3446
    time.sleep(min(60, max_time))
3447

    
3448
  if done:
3449
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3450
  return not cumul_degraded
3451

    
3452

    
3453
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3454
  """Check that mirrors are not degraded.
3455

3456
  The ldisk parameter, if True, will change the test from the
3457
  is_degraded attribute (which represents overall non-ok status for
3458
  the device(s)) to the ldisk (representing the local storage status).
3459

3460
  """
3461
  lu.cfg.SetDiskID(dev, node)
3462

    
3463
  result = True
3464

    
3465
  if on_primary or dev.AssembleOnSecondary():
3466
    rstats = lu.rpc.call_blockdev_find(node, dev)
3467
    msg = rstats.fail_msg
3468
    if msg:
3469
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3470
      result = False
3471
    elif not rstats.payload:
3472
      lu.LogWarning("Can't find disk on node %s", node)
3473
      result = False
3474
    else:
3475
      if ldisk:
3476
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3477
      else:
3478
        result = result and not rstats.payload.is_degraded
3479

    
3480
  if dev.children:
3481
    for child in dev.children:
3482
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3483

    
3484
  return result
3485

    
3486

    
3487
class LUOobCommand(NoHooksLU):
3488
  """Logical unit for OOB handling.
3489

3490
  """
3491
  REG_BGL = False
3492
  _SKIP_MASTER = (constants.OOB_POWER_OFF, constants.OOB_POWER_CYCLE)
3493

    
3494
  def ExpandNames(self):
3495
    """Gather locks we need.
3496

3497
    """
3498
    if self.op.node_names:
3499
      self.op.node_names = _GetWantedNodes(self, self.op.node_names)
3500
      lock_names = self.op.node_names
3501
    else:
3502
      lock_names = locking.ALL_SET
3503

    
3504
    self.needed_locks = {
3505
      locking.LEVEL_NODE: lock_names,
3506
      }
3507

    
3508
  def CheckPrereq(self):
3509
    """Check prerequisites.
3510

3511
    This checks:
3512
     - the node exists in the configuration
3513
     - OOB is supported
3514

3515
    Any errors are signaled by raising errors.OpPrereqError.
3516

3517
    """
3518
    self.nodes = []
3519
    self.master_node = self.cfg.GetMasterNode()
3520

    
3521
    assert self.op.power_delay >= 0.0
3522

    
3523
    if self.op.node_names:
3524
      if (self.op.command in self._SKIP_MASTER and
3525
          self.master_node in self.op.node_names):
3526
        master_node_obj = self.cfg.GetNodeInfo(self.master_node)
3527
        master_oob_handler = _SupportsOob(self.cfg, master_node_obj)
3528

    
3529
        if master_oob_handler:
3530
          additional_text = ("run '%s %s %s' if you want to operate on the"
3531
                             " master regardless") % (master_oob_handler,
3532
                                                      self.op.command,
3533
                                                      self.master_node)
3534
        else:
3535
          additional_text = "it does not support out-of-band operations"
3536

    
3537
        raise errors.OpPrereqError(("Operating on the master node %s is not"
3538
                                    " allowed for %s; %s") %
3539
                                   (self.master_node, self.op.command,
3540
                                    additional_text), errors.ECODE_INVAL)
3541
    else:
3542
      self.op.node_names = self.cfg.GetNodeList()
3543
      if self.op.command in self._SKIP_MASTER:
3544
        self.op.node_names.remove(self.master_node)
3545

    
3546
    if self.op.command in self._SKIP_MASTER:
3547
      assert self.master_node not in self.op.node_names
3548

    
3549
    for node_name in self.op.node_names:
3550
      node = self.cfg.GetNodeInfo(node_name)
3551

    
3552
      if node is None:
3553
        raise errors.OpPrereqError("Node %s not found" % node_name,
3554
                                   errors.ECODE_NOENT)
3555
      else:
3556
        self.nodes.append(node)
3557

    
3558
      if (not self.op.ignore_status and
3559
          (self.op.command == constants.OOB_POWER_OFF and not node.offline)):
3560
        raise errors.OpPrereqError(("Cannot power off node %s because it is"
3561
                                    " not marked offline") % node_name,
3562
                                   errors.ECODE_STATE)
3563

    
3564
  def Exec(self, feedback_fn):
3565
    """Execute OOB and return result if we expect any.
3566

3567
    """
3568
    master_node = self.master_node
3569
    ret = []
3570

    
3571
    for idx, node in enumerate(utils.NiceSort(self.nodes,
3572
                                              key=lambda node: node.name)):
3573
      node_entry = [(constants.RS_NORMAL, node.name)]
3574
      ret.append(node_entry)
3575

    
3576
      oob_program = _SupportsOob(self.cfg, node)
3577

    
3578
      if not oob_program:
3579
        node_entry.append((constants.RS_UNAVAIL, None))
3580
        continue
3581

    
3582
      logging.info("Executing out-of-band command '%s' using '%s' on %s",
3583
                   self.op.command, oob_program, node.name)
3584
      result = self.rpc.call_run_oob(master_node, oob_program,
3585
                                     self.op.command, node.name,
3586
                                     self.op.timeout)
3587

    
3588
      if result.fail_msg:
3589
        self.LogWarning("Out-of-band RPC failed on node '%s': %s",
3590
                        node.name, result.fail_msg)
3591
        node_entry.append((constants.RS_NODATA, None))
3592
      else:
3593
        try:
3594
          self._CheckPayload(result)
3595
        except errors.OpExecError, err:
3596
          self.LogWarning("Payload returned by node '%s' is not valid: %s",
3597
                          node.name, err)
3598
          node_entry.append((constants.RS_NODATA, None))
3599
        else:
3600
          if self.op.command == constants.OOB_HEALTH:
3601
            # For health we should log important events
3602
            for item, status in result.payload:
3603
              if status in [constants.OOB_STATUS_WARNING,
3604
                            constants.OOB_STATUS_CRITICAL]:
3605
                self.LogWarning("Item '%s' on node '%s' has status '%s'",
3606
                                item, node.name, status)
3607

    
3608
          if self.op.command == constants.OOB_POWER_ON:
3609
            node.powered = True
3610
          elif self.op.command == constants.OOB_POWER_OFF:
3611
            node.powered = False
3612
          elif self.op.command == constants.OOB_POWER_STATUS:
3613
            powered = result.payload[constants.OOB_POWER_STATUS_POWERED]
3614
            if powered != node.powered:
3615
              logging.warning(("Recorded power state (%s) of node '%s' does not"
3616
                               " match actual power state (%s)"), node.powered,
3617
                              node.name, powered)
3618

    
3619
          # For configuration changing commands we should update the node
3620
          if self.op.command in (constants.OOB_POWER_ON,
3621
                                 constants.OOB_POWER_OFF):
3622
            self.cfg.Update(node, feedback_fn)
3623

    
3624
          node_entry.append((constants.RS_NORMAL, result.payload))
3625

    
3626
          if (self.op.command == constants.OOB_POWER_ON and
3627
              idx < len(self.nodes) - 1):
3628
            time.sleep(self.op.power_delay)
3629

    
3630
    return ret
3631

    
3632
  def _CheckPayload(self, result):
3633
    """Checks if the payload is valid.
3634

3635
    @param result: RPC result
3636
    @raises errors.OpExecError: If payload is not valid
3637

3638
    """
3639
    errs = []
3640
    if self.op.command == constants.OOB_HEALTH:
3641
      if not isinstance(result.payload, list):
3642
        errs.append("command 'health' is expected to return a list but got %s" %
3643
                    type(result.payload))
3644
      else:
3645
        for item, status in result.payload:
3646
          if status not in constants.OOB_STATUSES:
3647
            errs.append("health item '%s' has invalid status '%s'" %
3648
                        (item, status))
3649

    
3650
    if self.op.command == constants.OOB_POWER_STATUS:
3651
      if not isinstance(result.payload, dict):
3652
        errs.append("power-status is expected to return a dict but got %s" %
3653
                    type(result.payload))
3654

    
3655
    if self.op.command in [
3656
        constants.OOB_POWER_ON,
3657
        constants.OOB_POWER_OFF,
3658
        constants.OOB_POWER_CYCLE,
3659
        ]:
3660
      if result.payload is not None:
3661
        errs.append("%s is expected to not return payload but got '%s'" %
3662
                    (self.op.command, result.payload))
3663

    
3664
    if errs:
3665
      raise errors.OpExecError("Check of out-of-band payload failed due to %s" %
3666
                               utils.CommaJoin(errs))
3667

    
3668
class _OsQuery(_QueryBase):
3669
  FIELDS = query.OS_FIELDS
3670

    
3671
  def ExpandNames(self, lu):
3672
    # Lock all nodes in shared mode
3673
    # Temporary removal of locks, should be reverted later
3674
    # TODO: reintroduce locks when they are lighter-weight
3675
    lu.needed_locks = {}
3676
    #self.share_locks[locking.LEVEL_NODE] = 1
3677
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3678

    
3679
    # The following variables interact with _QueryBase._GetNames
3680
    if self.names:
3681
      self.wanted = self.names
3682
    else:
3683
      self.wanted = locking.ALL_SET
3684

    
3685
    self.do_locking = self.use_locking
3686

    
3687
  def DeclareLocks(self, lu, level):
3688
    pass
3689

    
3690
  @staticmethod
3691
  def _DiagnoseByOS(rlist):
3692
    """Remaps a per-node return list into an a per-os per-node dictionary
3693

3694
    @param rlist: a map with node names as keys and OS objects as values
3695

3696
    @rtype: dict
3697
    @return: a dictionary with osnames as keys and as value another
3698
        map, with nodes as keys and tuples of (path, status, diagnose,
3699
        variants, parameters, api_versions) as values, eg::
3700

3701
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3702
                                     (/srv/..., False, "invalid api")],
3703
                           "node2": [(/srv/..., True, "", [], [])]}
3704
          }
3705

3706
    """
3707
    all_os = {}
3708
    # we build here the list of nodes that didn't fail the RPC (at RPC
3709
    # level), so that nodes with a non-responding node daemon don't
3710
    # make all OSes invalid
3711
    good_nodes = [node_name for node_name in rlist
3712
                  if not rlist[node_name].fail_msg]
3713
    for node_name, nr in rlist.items():
3714
      if nr.fail_msg or not nr.payload:
3715
        continue
3716
      for (name, path, status, diagnose, variants,
3717
           params, api_versions) in nr.payload:
3718
        if name not in all_os:
3719
          # build a list of nodes for this os containing empty lists
3720
          # for each node in node_list
3721
          all_os[name] = {}
3722
          for nname in good_nodes:
3723
            all_os[name][nname] = []
3724
        # convert params from [name, help] to (name, help)
3725
        params = [tuple(v) for v in params]
3726
        all_os[name][node_name].append((path, status, diagnose,
3727
                                        variants, params, api_versions))
3728
    return all_os
3729

    
3730
  def _GetQueryData(self, lu):
3731
    """Computes the list of nodes and their attributes.
3732

3733
    """
3734
    # Locking is not used
3735
    assert not (compat.any(lu.glm.is_owned(level)
3736
                           for level in locking.LEVELS
3737
                           if level != locking.LEVEL_CLUSTER) or
3738
                self.do_locking or self.use_locking)
3739

    
3740
    valid_nodes = [node.name
3741
                   for node in lu.cfg.GetAllNodesInfo().values()
3742
                   if not node.offline and node.vm_capable]
3743
    pol = self._DiagnoseByOS(lu.rpc.call_os_diagnose(valid_nodes))
3744
    cluster = lu.cfg.GetClusterInfo()
3745

    
3746
    data = {}
3747

    
3748
    for (os_name, os_data) in pol.items():
3749
      info = query.OsInfo(name=os_name, valid=True, node_status=os_data,
3750
                          hidden=(os_name in cluster.hidden_os),
3751
                          blacklisted=(os_name in cluster.blacklisted_os))
3752

    
3753
      variants = set()
3754
      parameters = set()
3755
      api_versions = set()
3756

    
3757
      for idx, osl in enumerate(os_data.values()):
3758
        info.valid = bool(info.valid and osl and osl[0][1])
3759
        if not info.valid:
3760
          break
3761

    
3762
        (node_variants, node_params, node_api) = osl[0][3:6]
3763
        if idx == 0:
3764
          # First entry
3765
          variants.update(node_variants)
3766
          parameters.update(node_params)
3767
          api_versions.update(node_api)
3768
        else:
3769
          # Filter out inconsistent values
3770
          variants.intersection_update(node_variants)
3771
          parameters.intersection_update(node_params)
3772
          api_versions.intersection_update(node_api)
3773

    
3774
      info.variants = list(variants)
3775
      info.parameters = list(parameters)
3776
      info.api_versions = list(api_versions)
3777

    
3778
      data[os_name] = info
3779

    
3780
    # Prepare data in requested order
3781
    return [data[name] for name in self._GetNames(lu, pol.keys(), None)
3782
            if name in data]
3783

    
3784

    
3785
class LUOsDiagnose(NoHooksLU):
3786
  """Logical unit for OS diagnose/query.
3787

3788
  """
3789
  REQ_BGL = False
3790

    
3791
  @staticmethod
3792
  def _BuildFilter(fields, names):
3793
    """Builds a filter for querying OSes.
3794

3795
    """
3796
    name_filter = qlang.MakeSimpleFilter("name", names)
3797

    
3798
    # Legacy behaviour: Hide hidden, blacklisted or invalid OSes if the
3799
    # respective field is not requested
3800
    status_filter = [[qlang.OP_NOT, [qlang.OP_TRUE, fname]]
3801
                     for fname in ["hidden", "blacklisted"]
3802
                     if fname not in fields]
3803
    if "valid" not in fields:
3804
      status_filter.append([qlang.OP_TRUE, "valid"])
3805

    
3806
    if status_filter:
3807
      status_filter.insert(0, qlang.OP_AND)
3808
    else:
3809
      status_filter = None
3810

    
3811
    if name_filter and status_filter:
3812
      return [qlang.OP_AND, name_filter, status_filter]
3813
    elif name_filter:
3814
      return name_filter
3815
    else:
3816
      return status_filter
3817

    
3818
  def CheckArguments(self):
3819
    self.oq = _OsQuery(self._BuildFilter(self.op.output_fields, self.op.names),
3820
                       self.op.output_fields, False)
3821

    
3822
  def ExpandNames(self):
3823
    self.oq.ExpandNames(self)
3824

    
3825
  def Exec(self, feedback_fn):
3826
    return self.oq.OldStyleQuery(self)
3827

    
3828

    
3829
class LUNodeRemove(LogicalUnit):
3830
  """Logical unit for removing a node.
3831

3832
  """
3833
  HPATH = "node-remove"
3834
  HTYPE = constants.HTYPE_NODE
3835

    
3836
  def BuildHooksEnv(self):
3837
    """Build hooks env.
3838

3839
    This doesn't run on the target node in the pre phase as a failed
3840
    node would then be impossible to remove.
3841

3842
    """
3843
    return {
3844
      "OP_TARGET": self.op.node_name,
3845
      "NODE_NAME": self.op.node_name,
3846
      }
3847

    
3848
  def BuildHooksNodes(self):
3849
    """Build hooks nodes.
3850

3851
    """
3852
    all_nodes = self.cfg.GetNodeList()
3853
    try:
3854
      all_nodes.remove(self.op.node_name)
3855
    except ValueError:
3856
      logging.warning("Node '%s', which is about to be removed, was not found"
3857
                      " in the list of all nodes", self.op.node_name)
3858
    return (all_nodes, all_nodes)
3859

    
3860
  def CheckPrereq(self):
3861
    """Check prerequisites.
3862

3863
    This checks:
3864
     - the node exists in the configuration
3865
     - it does not have primary or secondary instances
3866
     - it's not the master
3867

3868
    Any errors are signaled by raising errors.OpPrereqError.
3869

3870
    """
3871
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3872
    node = self.cfg.GetNodeInfo(self.op.node_name)
3873
    assert node is not None
3874

    
3875
    instance_list = self.cfg.GetInstanceList()
3876

    
3877
    masternode = self.cfg.GetMasterNode()
3878
    if node.name == masternode:
3879
      raise errors.OpPrereqError("Node is the master node, failover to another"
3880
                                 " node is required", errors.ECODE_INVAL)
3881

    
3882
    for instance_name in instance_list:
3883
      instance = self.cfg.GetInstanceInfo(instance_name)
3884
      if node.name in instance.all_nodes:
3885
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3886
                                   " please remove first" % instance_name,
3887
                                   errors.ECODE_INVAL)
3888
    self.op.node_name = node.name
3889
    self.node = node
3890

    
3891
  def Exec(self, feedback_fn):
3892
    """Removes the node from the cluster.
3893

3894
    """
3895
    node = self.node
3896
    logging.info("Stopping the node daemon and removing configs from node %s",
3897
                 node.name)
3898

    
3899
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3900

    
3901
    # Promote nodes to master candidate as needed
3902
    _AdjustCandidatePool(self, exceptions=[node.name])
3903
    self.context.RemoveNode(node.name)
3904

    
3905
    # Run post hooks on the node before it's removed
3906
    _RunPostHook(self, node.name)
3907

    
3908
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3909
    msg = result.fail_msg
3910
    if msg:
3911
      self.LogWarning("Errors encountered on the remote node while leaving"
3912
                      " the cluster: %s", msg)
3913

    
3914
    # Remove node from our /etc/hosts
3915
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3916
      master_node = self.cfg.GetMasterNode()
3917
      result = self.rpc.call_etc_hosts_modify(master_node,
3918
                                              constants.ETC_HOSTS_REMOVE,
3919
                                              node.name, None)
3920
      result.Raise("Can't update hosts file with new host data")
3921
      _RedistributeAncillaryFiles(self)
3922

    
3923

    
3924
class _NodeQuery(_QueryBase):
3925
  FIELDS = query.NODE_FIELDS
3926

    
3927
  def ExpandNames(self, lu):
3928
    lu.needed_locks = {}
3929
    lu.share_locks[locking.LEVEL_NODE] = 1
3930

    
3931
    if self.names:
3932
      self.wanted = _GetWantedNodes(lu, self.names)
3933
    else:
3934
      self.wanted = locking.ALL_SET
3935

    
3936
    self.do_locking = (self.use_locking and
3937
                       query.NQ_LIVE in self.requested_data)
3938

    
3939
    if self.do_locking:
3940
      # if we don't request only static fields, we need to lock the nodes
3941
      lu.needed_locks[locking.LEVEL_NODE] = self.wanted
3942

    
3943
  def DeclareLocks(self, lu, level):
3944
    pass
3945

    
3946
  def _GetQueryData(self, lu):
3947
    """Computes the list of nodes and their attributes.
3948

3949
    """
3950
    all_info = lu.cfg.GetAllNodesInfo()
3951

    
3952
    nodenames = self._GetNames(lu, all_info.keys(), locking.LEVEL_NODE)
3953

    
3954
    # Gather data as requested
3955
    if query.NQ_LIVE in self.requested_data:
3956
      # filter out non-vm_capable nodes
3957
      toquery_nodes = [name for name in nodenames if all_info[name].vm_capable]
3958

    
3959
      node_data = lu.rpc.call_node_info(toquery_nodes, lu.cfg.GetVGName(),
3960
                                        lu.cfg.GetHypervisorType())
3961
      live_data = dict((name, nresult.payload)
3962
                       for (name, nresult) in node_data.items()
3963
                       if not nresult.fail_msg and nresult.payload)
3964
    else:
3965
      live_data = None
3966

    
3967
    if query.NQ_INST in self.requested_data:
3968
      node_to_primary = dict([(name, set()) for name in nodenames])
3969
      node_to_secondary = dict([(name, set()) for name in nodenames])
3970

    
3971
      inst_data = lu.cfg.GetAllInstancesInfo()
3972

    
3973
      for inst in inst_data.values():
3974
        if inst.primary_node in node_to_primary:
3975
          node_to_primary[inst.primary_node].add(inst.name)
3976
        for secnode in inst.secondary_nodes:
3977
          if secnode in node_to_secondary:
3978
            node_to_secondary[secnode].add(inst.name)
3979
    else:
3980
      node_to_primary = None
3981
      node_to_secondary = None
3982

    
3983
    if query.NQ_OOB in self.requested_data:
3984
      oob_support = dict((name, bool(_SupportsOob(lu.cfg, node)))
3985
                         for name, node in all_info.iteritems())
3986
    else:
3987
      oob_support = None
3988

    
3989
    if query.NQ_GROUP in self.requested_data:
3990
      groups = lu.cfg.GetAllNodeGroupsInfo()
3991
    else:
3992
      groups = {}
3993

    
3994
    return query.NodeQueryData([all_info[name] for name in nodenames],
3995
                               live_data, lu.cfg.GetMasterNode(),
3996
                               node_to_primary, node_to_secondary, groups,
3997
                               oob_support, lu.cfg.GetClusterInfo())
3998

    
3999

    
4000
class LUNodeQuery(NoHooksLU):
4001
  """Logical unit for querying nodes.
4002

4003
  """
4004
  # pylint: disable-msg=W0142
4005
  REQ_BGL = False
4006

    
4007
  def CheckArguments(self):
4008
    self.nq = _NodeQuery(qlang.MakeSimpleFilter("name", self.op.names),
4009
                         self.op.output_fields, self.op.use_locking)
4010

    
4011
  def ExpandNames(self):
4012
    self.nq.ExpandNames(self)
4013

    
4014
  def Exec(self, feedback_fn):
4015
    return self.nq.OldStyleQuery(self)
4016

    
4017

    
4018
class LUNodeQueryvols(NoHooksLU):
4019
  """Logical unit for getting volumes on node(s).
4020

4021
  """
4022
  REQ_BGL = False
4023
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
4024
  _FIELDS_STATIC = utils.FieldSet("node")
4025

    
4026
  def CheckArguments(self):
4027
    _CheckOutputFields(static=self._FIELDS_STATIC,
4028
                       dynamic=self._FIELDS_DYNAMIC,
4029
                       selected=self.op.output_fields)
4030

    
4031
  def ExpandNames(self):
4032
    self.needed_locks = {}
4033
    self.share_locks[locking.LEVEL_NODE] = 1
4034
    if not self.op.nodes:
4035
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4036
    else:
4037
      self.needed_locks[locking.LEVEL_NODE] = \
4038
        _GetWantedNodes(self, self.op.nodes)
4039

    
4040
  def Exec(self, feedback_fn):
4041
    """Computes the list of nodes and their attributes.
4042

4043
    """
4044
    nodenames = self.glm.list_owned(locking.LEVEL_NODE)
4045
    volumes = self.rpc.call_node_volumes(nodenames)
4046

    
4047
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
4048
             in self.cfg.GetInstanceList()]
4049

    
4050
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
4051

    
4052
    output = []
4053
    for node in nodenames:
4054
      nresult = volumes[node]
4055
      if nresult.offline:
4056
        continue
4057
      msg = nresult.fail_msg
4058
      if msg:
4059
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
4060
        continue
4061

    
4062
      node_vols = nresult.payload[:]
4063
      node_vols.sort(key=lambda vol: vol['dev'])
4064

    
4065
      for vol in node_vols:
4066
        node_output = []
4067
        for field in self.op.output_fields:
4068
          if field == "node":
4069
            val = node
4070
          elif field == "phys":
4071
            val = vol['dev']
4072
          elif field == "vg":
4073
            val = vol['vg']
4074
          elif field == "name":
4075
            val = vol['name']
4076
          elif field == "size":
4077
            val = int(float(vol['size']))
4078
          elif field == "instance":
4079
            for inst in ilist:
4080
              if node not in lv_by_node[inst]:
4081
                continue
4082
              if vol['name'] in lv_by_node[inst][node]:
4083
                val = inst.name
4084
                break
4085
            else:
4086
              val = '-'
4087
          else:
4088
            raise errors.ParameterError(field)
4089
          node_output.append(str(val))
4090

    
4091
        output.append(node_output)
4092

    
4093
    return output
4094

    
4095

    
4096
class LUNodeQueryStorage(NoHooksLU):
4097
  """Logical unit for getting information on storage units on node(s).
4098

4099
  """
4100
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
4101
  REQ_BGL = False
4102

    
4103
  def CheckArguments(self):
4104
    _CheckOutputFields(static=self._FIELDS_STATIC,
4105
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
4106
                       selected=self.op.output_fields)
4107

    
4108
  def ExpandNames(self):
4109
    self.needed_locks = {}
4110
    self.share_locks[locking.LEVEL_NODE] = 1
4111

    
4112
    if self.op.nodes:
4113
      self.needed_locks[locking.LEVEL_NODE] = \
4114
        _GetWantedNodes(self, self.op.nodes)
4115
    else:
4116
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
4117

    
4118
  def Exec(self, feedback_fn):
4119
    """Computes the list of nodes and their attributes.
4120

4121
    """
4122
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
4123

    
4124
    # Always get name to sort by
4125
    if constants.SF_NAME in self.op.output_fields:
4126
      fields = self.op.output_fields[:]
4127
    else:
4128
      fields = [constants.SF_NAME] + self.op.output_fields
4129

    
4130
    # Never ask for node or type as it's only known to the LU
4131
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
4132
      while extra in fields:
4133
        fields.remove(extra)
4134

    
4135
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
4136
    name_idx = field_idx[constants.SF_NAME]
4137

    
4138
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4139
    data = self.rpc.call_storage_list(self.nodes,
4140
                                      self.op.storage_type, st_args,
4141
                                      self.op.name, fields)
4142

    
4143
    result = []
4144

    
4145
    for node in utils.NiceSort(self.nodes):
4146
      nresult = data[node]
4147
      if nresult.offline:
4148
        continue
4149

    
4150
      msg = nresult.fail_msg
4151
      if msg:
4152
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
4153
        continue
4154

    
4155
      rows = dict([(row[name_idx], row) for row in nresult.payload])
4156

    
4157
      for name in utils.NiceSort(rows.keys()):
4158
        row = rows[name]
4159

    
4160
        out = []
4161

    
4162
        for field in self.op.output_fields:
4163
          if field == constants.SF_NODE:
4164
            val = node
4165
          elif field == constants.SF_TYPE:
4166
            val = self.op.storage_type
4167
          elif field in field_idx:
4168
            val = row[field_idx[field]]
4169
          else:
4170
            raise errors.ParameterError(field)
4171

    
4172
          out.append(val)
4173

    
4174
        result.append(out)
4175

    
4176
    return result
4177

    
4178

    
4179
class _InstanceQuery(_QueryBase):
4180
  FIELDS = query.INSTANCE_FIELDS
4181

    
4182
  def ExpandNames(self, lu):
4183
    lu.needed_locks = {}
4184
    lu.share_locks[locking.LEVEL_INSTANCE] = 1
4185
    lu.share_locks[locking.LEVEL_NODE] = 1
4186

    
4187
    if self.names:
4188
      self.wanted = _GetWantedInstances(lu, self.names)
4189
    else:
4190
      self.wanted = locking.ALL_SET
4191

    
4192
    self.do_locking = (self.use_locking and
4193
                       query.IQ_LIVE in self.requested_data)
4194
    if self.do_locking:
4195
      lu.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4196
      lu.needed_locks[locking.LEVEL_NODE] = []
4197
      lu.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4198

    
4199
  def DeclareLocks(self, lu, level):
4200
    if level == locking.LEVEL_NODE and self.do_locking:
4201
      lu._LockInstancesNodes() # pylint: disable-msg=W0212
4202

    
4203
  def _GetQueryData(self, lu):
4204
    """Computes the list of instances and their attributes.
4205

4206
    """
4207
    cluster = lu.cfg.GetClusterInfo()
4208
    all_info = lu.cfg.GetAllInstancesInfo()
4209

    
4210
    instance_names = self._GetNames(lu, all_info.keys(), locking.LEVEL_INSTANCE)
4211

    
4212
    instance_list = [all_info[name] for name in instance_names]
4213
    nodes = frozenset(itertools.chain(*(inst.all_nodes
4214
                                        for inst in instance_list)))
4215
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
4216
    bad_nodes = []
4217
    offline_nodes = []
4218
    wrongnode_inst = set()
4219

    
4220
    # Gather data as requested
4221
    if self.requested_data & set([query.IQ_LIVE, query.IQ_CONSOLE]):
4222
      live_data = {}
4223
      node_data = lu.rpc.call_all_instances_info(nodes, hv_list)
4224
      for name in nodes:
4225
        result = node_data[name]
4226
        if result.offline:
4227
          # offline nodes will be in both lists
4228
          assert result.fail_msg
4229
          offline_nodes.append(name)
4230
        if result.fail_msg:
4231
          bad_nodes.append(name)
4232
        elif result.payload:
4233
          for inst in result.payload:
4234
            if inst in all_info:
4235
              if all_info[inst].primary_node == name:
4236
                live_data.update(result.payload)
4237
              else:
4238
                wrongnode_inst.add(inst)
4239
            else:
4240
              # orphan instance; we don't list it here as we don't
4241
              # handle this case yet in the output of instance listing
4242
              logging.warning("Orphan instance '%s' found on node %s",
4243
                              inst, name)
4244
        # else no instance is alive
4245
    else:
4246
      live_data = {}
4247

    
4248
    if query.IQ_DISKUSAGE in self.requested_data:
4249
      disk_usage = dict((inst.name,
4250
                         _ComputeDiskSize(inst.disk_template,
4251
                                          [{constants.IDISK_SIZE: disk.size}
4252
                                           for disk in inst.disks]))
4253
                        for inst in instance_list)
4254
    else:
4255
      disk_usage = None
4256

    
4257
    if query.IQ_CONSOLE in self.requested_data:
4258
      consinfo = {}
4259
      for inst in instance_list:
4260
        if inst.name in live_data:
4261
          # Instance is running
4262
          consinfo[inst.name] = _GetInstanceConsole(cluster, inst)
4263
        else:
4264
          consinfo[inst.name] = None
4265
      assert set(consinfo.keys()) == set(instance_names)
4266
    else:
4267
      consinfo = None
4268

    
4269
    return query.InstanceQueryData(instance_list, lu.cfg.GetClusterInfo(),
4270
                                   disk_usage, offline_nodes, bad_nodes,
4271
                                   live_data, wrongnode_inst, consinfo)
4272

    
4273

    
4274
class LUQuery(NoHooksLU):
4275
  """Query for resources/items of a certain kind.
4276

4277
  """
4278
  # pylint: disable-msg=W0142
4279
  REQ_BGL = False
4280

    
4281
  def CheckArguments(self):
4282
    qcls = _GetQueryImplementation(self.op.what)
4283

    
4284
    self.impl = qcls(self.op.filter, self.op.fields, False)
4285

    
4286
  def ExpandNames(self):
4287
    self.impl.ExpandNames(self)
4288

    
4289
  def DeclareLocks(self, level):
4290
    self.impl.DeclareLocks(self, level)
4291

    
4292
  def Exec(self, feedback_fn):
4293
    return self.impl.NewStyleQuery(self)
4294

    
4295

    
4296
class LUQueryFields(NoHooksLU):
4297
  """Query for resources/items of a certain kind.
4298

4299
  """
4300
  # pylint: disable-msg=W0142
4301
  REQ_BGL = False
4302

    
4303
  def CheckArguments(self):
4304
    self.qcls = _GetQueryImplementation(self.op.what)
4305

    
4306
  def ExpandNames(self):
4307
    self.needed_locks = {}
4308

    
4309
  def Exec(self, feedback_fn):
4310
    return query.QueryFields(self.qcls.FIELDS, self.op.fields)
4311

    
4312

    
4313
class LUNodeModifyStorage(NoHooksLU):
4314
  """Logical unit for modifying a storage volume on a node.
4315

4316
  """
4317
  REQ_BGL = False
4318

    
4319
  def CheckArguments(self):
4320
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4321

    
4322
    storage_type = self.op.storage_type
4323

    
4324
    try:
4325
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
4326
    except KeyError:
4327
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
4328
                                 " modified" % storage_type,
4329
                                 errors.ECODE_INVAL)
4330

    
4331
    diff = set(self.op.changes.keys()) - modifiable
4332
    if diff:
4333
      raise errors.OpPrereqError("The following fields can not be modified for"
4334
                                 " storage units of type '%s': %r" %
4335
                                 (storage_type, list(diff)),
4336
                                 errors.ECODE_INVAL)
4337

    
4338
  def ExpandNames(self):
4339
    self.needed_locks = {
4340
      locking.LEVEL_NODE: self.op.node_name,
4341
      }
4342

    
4343
  def Exec(self, feedback_fn):
4344
    """Computes the list of nodes and their attributes.
4345

4346
    """
4347
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
4348
    result = self.rpc.call_storage_modify(self.op.node_name,
4349
                                          self.op.storage_type, st_args,
4350
                                          self.op.name, self.op.changes)
4351
    result.Raise("Failed to modify storage unit '%s' on %s" %
4352
                 (self.op.name, self.op.node_name))
4353

    
4354

    
4355
class LUNodeAdd(LogicalUnit):
4356
  """Logical unit for adding node to the cluster.
4357

4358
  """
4359
  HPATH = "node-add"
4360
  HTYPE = constants.HTYPE_NODE
4361
  _NFLAGS = ["master_capable", "vm_capable"]
4362

    
4363
  def CheckArguments(self):
4364
    self.primary_ip_family = self.cfg.GetPrimaryIPFamily()
4365
    # validate/normalize the node name
4366
    self.hostname = netutils.GetHostname(name=self.op.node_name,
4367
                                         family=self.primary_ip_family)
4368
    self.op.node_name = self.hostname.name
4369

    
4370
    if self.op.readd and self.op.node_name == self.cfg.GetMasterNode():
4371
      raise errors.OpPrereqError("Cannot readd the master node",
4372
                                 errors.ECODE_STATE)
4373

    
4374
    if self.op.readd and self.op.group:
4375
      raise errors.OpPrereqError("Cannot pass a node group when a node is"
4376
                                 " being readded", errors.ECODE_INVAL)
4377

    
4378
  def BuildHooksEnv(self):
4379
    """Build hooks env.
4380

4381
    This will run on all nodes before, and on all nodes + the new node after.
4382

4383
    """
4384
    return {
4385
      "OP_TARGET": self.op.node_name,
4386
      "NODE_NAME": self.op.node_name,
4387
      "NODE_PIP": self.op.primary_ip,
4388
      "NODE_SIP": self.op.secondary_ip,
4389
      "MASTER_CAPABLE": str(self.op.master_capable),
4390
      "VM_CAPABLE": str(self.op.vm_capable),
4391
      }
4392

    
4393
  def BuildHooksNodes(self):
4394
    """Build hooks nodes.
4395

4396
    """
4397
    # Exclude added node
4398
    pre_nodes = list(set(self.cfg.GetNodeList()) - set([self.op.node_name]))
4399
    post_nodes = pre_nodes + [self.op.node_name, ]
4400

    
4401
    return (pre_nodes, post_nodes)
4402

    
4403
  def CheckPrereq(self):
4404
    """Check prerequisites.
4405

4406
    This checks:
4407
     - the new node is not already in the config
4408
     - it is resolvable
4409
     - its parameters (single/dual homed) matches the cluster
4410

4411
    Any errors are signaled by raising errors.OpPrereqError.
4412

4413
    """
4414
    cfg = self.cfg
4415
    hostname = self.hostname
4416
    node = hostname.name
4417
    primary_ip = self.op.primary_ip = hostname.ip
4418
    if self.op.secondary_ip is None:
4419
      if self.primary_ip_family == netutils.IP6Address.family:
4420
        raise errors.OpPrereqError("When using a IPv6 primary address, a valid"
4421
                                   " IPv4 address must be given as secondary",
4422
                                   errors.ECODE_INVAL)
4423
      self.op.secondary_ip = primary_ip
4424

    
4425
    secondary_ip = self.op.secondary_ip
4426
    if not netutils.IP4Address.IsValid(secondary_ip):
4427
      raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4428
                                 " address" % secondary_ip, errors.ECODE_INVAL)
4429

    
4430
    node_list = cfg.GetNodeList()
4431
    if not self.op.readd and node in node_list:
4432
      raise errors.OpPrereqError("Node %s is already in the configuration" %
4433
                                 node, errors.ECODE_EXISTS)
4434
    elif self.op.readd and node not in node_list:
4435
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
4436
                                 errors.ECODE_NOENT)
4437

    
4438
    self.changed_primary_ip = False
4439

    
4440
    for existing_node_name in node_list:
4441
      existing_node = cfg.GetNodeInfo(existing_node_name)
4442

    
4443
      if self.op.readd and node == existing_node_name:
4444
        if existing_node.secondary_ip != secondary_ip:
4445
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
4446
                                     " address configuration as before",
4447
                                     errors.ECODE_INVAL)
4448
        if existing_node.primary_ip != primary_ip:
4449
          self.changed_primary_ip = True
4450

    
4451
        continue
4452

    
4453
      if (existing_node.primary_ip == primary_ip or
4454
          existing_node.secondary_ip == primary_ip or
4455
          existing_node.primary_ip == secondary_ip or
4456
          existing_node.secondary_ip == secondary_ip):
4457
        raise errors.OpPrereqError("New node ip address(es) conflict with"
4458
                                   " existing node %s" % existing_node.name,
4459
                                   errors.ECODE_NOTUNIQUE)
4460

    
4461
    # After this 'if' block, None is no longer a valid value for the
4462
    # _capable op attributes
4463
    if self.op.readd:
4464
      old_node = self.cfg.GetNodeInfo(node)
4465
      assert old_node is not None, "Can't retrieve locked node %s" % node
4466
      for attr in self._NFLAGS:
4467
        if getattr(self.op, attr) is None:
4468
          setattr(self.op, attr, getattr(old_node, attr))
4469
    else:
4470
      for attr in self._NFLAGS:
4471
        if getattr(self.op, attr) is None:
4472
          setattr(self.op, attr, True)
4473

    
4474
    if self.op.readd and not self.op.vm_capable:
4475
      pri, sec = cfg.GetNodeInstances(node)
4476
      if pri or sec:
4477
        raise errors.OpPrereqError("Node %s being re-added with vm_capable"
4478
                                   " flag set to false, but it already holds"
4479
                                   " instances" % node,
4480
                                   errors.ECODE_STATE)
4481

    
4482
    # check that the type of the node (single versus dual homed) is the
4483
    # same as for the master
4484
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
4485
    master_singlehomed = myself.secondary_ip == myself.primary_ip
4486
    newbie_singlehomed = secondary_ip == primary_ip
4487
    if master_singlehomed != newbie_singlehomed:
4488
      if master_singlehomed:
4489
        raise errors.OpPrereqError("The master has no secondary ip but the"
4490
                                   " new node has one",
4491
                                   errors.ECODE_INVAL)
4492
      else:
4493
        raise errors.OpPrereqError("The master has a secondary ip but the"
4494
                                   " new node doesn't have one",
4495
                                   errors.ECODE_INVAL)
4496

    
4497
    # checks reachability
4498
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
4499
      raise errors.OpPrereqError("Node not reachable by ping",
4500
                                 errors.ECODE_ENVIRON)
4501

    
4502
    if not newbie_singlehomed:
4503
      # check reachability from my secondary ip to newbie's secondary ip
4504
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
4505
                           source=myself.secondary_ip):
4506
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4507
                                   " based ping to node daemon port",
4508
                                   errors.ECODE_ENVIRON)
4509

    
4510
    if self.op.readd:
4511
      exceptions = [node]
4512
    else:
4513
      exceptions = []
4514

    
4515
    if self.op.master_capable:
4516
      self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
4517
    else:
4518
      self.master_candidate = False
4519

    
4520
    if self.op.readd:
4521
      self.new_node = old_node
4522
    else:
4523
      node_group = cfg.LookupNodeGroup(self.op.group)
4524
      self.new_node = objects.Node(name=node,
4525
                                   primary_ip=primary_ip,
4526
                                   secondary_ip=secondary_ip,
4527
                                   master_candidate=self.master_candidate,
4528
                                   offline=False, drained=False,
4529
                                   group=node_group)
4530

    
4531
    if self.op.ndparams:
4532
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
4533

    
4534
  def Exec(self, feedback_fn):
4535
    """Adds the new node to the cluster.
4536

4537
    """
4538
    new_node = self.new_node
4539
    node = new_node.name
4540

    
4541
    # We adding a new node so we assume it's powered
4542
    new_node.powered = True
4543

    
4544
    # for re-adds, reset the offline/drained/master-candidate flags;
4545
    # we need to reset here, otherwise offline would prevent RPC calls
4546
    # later in the procedure; this also means that if the re-add
4547
    # fails, we are left with a non-offlined, broken node
4548
    if self.op.readd:
4549
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
4550
      self.LogInfo("Readding a node, the offline/drained flags were reset")
4551
      # if we demote the node, we do cleanup later in the procedure
4552
      new_node.master_candidate = self.master_candidate
4553
      if self.changed_primary_ip:
4554
        new_node.primary_ip = self.op.primary_ip
4555

    
4556
    # copy the master/vm_capable flags
4557
    for attr in self._NFLAGS:
4558
      setattr(new_node, attr, getattr(self.op, attr))
4559

    
4560
    # notify the user about any possible mc promotion
4561
    if new_node.master_candidate:
4562
      self.LogInfo("Node will be a master candidate")
4563

    
4564
    if self.op.ndparams:
4565
      new_node.ndparams = self.op.ndparams
4566
    else:
4567
      new_node.ndparams = {}
4568

    
4569
    # check connectivity
4570
    result = self.rpc.call_version([node])[node]
4571
    result.Raise("Can't get version information from node %s" % node)
4572
    if constants.PROTOCOL_VERSION == result.payload:
4573
      logging.info("Communication to node %s fine, sw version %s match",
4574
                   node, result.payload)
4575
    else:
4576
      raise errors.OpExecError("Version mismatch master version %s,"
4577
                               " node version %s" %
4578
                               (constants.PROTOCOL_VERSION, result.payload))
4579

    
4580
    # Add node to our /etc/hosts, and add key to known_hosts
4581
    if self.cfg.GetClusterInfo().modify_etc_hosts:
4582
      master_node = self.cfg.GetMasterNode()
4583
      result = self.rpc.call_etc_hosts_modify(master_node,
4584
                                              constants.ETC_HOSTS_ADD,
4585
                                              self.hostname.name,
4586
                                              self.hostname.ip)
4587
      result.Raise("Can't update hosts file with new host data")
4588

    
4589
    if new_node.secondary_ip != new_node.primary_ip:
4590
      _CheckNodeHasSecondaryIP(self, new_node.name, new_node.secondary_ip,
4591
                               False)
4592

    
4593
    node_verify_list = [self.cfg.GetMasterNode()]
4594
    node_verify_param = {
4595
      constants.NV_NODELIST: [node],
4596
      # TODO: do a node-net-test as well?
4597
    }
4598

    
4599
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
4600
                                       self.cfg.GetClusterName())
4601
    for verifier in node_verify_list:
4602
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
4603
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
4604
      if nl_payload:
4605
        for failed in nl_payload:
4606
          feedback_fn("ssh/hostname verification failed"
4607
                      " (checking from %s): %s" %
4608
                      (verifier, nl_payload[failed]))
4609
        raise errors.OpExecError("ssh/hostname verification failed")
4610

    
4611
    if self.op.readd:
4612
      _RedistributeAncillaryFiles(self)
4613
      self.context.ReaddNode(new_node)
4614
      # make sure we redistribute the config
4615
      self.cfg.Update(new_node, feedback_fn)
4616
      # and make sure the new node will not have old files around
4617
      if not new_node.master_candidate:
4618
        result = self.rpc.call_node_demote_from_mc(new_node.name)
4619
        msg = result.fail_msg
4620
        if msg:
4621
          self.LogWarning("Node failed to demote itself from master"
4622
                          " candidate status: %s" % msg)
4623
    else:
4624
      _RedistributeAncillaryFiles(self, additional_nodes=[node],
4625
                                  additional_vm=self.op.vm_capable)
4626
      self.context.AddNode(new_node, self.proc.GetECId())
4627

    
4628

    
4629
class LUNodeSetParams(LogicalUnit):
4630
  """Modifies the parameters of a node.
4631

4632
  @cvar _F2R: a dictionary from tuples of flags (mc, drained, offline)
4633
      to the node role (as _ROLE_*)
4634
  @cvar _R2F: a dictionary from node role to tuples of flags
4635
  @cvar _FLAGS: a list of attribute names corresponding to the flags
4636

4637
  """
4638
  HPATH = "node-modify"
4639
  HTYPE = constants.HTYPE_NODE
4640
  REQ_BGL = False
4641
  (_ROLE_CANDIDATE, _ROLE_DRAINED, _ROLE_OFFLINE, _ROLE_REGULAR) = range(4)
4642
  _F2R = {
4643
    (True, False, False): _ROLE_CANDIDATE,
4644
    (False, True, False): _ROLE_DRAINED,
4645
    (False, False, True): _ROLE_OFFLINE,
4646
    (False, False, False): _ROLE_REGULAR,
4647
    }
4648
  _R2F = dict((v, k) for k, v in _F2R.items())
4649
  _FLAGS = ["master_candidate", "drained", "offline"]
4650

    
4651
  def CheckArguments(self):
4652
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4653
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained,
4654
                self.op.master_capable, self.op.vm_capable,
4655
                self.op.secondary_ip, self.op.ndparams]
4656
    if all_mods.count(None) == len(all_mods):
4657
      raise errors.OpPrereqError("Please pass at least one modification",
4658
                                 errors.ECODE_INVAL)
4659
    if all_mods.count(True) > 1:
4660
      raise errors.OpPrereqError("Can't set the node into more than one"
4661
                                 " state at the same time",
4662
                                 errors.ECODE_INVAL)
4663

    
4664
    # Boolean value that tells us whether we might be demoting from MC
4665
    self.might_demote = (self.op.master_candidate == False or
4666
                         self.op.offline == True or
4667
                         self.op.drained == True or
4668
                         self.op.master_capable == False)
4669

    
4670
    if self.op.secondary_ip:
4671
      if not netutils.IP4Address.IsValid(self.op.secondary_ip):
4672
        raise errors.OpPrereqError("Secondary IP (%s) needs to be a valid IPv4"
4673
                                   " address" % self.op.secondary_ip,
4674
                                   errors.ECODE_INVAL)
4675

    
4676
    self.lock_all = self.op.auto_promote and self.might_demote
4677
    self.lock_instances = self.op.secondary_ip is not None
4678

    
4679
  def ExpandNames(self):
4680
    if self.lock_all:
4681
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
4682
    else:
4683
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
4684

    
4685
    if self.lock_instances:
4686
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
4687

    
4688
  def DeclareLocks(self, level):
4689
    # If we have locked all instances, before waiting to lock nodes, release
4690
    # all the ones living on nodes unrelated to the current operation.
4691
    if level == locking.LEVEL_NODE and self.lock_instances:
4692
      self.affected_instances = []
4693
      if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
4694
        instances_keep = []
4695

    
4696
        # Build list of instances to release
4697
        for instance_name in self.glm.list_owned(locking.LEVEL_INSTANCE):
4698
          instance = self.context.cfg.GetInstanceInfo(instance_name)
4699
          if (instance.disk_template in constants.DTS_INT_MIRROR and
4700
              self.op.node_name in instance.all_nodes):
4701
            instances_keep.append(instance_name)
4702
            self.affected_instances.append(instance)
4703

    
4704
        _ReleaseLocks(self, locking.LEVEL_INSTANCE, keep=instances_keep)
4705

    
4706
        assert (set(self.glm.list_owned(locking.LEVEL_INSTANCE)) ==
4707
                set(instances_keep))
4708

    
4709
  def BuildHooksEnv(self):
4710
    """Build hooks env.
4711

4712
    This runs on the master node.
4713

4714
    """
4715
    return {
4716
      "OP_TARGET": self.op.node_name,
4717
      "MASTER_CANDIDATE": str(self.op.master_candidate),
4718
      "OFFLINE": str(self.op.offline),
4719
      "DRAINED": str(self.op.drained),
4720
      "MASTER_CAPABLE": str(self.op.master_capable),
4721
      "VM_CAPABLE": str(self.op.vm_capable),
4722
      }
4723

    
4724
  def BuildHooksNodes(self):
4725
    """Build hooks nodes.
4726

4727
    """
4728
    nl = [self.cfg.GetMasterNode(), self.op.node_name]
4729
    return (nl, nl)
4730

    
4731
  def CheckPrereq(self):
4732
    """Check prerequisites.
4733

4734
    This only checks the instance list against the existing names.
4735

4736
    """
4737
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
4738

    
4739
    if (self.op.master_candidate is not None or
4740
        self.op.drained is not None or
4741
        self.op.offline is not None):
4742
      # we can't change the master's node flags
4743
      if self.op.node_name == self.cfg.GetMasterNode():
4744
        raise errors.OpPrereqError("The master role can be changed"
4745
                                   " only via master-failover",
4746
                                   errors.ECODE_INVAL)
4747

    
4748
    if self.op.master_candidate and not node.master_capable:
4749
      raise errors.OpPrereqError("Node %s is not master capable, cannot make"
4750
                                 " it a master candidate" % node.name,
4751
                                 errors.ECODE_STATE)
4752

    
4753
    if self.op.vm_capable == False:
4754
      (ipri, isec) = self.cfg.GetNodeInstances(self.op.node_name)
4755
      if ipri or isec:
4756
        raise errors.OpPrereqError("Node %s hosts instances, cannot unset"
4757
                                   " the vm_capable flag" % node.name,
4758
                                   errors.ECODE_STATE)
4759

    
4760
    if node.master_candidate and self.might_demote and not self.lock_all:
4761
      assert not self.op.auto_promote, "auto_promote set but lock_all not"
4762
      # check if after removing the current node, we're missing master
4763
      # candidates
4764
      (mc_remaining, mc_should, _) = \
4765
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4766
      if mc_remaining < mc_should:
4767
        raise errors.OpPrereqError("Not enough master candidates, please"
4768
                                   " pass auto promote option to allow"
4769
                                   " promotion", errors.ECODE_STATE)
4770

    
4771
    self.old_flags = old_flags = (node.master_candidate,
4772
                                  node.drained, node.offline)
4773
    assert old_flags in self._F2R, "Un-handled old flags %s" % str(old_flags)
4774
    self.old_role = old_role = self._F2R[old_flags]
4775

    
4776
    # Check for ineffective changes
4777
    for attr in self._FLAGS:
4778
      if (getattr(self.op, attr) == False and getattr(node, attr) == False):
4779
        self.LogInfo("Ignoring request to unset flag %s, already unset", attr)
4780
        setattr(self.op, attr, None)
4781

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

    
4785
    # TODO: We might query the real power state if it supports OOB
4786
    if _SupportsOob(self.cfg, node):
4787
      if self.op.offline is False and not (node.powered or
4788
                                           self.op.powered == True):
4789
        raise errors.OpPrereqError(("Node %s needs to be turned on before its"
4790
                                    " offline status can be reset") %
4791
                                   self.op.node_name)
4792
    elif self.op.powered is not None:
4793
      raise errors.OpPrereqError(("Unable to change powered state for node %s"
4794
                                  " as it does not support out-of-band"
4795
                                  " handling") % self.op.node_name)
4796

    
4797
    # If we're being deofflined/drained, we'll MC ourself if needed
4798
    if (self.op.drained == False or self.op.offline == False or
4799
        (self.op.master_capable and not node.master_capable)):
4800
      if _DecideSelfPromotion(self):
4801
        self.op.master_candidate = True
4802
        self.LogInfo("Auto-promoting node to master candidate")
4803

    
4804
    # If we're no longer master capable, we'll demote ourselves from MC
4805
    if self.op.master_capable == False and node.master_candidate:
4806
      self.LogInfo("Demoting from master candidate")
4807
      self.op.master_candidate = False
4808

    
4809
    # Compute new role
4810
    assert [getattr(self.op, attr) for attr in self._FLAGS].count(True) <= 1
4811
    if self.op.master_candidate:
4812
      new_role = self._ROLE_CANDIDATE
4813
    elif self.op.drained:
4814
      new_role = self._ROLE_DRAINED
4815
    elif self.op.offline:
4816
      new_role = self._ROLE_OFFLINE
4817
    elif False in [self.op.master_candidate, self.op.drained, self.op.offline]:
4818
      # False is still in new flags, which means we're un-setting (the
4819
      # only) True flag
4820
      new_role = self._ROLE_REGULAR
4821
    else: # no new flags, nothing, keep old role
4822
      new_role = old_role
4823

    
4824
    self.new_role = new_role
4825

    
4826
    if old_role == self._ROLE_OFFLINE and new_role != old_role:
4827
      # Trying to transition out of offline status
4828
      result = self.rpc.call_version([node.name])[node.name]
4829
      if result.fail_msg:
4830
        raise errors.OpPrereqError("Node %s is being de-offlined but fails"
4831
                                   " to report its version: %s" %
4832
                                   (node.name, result.fail_msg),
4833
                                   errors.ECODE_STATE)
4834
      else:
4835
        self.LogWarning("Transitioning node from offline to online state"
4836
                        " without using re-add. Please make sure the node"
4837
                        " is healthy!")
4838

    
4839
    if self.op.secondary_ip:
4840
      # Ok even without locking, because this can't be changed by any LU
4841
      master = self.cfg.GetNodeInfo(self.cfg.GetMasterNode())
4842
      master_singlehomed = master.secondary_ip == master.primary_ip
4843
      if master_singlehomed and self.op.secondary_ip:
4844
        raise errors.OpPrereqError("Cannot change the secondary ip on a single"
4845
                                   " homed cluster", errors.ECODE_INVAL)
4846

    
4847
      if node.offline:
4848
        if self.affected_instances:
4849
          raise errors.OpPrereqError("Cannot change secondary ip: offline"
4850
                                     " node has instances (%s) configured"
4851
                                     " to use it" % self.affected_instances)
4852
      else:
4853
        # On online nodes, check that no instances are running, and that
4854
        # the node has the new ip and we can reach it.
4855
        for instance in self.affected_instances:
4856
          _CheckInstanceDown(self, instance, "cannot change secondary ip")
4857

    
4858
        _CheckNodeHasSecondaryIP(self, node.name, self.op.secondary_ip, True)
4859
        if master.name != node.name:
4860
          # check reachability from master secondary ip to new secondary ip
4861
          if not netutils.TcpPing(self.op.secondary_ip,
4862
                                  constants.DEFAULT_NODED_PORT,
4863
                                  source=master.secondary_ip):
4864
            raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
4865
                                       " based ping to node daemon port",
4866
                                       errors.ECODE_ENVIRON)
4867

    
4868
    if self.op.ndparams:
4869
      new_ndparams = _GetUpdatedParams(self.node.ndparams, self.op.ndparams)
4870
      utils.ForceDictType(new_ndparams, constants.NDS_PARAMETER_TYPES)
4871
      self.new_ndparams = new_ndparams
4872

    
4873
  def Exec(self, feedback_fn):
4874
    """Modifies a node.
4875

4876
    """
4877
    node = self.node
4878
    old_role = self.old_role
4879
    new_role = self.new_role
4880

    
4881
    result = []
4882

    
4883
    if self.op.ndparams:
4884
      node.ndparams = self.new_ndparams
4885

    
4886
    if self.op.powered is not None:
4887
      node.powered = self.op.powered
4888

    
4889
    for attr in ["master_capable", "vm_capable"]:
4890
      val = getattr(self.op, attr)
4891
      if val is not None:
4892
        setattr(node, attr, val)
4893
        result.append((attr, str(val)))
4894

    
4895
    if new_role != old_role:
4896
      # Tell the node to demote itself, if no longer MC and not offline
4897
      if old_role == self._ROLE_CANDIDATE and new_role != self._ROLE_OFFLINE:
4898
        msg = self.rpc.call_node_demote_from_mc(node.name).fail_msg
4899
        if msg:
4900
          self.LogWarning("Node failed to demote itself: %s", msg)
4901

    
4902
      new_flags = self._R2F[new_role]
4903
      for of, nf, desc in zip(self.old_flags, new_flags, self._FLAGS):
4904
        if of != nf:
4905
          result.append((desc, str(nf)))
4906
      (node.master_candidate, node.drained, node.offline) = new_flags
4907

    
4908
      # we locked all nodes, we adjust the CP before updating this node
4909
      if self.lock_all:
4910
        _AdjustCandidatePool(self, [node.name])
4911

    
4912
    if self.op.secondary_ip:
4913
      node.secondary_ip = self.op.secondary_ip
4914
      result.append(("secondary_ip", self.op.secondary_ip))
4915

    
4916
    # this will trigger configuration file update, if needed
4917
    self.cfg.Update(node, feedback_fn)
4918

    
4919
    # this will trigger job queue propagation or cleanup if the mc
4920
    # flag changed
4921
    if [old_role, new_role].count(self._ROLE_CANDIDATE) == 1:
4922
      self.context.ReaddNode(node)
4923

    
4924
    return result
4925

    
4926

    
4927
class LUNodePowercycle(NoHooksLU):
4928
  """Powercycles a node.
4929

4930
  """
4931
  REQ_BGL = False
4932

    
4933
  def CheckArguments(self):
4934
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4935
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4936
      raise errors.OpPrereqError("The node is the master and the force"
4937
                                 " parameter was not set",
4938
                                 errors.ECODE_INVAL)
4939

    
4940
  def ExpandNames(self):
4941
    """Locking for PowercycleNode.
4942

4943
    This is a last-resort option and shouldn't block on other
4944
    jobs. Therefore, we grab no locks.
4945

4946
    """
4947
    self.needed_locks = {}
4948

    
4949
  def Exec(self, feedback_fn):
4950
    """Reboots a node.
4951

4952
    """
4953
    result = self.rpc.call_node_powercycle(self.op.node_name,
4954
                                           self.cfg.GetHypervisorType())
4955
    result.Raise("Failed to schedule the reboot")
4956
    return result.payload
4957

    
4958

    
4959
class LUClusterQuery(NoHooksLU):
4960
  """Query cluster configuration.
4961

4962
  """
4963
  REQ_BGL = False
4964

    
4965
  def ExpandNames(self):
4966
    self.needed_locks = {}
4967

    
4968
  def Exec(self, feedback_fn):
4969
    """Return cluster config.
4970

4971
    """
4972
    cluster = self.cfg.GetClusterInfo()
4973
    os_hvp = {}
4974

    
4975
    # Filter just for enabled hypervisors
4976
    for os_name, hv_dict in cluster.os_hvp.items():
4977
      os_hvp[os_name] = {}
4978
      for hv_name, hv_params in hv_dict.items():
4979
        if hv_name in cluster.enabled_hypervisors:
4980
          os_hvp[os_name][hv_name] = hv_params
4981

    
4982
    # Convert ip_family to ip_version
4983
    primary_ip_version = constants.IP4_VERSION
4984
    if cluster.primary_ip_family == netutils.IP6Address.family:
4985
      primary_ip_version = constants.IP6_VERSION
4986

    
4987
    result = {
4988
      "software_version": constants.RELEASE_VERSION,
4989
      "protocol_version": constants.PROTOCOL_VERSION,
4990
      "config_version": constants.CONFIG_VERSION,
4991
      "os_api_version": max(constants.OS_API_VERSIONS),
4992
      "export_version": constants.EXPORT_VERSION,
4993
      "architecture": (platform.architecture()[0], platform.machine()),
4994
      "name": cluster.cluster_name,
4995
      "master": cluster.master_node,
4996
      "default_hypervisor": cluster.enabled_hypervisors[0],
4997
      "enabled_hypervisors": cluster.enabled_hypervisors,
4998
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4999
                        for hypervisor_name in cluster.enabled_hypervisors]),
5000
      "os_hvp": os_hvp,
5001
      "beparams": cluster.beparams,
5002
      "osparams": cluster.osparams,
5003
      "nicparams": cluster.nicparams,
5004
      "ndparams": cluster.ndparams,
5005
      "candidate_pool_size": cluster.candidate_pool_size,
5006
      "master_netdev": cluster.master_netdev,
5007
      "volume_group_name": cluster.volume_group_name,
5008
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
5009
      "file_storage_dir": cluster.file_storage_dir,
5010
      "shared_file_storage_dir": cluster.shared_file_storage_dir,
5011
      "maintain_node_health": cluster.maintain_node_health,
5012
      "ctime": cluster.ctime,
5013
      "mtime": cluster.mtime,
5014
      "uuid": cluster.uuid,
5015
      "tags": list(cluster.GetTags()),
5016
      "uid_pool": cluster.uid_pool,
5017
      "default_iallocator": cluster.default_iallocator,
5018
      "reserved_lvs": cluster.reserved_lvs,
5019
      "primary_ip_version": primary_ip_version,
5020
      "prealloc_wipe_disks": cluster.prealloc_wipe_disks,
5021
      "hidden_os": cluster.hidden_os,
5022
      "blacklisted_os": cluster.blacklisted_os,
5023
      }
5024

    
5025
    return result
5026

    
5027

    
5028
class LUClusterConfigQuery(NoHooksLU):
5029
  """Return configuration values.
5030

5031
  """
5032
  REQ_BGL = False
5033
  _FIELDS_DYNAMIC = utils.FieldSet()
5034
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
5035
                                  "watcher_pause", "volume_group_name")
5036

    
5037
  def CheckArguments(self):
5038
    _CheckOutputFields(static=self._FIELDS_STATIC,
5039
                       dynamic=self._FIELDS_DYNAMIC,
5040
                       selected=self.op.output_fields)
5041

    
5042
  def ExpandNames(self):
5043
    self.needed_locks = {}
5044

    
5045
  def Exec(self, feedback_fn):
5046
    """Dump a representation of the cluster config to the standard output.
5047

5048
    """
5049
    values = []
5050
    for field in self.op.output_fields:
5051
      if field == "cluster_name":
5052
        entry = self.cfg.GetClusterName()
5053
      elif field == "master_node":
5054
        entry = self.cfg.GetMasterNode()
5055
      elif field == "drain_flag":
5056
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
5057
      elif field == "watcher_pause":
5058
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
5059
      elif field == "volume_group_name":
5060
        entry = self.cfg.GetVGName()
5061
      else:
5062
        raise errors.ParameterError(field)
5063
      values.append(entry)
5064
    return values
5065

    
5066

    
5067
class LUInstanceActivateDisks(NoHooksLU):
5068
  """Bring up an instance's disks.
5069

5070
  """
5071
  REQ_BGL = False
5072

    
5073
  def ExpandNames(self):
5074
    self._ExpandAndLockInstance()
5075
    self.needed_locks[locking.LEVEL_NODE] = []
5076
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5077

    
5078
  def DeclareLocks(self, level):
5079
    if level == locking.LEVEL_NODE:
5080
      self._LockInstancesNodes()
5081

    
5082
  def CheckPrereq(self):
5083
    """Check prerequisites.
5084

5085
    This checks that the instance is in the cluster.
5086

5087
    """
5088
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5089
    assert self.instance is not None, \
5090
      "Cannot retrieve locked instance %s" % self.op.instance_name
5091
    _CheckNodeOnline(self, self.instance.primary_node)
5092

    
5093
  def Exec(self, feedback_fn):
5094
    """Activate the disks.
5095

5096
    """
5097
    disks_ok, disks_info = \
5098
              _AssembleInstanceDisks(self, self.instance,
5099
                                     ignore_size=self.op.ignore_size)
5100
    if not disks_ok:
5101
      raise errors.OpExecError("Cannot activate block devices")
5102

    
5103
    return disks_info
5104

    
5105

    
5106
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
5107
                           ignore_size=False):
5108
  """Prepare the block devices for an instance.
5109

5110
  This sets up the block devices on all nodes.
5111

5112
  @type lu: L{LogicalUnit}
5113
  @param lu: the logical unit on whose behalf we execute
5114
  @type instance: L{objects.Instance}
5115
  @param instance: the instance for whose disks we assemble
5116
  @type disks: list of L{objects.Disk} or None
5117
  @param disks: which disks to assemble (or all, if None)
5118
  @type ignore_secondaries: boolean
5119
  @param ignore_secondaries: if true, errors on secondary nodes
5120
      won't result in an error return from the function
5121
  @type ignore_size: boolean
5122
  @param ignore_size: if true, the current known size of the disk
5123
      will not be used during the disk activation, useful for cases
5124
      when the size is wrong
5125
  @return: False if the operation failed, otherwise a list of
5126
      (host, instance_visible_name, node_visible_name)
5127
      with the mapping from node devices to instance devices
5128

5129
  """
5130
  device_info = []
5131
  disks_ok = True
5132
  iname = instance.name
5133
  disks = _ExpandCheckDisks(instance, disks)
5134

    
5135
  # With the two passes mechanism we try to reduce the window of
5136
  # opportunity for the race condition of switching DRBD to primary
5137
  # before handshaking occured, but we do not eliminate it
5138

    
5139
  # The proper fix would be to wait (with some limits) until the
5140
  # connection has been made and drbd transitions from WFConnection
5141
  # into any other network-connected state (Connected, SyncTarget,
5142
  # SyncSource, etc.)
5143

    
5144
  # 1st pass, assemble on all nodes in secondary mode
5145
  for idx, inst_disk in enumerate(disks):
5146
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5147
      if ignore_size:
5148
        node_disk = node_disk.Copy()
5149
        node_disk.UnsetSize()
5150
      lu.cfg.SetDiskID(node_disk, node)
5151
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False, idx)
5152
      msg = result.fail_msg
5153
      if msg:
5154
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5155
                           " (is_primary=False, pass=1): %s",
5156
                           inst_disk.iv_name, node, msg)
5157
        if not ignore_secondaries:
5158
          disks_ok = False
5159

    
5160
  # FIXME: race condition on drbd migration to primary
5161

    
5162
  # 2nd pass, do only the primary node
5163
  for idx, inst_disk in enumerate(disks):
5164
    dev_path = None
5165

    
5166
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
5167
      if node != instance.primary_node:
5168
        continue
5169
      if ignore_size:
5170
        node_disk = node_disk.Copy()
5171
        node_disk.UnsetSize()
5172
      lu.cfg.SetDiskID(node_disk, node)
5173
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True, idx)
5174
      msg = result.fail_msg
5175
      if msg:
5176
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
5177
                           " (is_primary=True, pass=2): %s",
5178
                           inst_disk.iv_name, node, msg)
5179
        disks_ok = False
5180
      else:
5181
        dev_path = result.payload
5182

    
5183
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
5184

    
5185
  # leave the disks configured for the primary node
5186
  # this is a workaround that would be fixed better by
5187
  # improving the logical/physical id handling
5188
  for disk in disks:
5189
    lu.cfg.SetDiskID(disk, instance.primary_node)
5190

    
5191
  return disks_ok, device_info
5192

    
5193

    
5194
def _StartInstanceDisks(lu, instance, force):
5195
  """Start the disks of an instance.
5196

5197
  """
5198
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
5199
                                           ignore_secondaries=force)
5200
  if not disks_ok:
5201
    _ShutdownInstanceDisks(lu, instance)
5202
    if force is not None and not force:
5203
      lu.proc.LogWarning("", hint="If the message above refers to a"
5204
                         " secondary node,"
5205
                         " you can retry the operation using '--force'.")
5206
    raise errors.OpExecError("Disk consistency error")
5207

    
5208

    
5209
class LUInstanceDeactivateDisks(NoHooksLU):
5210
  """Shutdown an instance's disks.
5211

5212
  """
5213
  REQ_BGL = False
5214

    
5215
  def ExpandNames(self):
5216
    self._ExpandAndLockInstance()
5217
    self.needed_locks[locking.LEVEL_NODE] = []
5218
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5219

    
5220
  def DeclareLocks(self, level):
5221
    if level == locking.LEVEL_NODE:
5222
      self._LockInstancesNodes()
5223

    
5224
  def CheckPrereq(self):
5225
    """Check prerequisites.
5226

5227
    This checks that the instance is in the cluster.
5228

5229
    """
5230
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5231
    assert self.instance is not None, \
5232
      "Cannot retrieve locked instance %s" % self.op.instance_name
5233

    
5234
  def Exec(self, feedback_fn):
5235
    """Deactivate the disks
5236

5237
    """
5238
    instance = self.instance
5239
    if self.op.force:
5240
      _ShutdownInstanceDisks(self, instance)
5241
    else:
5242
      _SafeShutdownInstanceDisks(self, instance)
5243

    
5244

    
5245
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
5246
  """Shutdown block devices of an instance.
5247

5248
  This function checks if an instance is running, before calling
5249
  _ShutdownInstanceDisks.
5250

5251
  """
5252
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
5253
  _ShutdownInstanceDisks(lu, instance, disks=disks)
5254

    
5255

    
5256
def _ExpandCheckDisks(instance, disks):
5257
  """Return the instance disks selected by the disks list
5258

5259
  @type disks: list of L{objects.Disk} or None
5260
  @param disks: selected disks
5261
  @rtype: list of L{objects.Disk}
5262
  @return: selected instance disks to act on
5263

5264
  """
5265
  if disks is None:
5266
    return instance.disks
5267
  else:
5268
    if not set(disks).issubset(instance.disks):
5269
      raise errors.ProgrammerError("Can only act on disks belonging to the"
5270
                                   " target instance")
5271
    return disks
5272

    
5273

    
5274
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
5275
  """Shutdown block devices of an instance.
5276

5277
  This does the shutdown on all nodes of the instance.
5278

5279
  If the ignore_primary is false, errors on the primary node are
5280
  ignored.
5281

5282
  """
5283
  all_result = True
5284
  disks = _ExpandCheckDisks(instance, disks)
5285

    
5286
  for disk in disks:
5287
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
5288
      lu.cfg.SetDiskID(top_disk, node)
5289
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
5290
      msg = result.fail_msg
5291
      if msg:
5292
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
5293
                      disk.iv_name, node, msg)
5294
        if ((node == instance.primary_node and not ignore_primary) or
5295
            (node != instance.primary_node and not result.offline)):
5296
          all_result = False
5297
  return all_result
5298

    
5299

    
5300
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
5301
  """Checks if a node has enough free memory.
5302

5303
  This function check if a given node has the needed amount of free
5304
  memory. In case the node has less memory or we cannot get the
5305
  information from the node, this function raise an OpPrereqError
5306
  exception.
5307

5308
  @type lu: C{LogicalUnit}
5309
  @param lu: a logical unit from which we get configuration data
5310
  @type node: C{str}
5311
  @param node: the node to check
5312
  @type reason: C{str}
5313
  @param reason: string to use in the error message
5314
  @type requested: C{int}
5315
  @param requested: the amount of memory in MiB to check for
5316
  @type hypervisor_name: C{str}
5317
  @param hypervisor_name: the hypervisor to ask for memory stats
5318
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
5319
      we cannot check the node
5320

5321
  """
5322
  nodeinfo = lu.rpc.call_node_info([node], None, hypervisor_name)
5323
  nodeinfo[node].Raise("Can't get data from node %s" % node,
5324
                       prereq=True, ecode=errors.ECODE_ENVIRON)
5325
  free_mem = nodeinfo[node].payload.get('memory_free', None)
5326
  if not isinstance(free_mem, int):
5327
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
5328
                               " was '%s'" % (node, free_mem),
5329
                               errors.ECODE_ENVIRON)
5330
  if requested > free_mem:
5331
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
5332
                               " needed %s MiB, available %s MiB" %
5333
                               (node, reason, requested, free_mem),
5334
                               errors.ECODE_NORES)
5335

    
5336

    
5337
def _CheckNodesFreeDiskPerVG(lu, nodenames, req_sizes):
5338
  """Checks if nodes have enough free disk space in the all VGs.
5339

5340
  This function check if all given nodes have the needed amount of
5341
  free disk. In case any node has less disk or we cannot get the
5342
  information from the node, this function raise an OpPrereqError
5343
  exception.
5344

5345
  @type lu: C{LogicalUnit}
5346
  @param lu: a logical unit from which we get configuration data
5347
  @type nodenames: C{list}
5348
  @param nodenames: the list of node names to check
5349
  @type req_sizes: C{dict}
5350
  @param req_sizes: the hash of vg and corresponding amount of disk in
5351
      MiB to check for
5352
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5353
      or we cannot check the node
5354

5355
  """
5356
  for vg, req_size in req_sizes.items():
5357
    _CheckNodesFreeDiskOnVG(lu, nodenames, vg, req_size)
5358

    
5359

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

5363
  This function check if all given nodes have the needed amount of
5364
  free disk. In case any node has less disk or we cannot get the
5365
  information from the node, this function raise an OpPrereqError
5366
  exception.
5367

5368
  @type lu: C{LogicalUnit}
5369
  @param lu: a logical unit from which we get configuration data
5370
  @type nodenames: C{list}
5371
  @param nodenames: the list of node names to check
5372
  @type vg: C{str}
5373
  @param vg: the volume group to check
5374
  @type requested: C{int}
5375
  @param requested: the amount of disk in MiB to check for
5376
  @raise errors.OpPrereqError: if the node doesn't have enough disk,
5377
      or we cannot check the node
5378

5379
  """
5380
  nodeinfo = lu.rpc.call_node_info(nodenames, vg, None)
5381
  for node in nodenames:
5382
    info = nodeinfo[node]
5383
    info.Raise("Cannot get current information from node %s" % node,
5384
               prereq=True, ecode=errors.ECODE_ENVIRON)
5385
    vg_free = info.payload.get("vg_free", None)
5386
    if not isinstance(vg_free, int):
5387
      raise errors.OpPrereqError("Can't compute free disk space on node"
5388
                                 " %s for vg %s, result was '%s'" %
5389
                                 (node, vg, vg_free), errors.ECODE_ENVIRON)
5390
    if requested > vg_free:
5391
      raise errors.OpPrereqError("Not enough disk space on target node %s"
5392
                                 " vg %s: required %d MiB, available %d MiB" %
5393
                                 (node, vg, requested, vg_free),
5394
                                 errors.ECODE_NORES)
5395

    
5396

    
5397
class LUInstanceStartup(LogicalUnit):
5398
  """Starts an instance.
5399

5400
  """
5401
  HPATH = "instance-start"
5402
  HTYPE = constants.HTYPE_INSTANCE
5403
  REQ_BGL = False
5404

    
5405
  def CheckArguments(self):
5406
    # extra beparams
5407
    if self.op.beparams:
5408
      # fill the beparams dict
5409
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
5410

    
5411
  def ExpandNames(self):
5412
    self._ExpandAndLockInstance()
5413

    
5414
  def BuildHooksEnv(self):
5415
    """Build hooks env.
5416

5417
    This runs on master, primary and secondary nodes of the instance.
5418

5419
    """
5420
    env = {
5421
      "FORCE": self.op.force,
5422
      }
5423

    
5424
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5425

    
5426
    return env
5427

    
5428
  def BuildHooksNodes(self):
5429
    """Build hooks nodes.
5430

5431
    """
5432
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5433
    return (nl, nl)
5434

    
5435
  def CheckPrereq(self):
5436
    """Check prerequisites.
5437

5438
    This checks that the instance is in the cluster.
5439

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

    
5445
    # extra hvparams
5446
    if self.op.hvparams:
5447
      # check hypervisor parameter syntax (locally)
5448
      cluster = self.cfg.GetClusterInfo()
5449
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
5450
      filled_hvp = cluster.FillHV(instance)
5451
      filled_hvp.update(self.op.hvparams)
5452
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
5453
      hv_type.CheckParameterSyntax(filled_hvp)
5454
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
5455

    
5456
    self.primary_offline = self.cfg.GetNodeInfo(instance.primary_node).offline
5457

    
5458
    if self.primary_offline and self.op.ignore_offline_nodes:
5459
      self.proc.LogWarning("Ignoring offline primary node")
5460

    
5461
      if self.op.hvparams or self.op.beparams:
5462
        self.proc.LogWarning("Overridden parameters are ignored")
5463
    else:
5464
      _CheckNodeOnline(self, instance.primary_node)
5465

    
5466
      bep = self.cfg.GetClusterInfo().FillBE(instance)
5467

    
5468
      # check bridges existence
5469
      _CheckInstanceBridgesExist(self, instance)
5470

    
5471
      remote_info = self.rpc.call_instance_info(instance.primary_node,
5472
                                                instance.name,
5473
                                                instance.hypervisor)
5474
      remote_info.Raise("Error checking node %s" % instance.primary_node,
5475
                        prereq=True, ecode=errors.ECODE_ENVIRON)
5476
      if not remote_info.payload: # not running already
5477
        _CheckNodeFreeMemory(self, instance.primary_node,
5478
                             "starting instance %s" % instance.name,
5479
                             bep[constants.BE_MEMORY], instance.hypervisor)
5480

    
5481
  def Exec(self, feedback_fn):
5482
    """Start the instance.
5483

5484
    """
5485
    instance = self.instance
5486
    force = self.op.force
5487

    
5488
    if not self.op.no_remember:
5489
      self.cfg.MarkInstanceUp(instance.name)
5490

    
5491
    if self.primary_offline:
5492
      assert self.op.ignore_offline_nodes
5493
      self.proc.LogInfo("Primary node offline, marked instance as started")
5494
    else:
5495
      node_current = instance.primary_node
5496

    
5497
      _StartInstanceDisks(self, instance, force)
5498

    
5499
      result = self.rpc.call_instance_start(node_current, instance,
5500
                                            self.op.hvparams, self.op.beparams)
5501
      msg = result.fail_msg
5502
      if msg:
5503
        _ShutdownInstanceDisks(self, instance)
5504
        raise errors.OpExecError("Could not start instance: %s" % msg)
5505

    
5506

    
5507
class LUInstanceReboot(LogicalUnit):
5508
  """Reboot an instance.
5509

5510
  """
5511
  HPATH = "instance-reboot"
5512
  HTYPE = constants.HTYPE_INSTANCE
5513
  REQ_BGL = False
5514

    
5515
  def ExpandNames(self):
5516
    self._ExpandAndLockInstance()
5517

    
5518
  def BuildHooksEnv(self):
5519
    """Build hooks env.
5520

5521
    This runs on master, primary and secondary nodes of the instance.
5522

5523
    """
5524
    env = {
5525
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
5526
      "REBOOT_TYPE": self.op.reboot_type,
5527
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5528
      }
5529

    
5530
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5531

    
5532
    return env
5533

    
5534
  def BuildHooksNodes(self):
5535
    """Build hooks nodes.
5536

5537
    """
5538
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5539
    return (nl, nl)
5540

    
5541
  def CheckPrereq(self):
5542
    """Check prerequisites.
5543

5544
    This checks that the instance is in the cluster.
5545

5546
    """
5547
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5548
    assert self.instance is not None, \
5549
      "Cannot retrieve locked instance %s" % self.op.instance_name
5550

    
5551
    _CheckNodeOnline(self, instance.primary_node)
5552

    
5553
    # check bridges existence
5554
    _CheckInstanceBridgesExist(self, instance)
5555

    
5556
  def Exec(self, feedback_fn):
5557
    """Reboot the instance.
5558

5559
    """
5560
    instance = self.instance
5561
    ignore_secondaries = self.op.ignore_secondaries
5562
    reboot_type = self.op.reboot_type
5563

    
5564
    remote_info = self.rpc.call_instance_info(instance.primary_node,
5565
                                              instance.name,
5566
                                              instance.hypervisor)
5567
    remote_info.Raise("Error checking node %s" % instance.primary_node)
5568
    instance_running = bool(remote_info.payload)
5569

    
5570
    node_current = instance.primary_node
5571

    
5572
    if instance_running and reboot_type in [constants.INSTANCE_REBOOT_SOFT,
5573
                                            constants.INSTANCE_REBOOT_HARD]:
5574
      for disk in instance.disks:
5575
        self.cfg.SetDiskID(disk, node_current)
5576
      result = self.rpc.call_instance_reboot(node_current, instance,
5577
                                             reboot_type,
5578
                                             self.op.shutdown_timeout)
5579
      result.Raise("Could not reboot instance")
5580
    else:
5581
      if instance_running:
5582
        result = self.rpc.call_instance_shutdown(node_current, instance,
5583
                                                 self.op.shutdown_timeout)
5584
        result.Raise("Could not shutdown instance for full reboot")
5585
        _ShutdownInstanceDisks(self, instance)
5586
      else:
5587
        self.LogInfo("Instance %s was already stopped, starting now",
5588
                     instance.name)
5589
      _StartInstanceDisks(self, instance, ignore_secondaries)
5590
      result = self.rpc.call_instance_start(node_current, instance, None, None)
5591
      msg = result.fail_msg
5592
      if msg:
5593
        _ShutdownInstanceDisks(self, instance)
5594
        raise errors.OpExecError("Could not start instance for"
5595
                                 " full reboot: %s" % msg)
5596

    
5597
    self.cfg.MarkInstanceUp(instance.name)
5598

    
5599

    
5600
class LUInstanceShutdown(LogicalUnit):
5601
  """Shutdown an instance.
5602

5603
  """
5604
  HPATH = "instance-stop"
5605
  HTYPE = constants.HTYPE_INSTANCE
5606
  REQ_BGL = False
5607

    
5608
  def ExpandNames(self):
5609
    self._ExpandAndLockInstance()
5610

    
5611
  def BuildHooksEnv(self):
5612
    """Build hooks env.
5613

5614
    This runs on master, primary and secondary nodes of the instance.
5615

5616
    """
5617
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5618
    env["TIMEOUT"] = self.op.timeout
5619
    return env
5620

    
5621
  def BuildHooksNodes(self):
5622
    """Build hooks nodes.
5623

5624
    """
5625
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5626
    return (nl, nl)
5627

    
5628
  def CheckPrereq(self):
5629
    """Check prerequisites.
5630

5631
    This checks that the instance is in the cluster.
5632

5633
    """
5634
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5635
    assert self.instance is not None, \
5636
      "Cannot retrieve locked instance %s" % self.op.instance_name
5637

    
5638
    self.primary_offline = \
5639
      self.cfg.GetNodeInfo(self.instance.primary_node).offline
5640

    
5641
    if self.primary_offline and self.op.ignore_offline_nodes:
5642
      self.proc.LogWarning("Ignoring offline primary node")
5643
    else:
5644
      _CheckNodeOnline(self, self.instance.primary_node)
5645

    
5646
  def Exec(self, feedback_fn):
5647
    """Shutdown the instance.
5648

5649
    """
5650
    instance = self.instance
5651
    node_current = instance.primary_node
5652
    timeout = self.op.timeout
5653

    
5654
    if not self.op.no_remember:
5655
      self.cfg.MarkInstanceDown(instance.name)
5656

    
5657
    if self.primary_offline:
5658
      assert self.op.ignore_offline_nodes
5659
      self.proc.LogInfo("Primary node offline, marked instance as stopped")
5660
    else:
5661
      result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
5662
      msg = result.fail_msg
5663
      if msg:
5664
        self.proc.LogWarning("Could not shutdown instance: %s" % msg)
5665

    
5666
      _ShutdownInstanceDisks(self, instance)
5667

    
5668

    
5669
class LUInstanceReinstall(LogicalUnit):
5670
  """Reinstall an instance.
5671

5672
  """
5673
  HPATH = "instance-reinstall"
5674
  HTYPE = constants.HTYPE_INSTANCE
5675
  REQ_BGL = False
5676

    
5677
  def ExpandNames(self):
5678
    self._ExpandAndLockInstance()
5679

    
5680
  def BuildHooksEnv(self):
5681
    """Build hooks env.
5682

5683
    This runs on master, primary and secondary nodes of the instance.
5684

5685
    """
5686
    return _BuildInstanceHookEnvByObject(self, self.instance)
5687

    
5688
  def BuildHooksNodes(self):
5689
    """Build hooks nodes.
5690

5691
    """
5692
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5693
    return (nl, nl)
5694

    
5695
  def CheckPrereq(self):
5696
    """Check prerequisites.
5697

5698
    This checks that the instance is in the cluster and is not running.
5699

5700
    """
5701
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5702
    assert instance is not None, \
5703
      "Cannot retrieve locked instance %s" % self.op.instance_name
5704
    _CheckNodeOnline(self, instance.primary_node, "Instance primary node"
5705
                     " offline, cannot reinstall")
5706
    for node in instance.secondary_nodes:
5707
      _CheckNodeOnline(self, node, "Instance secondary node offline,"
5708
                       " cannot reinstall")
5709

    
5710
    if instance.disk_template == constants.DT_DISKLESS:
5711
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5712
                                 self.op.instance_name,
5713
                                 errors.ECODE_INVAL)
5714
    _CheckInstanceDown(self, instance, "cannot reinstall")
5715

    
5716
    if self.op.os_type is not None:
5717
      # OS verification
5718
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
5719
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
5720
      instance_os = self.op.os_type
5721
    else:
5722
      instance_os = instance.os
5723

    
5724
    nodelist = list(instance.all_nodes)
5725

    
5726
    if self.op.osparams:
5727
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
5728
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
5729
      self.os_inst = i_osdict # the new dict (without defaults)
5730
    else:
5731
      self.os_inst = None
5732

    
5733
    self.instance = instance
5734

    
5735
  def Exec(self, feedback_fn):
5736
    """Reinstall the instance.
5737

5738
    """
5739
    inst = self.instance
5740

    
5741
    if self.op.os_type is not None:
5742
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
5743
      inst.os = self.op.os_type
5744
      # Write to configuration
5745
      self.cfg.Update(inst, feedback_fn)
5746

    
5747
    _StartInstanceDisks(self, inst, None)
5748
    try:
5749
      feedback_fn("Running the instance OS create scripts...")
5750
      # FIXME: pass debug option from opcode to backend
5751
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
5752
                                             self.op.debug_level,
5753
                                             osparams=self.os_inst)
5754
      result.Raise("Could not install OS for instance %s on node %s" %
5755
                   (inst.name, inst.primary_node))
5756
    finally:
5757
      _ShutdownInstanceDisks(self, inst)
5758

    
5759

    
5760
class LUInstanceRecreateDisks(LogicalUnit):
5761
  """Recreate an instance's missing disks.
5762

5763
  """
5764
  HPATH = "instance-recreate-disks"
5765
  HTYPE = constants.HTYPE_INSTANCE
5766
  REQ_BGL = False
5767

    
5768
  def CheckArguments(self):
5769
    # normalise the disk list
5770
    self.op.disks = sorted(frozenset(self.op.disks))
5771

    
5772
  def ExpandNames(self):
5773
    self._ExpandAndLockInstance()
5774
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5775
    if self.op.nodes:
5776
      self.op.nodes = [_ExpandNodeName(self.cfg, n) for n in self.op.nodes]
5777
      self.needed_locks[locking.LEVEL_NODE] = list(self.op.nodes)
5778
    else:
5779
      self.needed_locks[locking.LEVEL_NODE] = []
5780

    
5781
  def DeclareLocks(self, level):
5782
    if level == locking.LEVEL_NODE:
5783
      # if we replace the nodes, we only need to lock the old primary,
5784
      # otherwise we need to lock all nodes for disk re-creation
5785
      primary_only = bool(self.op.nodes)
5786
      self._LockInstancesNodes(primary_only=primary_only)
5787

    
5788
  def BuildHooksEnv(self):
5789
    """Build hooks env.
5790

5791
    This runs on master, primary and secondary nodes of the instance.
5792

5793
    """
5794
    return _BuildInstanceHookEnvByObject(self, self.instance)
5795

    
5796
  def BuildHooksNodes(self):
5797
    """Build hooks nodes.
5798

5799
    """
5800
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5801
    return (nl, nl)
5802

    
5803
  def CheckPrereq(self):
5804
    """Check prerequisites.
5805

5806
    This checks that the instance is in the cluster and is not running.
5807

5808
    """
5809
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5810
    assert instance is not None, \
5811
      "Cannot retrieve locked instance %s" % self.op.instance_name
5812
    if self.op.nodes:
5813
      if len(self.op.nodes) != len(instance.all_nodes):
5814
        raise errors.OpPrereqError("Instance %s currently has %d nodes, but"
5815
                                   " %d replacement nodes were specified" %
5816
                                   (instance.name, len(instance.all_nodes),
5817
                                    len(self.op.nodes)),
5818
                                   errors.ECODE_INVAL)
5819
      assert instance.disk_template != constants.DT_DRBD8 or \
5820
          len(self.op.nodes) == 2
5821
      assert instance.disk_template != constants.DT_PLAIN or \
5822
          len(self.op.nodes) == 1
5823
      primary_node = self.op.nodes[0]
5824
    else:
5825
      primary_node = instance.primary_node
5826
    _CheckNodeOnline(self, primary_node)
5827

    
5828
    if instance.disk_template == constants.DT_DISKLESS:
5829
      raise errors.OpPrereqError("Instance '%s' has no disks" %
5830
                                 self.op.instance_name, errors.ECODE_INVAL)
5831
    # if we replace nodes *and* the old primary is offline, we don't
5832
    # check
5833
    assert instance.primary_node in self.needed_locks[locking.LEVEL_NODE]
5834
    old_pnode = self.cfg.GetNodeInfo(instance.primary_node)
5835
    if not (self.op.nodes and old_pnode.offline):
5836
      _CheckInstanceDown(self, instance, "cannot recreate disks")
5837

    
5838
    if not self.op.disks:
5839
      self.op.disks = range(len(instance.disks))
5840
    else:
5841
      for idx in self.op.disks:
5842
        if idx >= len(instance.disks):
5843
          raise errors.OpPrereqError("Invalid disk index '%s'" % idx,
5844
                                     errors.ECODE_INVAL)
5845
    if self.op.disks != range(len(instance.disks)) and self.op.nodes:
5846
      raise errors.OpPrereqError("Can't recreate disks partially and"
5847
                                 " change the nodes at the same time",
5848
                                 errors.ECODE_INVAL)
5849
    self.instance = instance
5850

    
5851
  def Exec(self, feedback_fn):
5852
    """Recreate the disks.
5853

5854
    """
5855
    # change primary node, if needed
5856
    if self.op.nodes:
5857
      self.instance.primary_node = self.op.nodes[0]
5858
      self.LogWarning("Changing the instance's nodes, you will have to"
5859
                      " remove any disks left on the older nodes manually")
5860

    
5861
    to_skip = []
5862
    for idx, disk in enumerate(self.instance.disks):
5863
      if idx not in self.op.disks: # disk idx has not been passed in
5864
        to_skip.append(idx)
5865
        continue
5866
      # update secondaries for disks, if needed
5867
      if self.op.nodes:
5868
        if disk.dev_type == constants.LD_DRBD8:
5869
          # need to update the nodes
5870
          assert len(self.op.nodes) == 2
5871
          logical_id = list(disk.logical_id)
5872
          logical_id[0] = self.op.nodes[0]
5873
          logical_id[1] = self.op.nodes[1]
5874
          disk.logical_id = tuple(logical_id)
5875

    
5876
    if self.op.nodes:
5877
      self.cfg.Update(self.instance, feedback_fn)
5878

    
5879
    _CreateDisks(self, self.instance, to_skip=to_skip)
5880

    
5881

    
5882
class LUInstanceRename(LogicalUnit):
5883
  """Rename an instance.
5884

5885
  """
5886
  HPATH = "instance-rename"
5887
  HTYPE = constants.HTYPE_INSTANCE
5888

    
5889
  def CheckArguments(self):
5890
    """Check arguments.
5891

5892
    """
5893
    if self.op.ip_check and not self.op.name_check:
5894
      # TODO: make the ip check more flexible and not depend on the name check
5895
      raise errors.OpPrereqError("IP address check requires a name check",
5896
                                 errors.ECODE_INVAL)
5897

    
5898
  def BuildHooksEnv(self):
5899
    """Build hooks env.
5900

5901
    This runs on master, primary and secondary nodes of the instance.
5902

5903
    """
5904
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5905
    env["INSTANCE_NEW_NAME"] = self.op.new_name
5906
    return env
5907

    
5908
  def BuildHooksNodes(self):
5909
    """Build hooks nodes.
5910

5911
    """
5912
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
5913
    return (nl, nl)
5914

    
5915
  def CheckPrereq(self):
5916
    """Check prerequisites.
5917

5918
    This checks that the instance is in the cluster and is not running.
5919

5920
    """
5921
    self.op.instance_name = _ExpandInstanceName(self.cfg,
5922
                                                self.op.instance_name)
5923
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5924
    assert instance is not None
5925
    _CheckNodeOnline(self, instance.primary_node)
5926
    _CheckInstanceDown(self, instance, "cannot rename")
5927
    self.instance = instance
5928

    
5929
    new_name = self.op.new_name
5930
    if self.op.name_check:
5931
      hostname = netutils.GetHostname(name=new_name)
5932
      if hostname != new_name:
5933
        self.LogInfo("Resolved given name '%s' to '%s'", new_name,
5934
                     hostname.name)
5935
      if not utils.MatchNameComponent(self.op.new_name, [hostname.name]):
5936
        raise errors.OpPrereqError(("Resolved hostname '%s' does not look the"
5937
                                    " same as given hostname '%s'") %
5938
                                    (hostname.name, self.op.new_name),
5939
                                    errors.ECODE_INVAL)
5940
      new_name = self.op.new_name = hostname.name
5941
      if (self.op.ip_check and
5942
          netutils.TcpPing(hostname.ip, constants.DEFAULT_NODED_PORT)):
5943
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
5944
                                   (hostname.ip, new_name),
5945
                                   errors.ECODE_NOTUNIQUE)
5946

    
5947
    instance_list = self.cfg.GetInstanceList()
5948
    if new_name in instance_list and new_name != instance.name:
5949
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
5950
                                 new_name, errors.ECODE_EXISTS)
5951

    
5952
  def Exec(self, feedback_fn):
5953
    """Rename the instance.
5954

5955
    """
5956
    inst = self.instance
5957
    old_name = inst.name
5958

    
5959
    rename_file_storage = False
5960
    if (inst.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE) and
5961
        self.op.new_name != inst.name):
5962
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5963
      rename_file_storage = True
5964

    
5965
    self.cfg.RenameInstance(inst.name, self.op.new_name)
5966
    # Change the instance lock. This is definitely safe while we hold the BGL.
5967
    # Otherwise the new lock would have to be added in acquired mode.
5968
    assert self.REQ_BGL
5969
    self.glm.remove(locking.LEVEL_INSTANCE, old_name)
5970
    self.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
5971

    
5972
    # re-read the instance from the configuration after rename
5973
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
5974

    
5975
    if rename_file_storage:
5976
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
5977
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
5978
                                                     old_file_storage_dir,
5979
                                                     new_file_storage_dir)
5980
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
5981
                   " (but the instance has been renamed in Ganeti)" %
5982
                   (inst.primary_node, old_file_storage_dir,
5983
                    new_file_storage_dir))
5984

    
5985
    _StartInstanceDisks(self, inst, None)
5986
    try:
5987
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
5988
                                                 old_name, self.op.debug_level)
5989
      msg = result.fail_msg
5990
      if msg:
5991
        msg = ("Could not run OS rename script for instance %s on node %s"
5992
               " (but the instance has been renamed in Ganeti): %s" %
5993
               (inst.name, inst.primary_node, msg))
5994
        self.proc.LogWarning(msg)
5995
    finally:
5996
      _ShutdownInstanceDisks(self, inst)
5997

    
5998
    return inst.name
5999

    
6000

    
6001
class LUInstanceRemove(LogicalUnit):
6002
  """Remove an instance.
6003

6004
  """
6005
  HPATH = "instance-remove"
6006
  HTYPE = constants.HTYPE_INSTANCE
6007
  REQ_BGL = False
6008

    
6009
  def ExpandNames(self):
6010
    self._ExpandAndLockInstance()
6011
    self.needed_locks[locking.LEVEL_NODE] = []
6012
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6013

    
6014
  def DeclareLocks(self, level):
6015
    if level == locking.LEVEL_NODE:
6016
      self._LockInstancesNodes()
6017

    
6018
  def BuildHooksEnv(self):
6019
    """Build hooks env.
6020

6021
    This runs on master, primary and secondary nodes of the instance.
6022

6023
    """
6024
    env = _BuildInstanceHookEnvByObject(self, self.instance)
6025
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
6026
    return env
6027

    
6028
  def BuildHooksNodes(self):
6029
    """Build hooks nodes.
6030

6031
    """
6032
    nl = [self.cfg.GetMasterNode()]
6033
    nl_post = list(self.instance.all_nodes) + nl
6034
    return (nl, nl_post)
6035

    
6036
  def CheckPrereq(self):
6037
    """Check prerequisites.
6038

6039
    This checks that the instance is in the cluster.
6040

6041
    """
6042
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6043
    assert self.instance is not None, \
6044
      "Cannot retrieve locked instance %s" % self.op.instance_name
6045

    
6046
  def Exec(self, feedback_fn):
6047
    """Remove the instance.
6048

6049
    """
6050
    instance = self.instance
6051
    logging.info("Shutting down instance %s on node %s",
6052
                 instance.name, instance.primary_node)
6053

    
6054
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
6055
                                             self.op.shutdown_timeout)
6056
    msg = result.fail_msg
6057
    if msg:
6058
      if self.op.ignore_failures:
6059
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
6060
      else:
6061
        raise errors.OpExecError("Could not shutdown instance %s on"
6062
                                 " node %s: %s" %
6063
                                 (instance.name, instance.primary_node, msg))
6064

    
6065
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
6066

    
6067

    
6068
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
6069
  """Utility function to remove an instance.
6070

6071
  """
6072
  logging.info("Removing block devices for instance %s", instance.name)
6073

    
6074
  if not _RemoveDisks(lu, instance):
6075
    if not ignore_failures:
6076
      raise errors.OpExecError("Can't remove instance's disks")
6077
    feedback_fn("Warning: can't remove instance's disks")
6078

    
6079
  logging.info("Removing instance %s out of cluster config", instance.name)
6080

    
6081
  lu.cfg.RemoveInstance(instance.name)
6082

    
6083
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
6084
    "Instance lock removal conflict"
6085

    
6086
  # Remove lock for the instance
6087
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
6088

    
6089

    
6090
class LUInstanceQuery(NoHooksLU):
6091
  """Logical unit for querying instances.
6092

6093
  """
6094
  # pylint: disable-msg=W0142
6095
  REQ_BGL = False
6096

    
6097
  def CheckArguments(self):
6098
    self.iq = _InstanceQuery(qlang.MakeSimpleFilter("name", self.op.names),
6099
                             self.op.output_fields, self.op.use_locking)
6100

    
6101
  def ExpandNames(self):
6102
    self.iq.ExpandNames(self)
6103

    
6104
  def DeclareLocks(self, level):
6105
    self.iq.DeclareLocks(self, level)
6106

    
6107
  def Exec(self, feedback_fn):
6108
    return self.iq.OldStyleQuery(self)
6109

    
6110

    
6111
class LUInstanceFailover(LogicalUnit):
6112
  """Failover an instance.
6113

6114
  """
6115
  HPATH = "instance-failover"
6116
  HTYPE = constants.HTYPE_INSTANCE
6117
  REQ_BGL = False
6118

    
6119
  def CheckArguments(self):
6120
    """Check the arguments.
6121

6122
    """
6123
    self.iallocator = getattr(self.op, "iallocator", None)
6124
    self.target_node = getattr(self.op, "target_node", None)
6125

    
6126
  def ExpandNames(self):
6127
    self._ExpandAndLockInstance()
6128

    
6129
    if self.op.target_node is not None:
6130
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6131

    
6132
    self.needed_locks[locking.LEVEL_NODE] = []
6133
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6134

    
6135
    ignore_consistency = self.op.ignore_consistency
6136
    shutdown_timeout = self.op.shutdown_timeout
6137
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6138
                                       cleanup=False,
6139
                                       failover=True,
6140
                                       ignore_consistency=ignore_consistency,
6141
                                       shutdown_timeout=shutdown_timeout)
6142
    self.tasklets = [self._migrater]
6143

    
6144
  def DeclareLocks(self, level):
6145
    if level == locking.LEVEL_NODE:
6146
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6147
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6148
        if self.op.target_node is None:
6149
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6150
        else:
6151
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6152
                                                   self.op.target_node]
6153
        del self.recalculate_locks[locking.LEVEL_NODE]
6154
      else:
6155
        self._LockInstancesNodes()
6156

    
6157
  def BuildHooksEnv(self):
6158
    """Build hooks env.
6159

6160
    This runs on master, primary and secondary nodes of the instance.
6161

6162
    """
6163
    instance = self._migrater.instance
6164
    source_node = instance.primary_node
6165
    target_node = self.op.target_node
6166
    env = {
6167
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
6168
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6169
      "OLD_PRIMARY": source_node,
6170
      "NEW_PRIMARY": target_node,
6171
      }
6172

    
6173
    if instance.disk_template in constants.DTS_INT_MIRROR:
6174
      env["OLD_SECONDARY"] = instance.secondary_nodes[0]
6175
      env["NEW_SECONDARY"] = source_node
6176
    else:
6177
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = ""
6178

    
6179
    env.update(_BuildInstanceHookEnvByObject(self, instance))
6180

    
6181
    return env
6182

    
6183
  def BuildHooksNodes(self):
6184
    """Build hooks nodes.
6185

6186
    """
6187
    instance = self._migrater.instance
6188
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6189
    return (nl, nl + [instance.primary_node])
6190

    
6191

    
6192
class LUInstanceMigrate(LogicalUnit):
6193
  """Migrate an instance.
6194

6195
  This is migration without shutting down, compared to the failover,
6196
  which is done with shutdown.
6197

6198
  """
6199
  HPATH = "instance-migrate"
6200
  HTYPE = constants.HTYPE_INSTANCE
6201
  REQ_BGL = False
6202

    
6203
  def ExpandNames(self):
6204
    self._ExpandAndLockInstance()
6205

    
6206
    if self.op.target_node is not None:
6207
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6208

    
6209
    self.needed_locks[locking.LEVEL_NODE] = []
6210
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
6211

    
6212
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
6213
                                       cleanup=self.op.cleanup,
6214
                                       failover=False,
6215
                                       fallback=self.op.allow_failover)
6216
    self.tasklets = [self._migrater]
6217

    
6218
  def DeclareLocks(self, level):
6219
    if level == locking.LEVEL_NODE:
6220
      instance = self.context.cfg.GetInstanceInfo(self.op.instance_name)
6221
      if instance.disk_template in constants.DTS_EXT_MIRROR:
6222
        if self.op.target_node is None:
6223
          self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6224
        else:
6225
          self.needed_locks[locking.LEVEL_NODE] = [instance.primary_node,
6226
                                                   self.op.target_node]
6227
        del self.recalculate_locks[locking.LEVEL_NODE]
6228
      else:
6229
        self._LockInstancesNodes()
6230

    
6231
  def BuildHooksEnv(self):
6232
    """Build hooks env.
6233

6234
    This runs on master, primary and secondary nodes of the instance.
6235

6236
    """
6237
    instance = self._migrater.instance
6238
    source_node = instance.primary_node
6239
    target_node = self.op.target_node
6240
    env = _BuildInstanceHookEnvByObject(self, instance)
6241
    env.update({
6242
      "MIGRATE_LIVE": self._migrater.live,
6243
      "MIGRATE_CLEANUP": self.op.cleanup,
6244
      "OLD_PRIMARY": source_node,
6245
      "NEW_PRIMARY": target_node,
6246
      })
6247

    
6248
    if instance.disk_template in constants.DTS_INT_MIRROR:
6249
      env["OLD_SECONDARY"] = target_node
6250
      env["NEW_SECONDARY"] = source_node
6251
    else:
6252
      env["OLD_SECONDARY"] = env["NEW_SECONDARY"] = None
6253

    
6254
    return env
6255

    
6256
  def BuildHooksNodes(self):
6257
    """Build hooks nodes.
6258

6259
    """
6260
    instance = self._migrater.instance
6261
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
6262
    return (nl, nl + [instance.primary_node])
6263

    
6264

    
6265
class LUInstanceMove(LogicalUnit):
6266
  """Move an instance by data-copying.
6267

6268
  """
6269
  HPATH = "instance-move"
6270
  HTYPE = constants.HTYPE_INSTANCE
6271
  REQ_BGL = False
6272

    
6273
  def ExpandNames(self):
6274
    self._ExpandAndLockInstance()
6275
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
6276
    self.op.target_node = target_node
6277
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
6278
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6279

    
6280
  def DeclareLocks(self, level):
6281
    if level == locking.LEVEL_NODE:
6282
      self._LockInstancesNodes(primary_only=True)
6283

    
6284
  def BuildHooksEnv(self):
6285
    """Build hooks env.
6286

6287
    This runs on master, primary and secondary nodes of the instance.
6288

6289
    """
6290
    env = {
6291
      "TARGET_NODE": self.op.target_node,
6292
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
6293
      }
6294
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
6295
    return env
6296

    
6297
  def BuildHooksNodes(self):
6298
    """Build hooks nodes.
6299

6300
    """
6301
    nl = [
6302
      self.cfg.GetMasterNode(),
6303
      self.instance.primary_node,
6304
      self.op.target_node,
6305
      ]
6306
    return (nl, nl)
6307

    
6308
  def CheckPrereq(self):
6309
    """Check prerequisites.
6310

6311
    This checks that the instance is in the cluster.
6312

6313
    """
6314
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
6315
    assert self.instance is not None, \
6316
      "Cannot retrieve locked instance %s" % self.op.instance_name
6317

    
6318
    node = self.cfg.GetNodeInfo(self.op.target_node)
6319
    assert node is not None, \
6320
      "Cannot retrieve locked node %s" % self.op.target_node
6321

    
6322
    self.target_node = target_node = node.name
6323

    
6324
    if target_node == instance.primary_node:
6325
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
6326
                                 (instance.name, target_node),
6327
                                 errors.ECODE_STATE)
6328

    
6329
    bep = self.cfg.GetClusterInfo().FillBE(instance)
6330

    
6331
    for idx, dsk in enumerate(instance.disks):
6332
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
6333
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
6334
                                   " cannot copy" % idx, errors.ECODE_STATE)
6335

    
6336
    _CheckNodeOnline(self, target_node)
6337
    _CheckNodeNotDrained(self, target_node)
6338
    _CheckNodeVmCapable(self, target_node)
6339

    
6340
    if instance.admin_up:
6341
      # check memory requirements on the secondary node
6342
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
6343
                           instance.name, bep[constants.BE_MEMORY],
6344
                           instance.hypervisor)
6345
    else:
6346
      self.LogInfo("Not checking memory on the secondary node as"
6347
                   " instance will not be started")
6348

    
6349
    # check bridge existance
6350
    _CheckInstanceBridgesExist(self, instance, node=target_node)
6351

    
6352
  def Exec(self, feedback_fn):
6353
    """Move an instance.
6354

6355
    The move is done by shutting it down on its present node, copying
6356
    the data over (slow) and starting it on the new node.
6357

6358
    """
6359
    instance = self.instance
6360

    
6361
    source_node = instance.primary_node
6362
    target_node = self.target_node
6363

    
6364
    self.LogInfo("Shutting down instance %s on source node %s",
6365
                 instance.name, source_node)
6366

    
6367
    result = self.rpc.call_instance_shutdown(source_node, instance,
6368
                                             self.op.shutdown_timeout)
6369
    msg = result.fail_msg
6370
    if msg:
6371
      if self.op.ignore_consistency:
6372
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
6373
                             " Proceeding anyway. Please make sure node"
6374
                             " %s is down. Error details: %s",
6375
                             instance.name, source_node, source_node, msg)
6376
      else:
6377
        raise errors.OpExecError("Could not shutdown instance %s on"
6378
                                 " node %s: %s" %
6379
                                 (instance.name, source_node, msg))
6380

    
6381
    # create the target disks
6382
    try:
6383
      _CreateDisks(self, instance, target_node=target_node)
6384
    except errors.OpExecError:
6385
      self.LogWarning("Device creation failed, reverting...")
6386
      try:
6387
        _RemoveDisks(self, instance, target_node=target_node)
6388
      finally:
6389
        self.cfg.ReleaseDRBDMinors(instance.name)
6390
        raise
6391

    
6392
    cluster_name = self.cfg.GetClusterInfo().cluster_name
6393

    
6394
    errs = []
6395
    # activate, get path, copy the data over
6396
    for idx, disk in enumerate(instance.disks):
6397
      self.LogInfo("Copying data for disk %d", idx)
6398
      result = self.rpc.call_blockdev_assemble(target_node, disk,
6399
                                               instance.name, True, idx)
6400
      if result.fail_msg:
6401
        self.LogWarning("Can't assemble newly created disk %d: %s",
6402
                        idx, result.fail_msg)
6403
        errs.append(result.fail_msg)
6404
        break
6405
      dev_path = result.payload
6406
      result = self.rpc.call_blockdev_export(source_node, disk,
6407
                                             target_node, dev_path,
6408
                                             cluster_name)
6409
      if result.fail_msg:
6410
        self.LogWarning("Can't copy data over for disk %d: %s",
6411
                        idx, result.fail_msg)
6412
        errs.append(result.fail_msg)
6413
        break
6414

    
6415
    if errs:
6416
      self.LogWarning("Some disks failed to copy, aborting")
6417
      try:
6418
        _RemoveDisks(self, instance, target_node=target_node)
6419
      finally:
6420
        self.cfg.ReleaseDRBDMinors(instance.name)
6421
        raise errors.OpExecError("Errors during disk copy: %s" %
6422
                                 (",".join(errs),))
6423

    
6424
    instance.primary_node = target_node
6425
    self.cfg.Update(instance, feedback_fn)
6426

    
6427
    self.LogInfo("Removing the disks on the original node")
6428
    _RemoveDisks(self, instance, target_node=source_node)
6429

    
6430
    # Only start the instance if it's marked as up
6431
    if instance.admin_up:
6432
      self.LogInfo("Starting instance %s on node %s",
6433
                   instance.name, target_node)
6434

    
6435
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
6436
                                           ignore_secondaries=True)
6437
      if not disks_ok:
6438
        _ShutdownInstanceDisks(self, instance)
6439
        raise errors.OpExecError("Can't activate the instance's disks")
6440

    
6441
      result = self.rpc.call_instance_start(target_node, instance, None, None)
6442
      msg = result.fail_msg
6443
      if msg:
6444
        _ShutdownInstanceDisks(self, instance)
6445
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
6446
                                 (instance.name, target_node, msg))
6447

    
6448

    
6449
class LUNodeMigrate(LogicalUnit):
6450
  """Migrate all instances from a node.
6451

6452
  """
6453
  HPATH = "node-migrate"
6454
  HTYPE = constants.HTYPE_NODE
6455
  REQ_BGL = False
6456

    
6457
  def CheckArguments(self):
6458
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
6459

    
6460
  def ExpandNames(self):
6461
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
6462

    
6463
    self.needed_locks = {}
6464

    
6465
    # Create tasklets for migrating instances for all instances on this node
6466
    names = []
6467
    tasklets = []
6468

    
6469
    self.lock_all_nodes = False
6470

    
6471
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
6472
      logging.debug("Migrating instance %s", inst.name)
6473
      names.append(inst.name)
6474

    
6475
      tasklets.append(TLMigrateInstance(self, inst.name, cleanup=False))
6476

    
6477
      if inst.disk_template in constants.DTS_EXT_MIRROR:
6478
        # We need to lock all nodes, as the iallocator will choose the
6479
        # destination nodes afterwards
6480
        self.lock_all_nodes = True
6481

    
6482
    self.tasklets = tasklets
6483

    
6484
    # Declare node locks
6485
    if self.lock_all_nodes:
6486
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6487
    else:
6488
      self.needed_locks[locking.LEVEL_NODE] = [self.op.node_name]
6489
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
6490

    
6491
    # Declare instance locks
6492
    self.needed_locks[locking.LEVEL_INSTANCE] = names
6493

    
6494
  def DeclareLocks(self, level):
6495
    if level == locking.LEVEL_NODE and not self.lock_all_nodes:
6496
      self._LockInstancesNodes()
6497

    
6498
  def BuildHooksEnv(self):
6499
    """Build hooks env.
6500

6501
    This runs on the master, the primary and all the secondaries.
6502

6503
    """
6504
    return {
6505
      "NODE_NAME": self.op.node_name,
6506
      }
6507

    
6508
  def BuildHooksNodes(self):
6509
    """Build hooks nodes.
6510

6511
    """
6512
    nl = [self.cfg.GetMasterNode()]
6513
    return (nl, nl)
6514

    
6515

    
6516
class TLMigrateInstance(Tasklet):
6517
  """Tasklet class for instance migration.
6518

6519
  @type live: boolean
6520
  @ivar live: whether the migration will be done live or non-live;
6521
      this variable is initalized only after CheckPrereq has run
6522
  @type cleanup: boolean
6523
  @ivar cleanup: Wheater we cleanup from a failed migration
6524
  @type iallocator: string
6525
  @ivar iallocator: The iallocator used to determine target_node
6526
  @type target_node: string
6527
  @ivar target_node: If given, the target_node to reallocate the instance to
6528
  @type failover: boolean
6529
  @ivar failover: Whether operation results in failover or migration
6530
  @type fallback: boolean
6531
  @ivar fallback: Whether fallback to failover is allowed if migration not
6532
                  possible
6533
  @type ignore_consistency: boolean
6534
  @ivar ignore_consistency: Wheter we should ignore consistency between source
6535
                            and target node
6536
  @type shutdown_timeout: int
6537
  @ivar shutdown_timeout: In case of failover timeout of the shutdown
6538

6539
  """
6540
  def __init__(self, lu, instance_name, cleanup=False,
6541
               failover=False, fallback=False,
6542
               ignore_consistency=False,
6543
               shutdown_timeout=constants.DEFAULT_SHUTDOWN_TIMEOUT):
6544
    """Initializes this class.
6545

6546
    """
6547
    Tasklet.__init__(self, lu)
6548

    
6549
    # Parameters
6550
    self.instance_name = instance_name
6551
    self.cleanup = cleanup
6552
    self.live = False # will be overridden later
6553
    self.failover = failover
6554
    self.fallback = fallback
6555
    self.ignore_consistency = ignore_consistency
6556
    self.shutdown_timeout = shutdown_timeout
6557

    
6558
  def CheckPrereq(self):
6559
    """Check prerequisites.
6560

6561
    This checks that the instance is in the cluster.
6562

6563
    """
6564
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
6565
    instance = self.cfg.GetInstanceInfo(instance_name)
6566
    assert instance is not None
6567
    self.instance = instance
6568

    
6569
    if (not self.cleanup and not instance.admin_up and not self.failover and
6570
        self.fallback):
6571
      self.lu.LogInfo("Instance is marked down, fallback allowed, switching"
6572
                      " to failover")
6573
      self.failover = True
6574

    
6575
    if instance.disk_template not in constants.DTS_MIRRORED:
6576
      if self.failover:
6577
        text = "failovers"
6578
      else:
6579
        text = "migrations"
6580
      raise errors.OpPrereqError("Instance's disk layout '%s' does not allow"
6581
                                 " %s" % (instance.disk_template, text),
6582
                                 errors.ECODE_STATE)
6583

    
6584
    if instance.disk_template in constants.DTS_EXT_MIRROR:
6585
      _CheckIAllocatorOrNode(self.lu, "iallocator", "target_node")
6586

    
6587
      if self.lu.op.iallocator:
6588
        self._RunAllocator()
6589
      else:
6590
        # We set set self.target_node as it is required by
6591
        # BuildHooksEnv
6592
        self.target_node = self.lu.op.target_node
6593

    
6594
      # self.target_node is already populated, either directly or by the
6595
      # iallocator run
6596
      target_node = self.target_node
6597
      if self.target_node == instance.primary_node:
6598
        raise errors.OpPrereqError("Cannot migrate instance %s"
6599
                                   " to its primary (%s)" %
6600
                                   (instance.name, instance.primary_node))
6601

    
6602
      if len(self.lu.tasklets) == 1:
6603
        # It is safe to release locks only when we're the only tasklet
6604
        # in the LU
6605
        _ReleaseLocks(self.lu, locking.LEVEL_NODE,
6606
                      keep=[instance.primary_node, self.target_node])
6607

    
6608
    else:
6609
      secondary_nodes = instance.secondary_nodes
6610
      if not secondary_nodes:
6611
        raise errors.ConfigurationError("No secondary node but using"
6612
                                        " %s disk template" %
6613
                                        instance.disk_template)
6614
      target_node = secondary_nodes[0]
6615
      if self.lu.op.iallocator or (self.lu.op.target_node and
6616
                                   self.lu.op.target_node != target_node):
6617
        if self.failover:
6618
          text = "failed over"
6619
        else:
6620
          text = "migrated"
6621
        raise errors.OpPrereqError("Instances with disk template %s cannot"
6622
                                   " be %s to arbitrary nodes"
6623
                                   " (neither an iallocator nor a target"
6624
                                   " node can be passed)" %
6625
                                   (instance.disk_template, text),
6626
                                   errors.ECODE_INVAL)
6627

    
6628
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
6629

    
6630
    # check memory requirements on the secondary node
6631
    if not self.failover or instance.admin_up:
6632
      _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
6633
                           instance.name, i_be[constants.BE_MEMORY],
6634
                           instance.hypervisor)
6635
    else:
6636
      self.lu.LogInfo("Not checking memory on the secondary node as"
6637
                      " instance will not be started")
6638

    
6639
    # check bridge existance
6640
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
6641

    
6642
    if not self.cleanup:
6643
      _CheckNodeNotDrained(self.lu, target_node)
6644
      if not self.failover:
6645
        result = self.rpc.call_instance_migratable(instance.primary_node,
6646
                                                   instance)
6647
        if result.fail_msg and self.fallback:
6648
          self.lu.LogInfo("Can't migrate, instance offline, fallback to"
6649
                          " failover")
6650
          self.failover = True
6651
        else:
6652
          result.Raise("Can't migrate, please use failover",
6653
                       prereq=True, ecode=errors.ECODE_STATE)
6654

    
6655
    assert not (self.failover and self.cleanup)
6656

    
6657
    if not self.failover:
6658
      if self.lu.op.live is not None and self.lu.op.mode is not None:
6659
        raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
6660
                                   " parameters are accepted",
6661
                                   errors.ECODE_INVAL)
6662
      if self.lu.op.live is not None:
6663
        if self.lu.op.live:
6664
          self.lu.op.mode = constants.HT_MIGRATION_LIVE
6665
        else:
6666
          self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
6667
        # reset the 'live' parameter to None so that repeated
6668
        # invocations of CheckPrereq do not raise an exception
6669
        self.lu.op.live = None
6670
      elif self.lu.op.mode is None:
6671
        # read the default value from the hypervisor
6672
        i_hv = self.cfg.GetClusterInfo().FillHV(self.instance,
6673
                                                skip_globals=False)
6674
        self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
6675

    
6676
      self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
6677
    else:
6678
      # Failover is never live
6679
      self.live = False
6680

    
6681
  def _RunAllocator(self):
6682
    """Run the allocator based on input opcode.
6683

6684
    """
6685
    ial = IAllocator(self.cfg, self.rpc,
6686
                     mode=constants.IALLOCATOR_MODE_RELOC,
6687
                     name=self.instance_name,
6688
                     # TODO See why hail breaks with a single node below
6689
                     relocate_from=[self.instance.primary_node,
6690
                                    self.instance.primary_node],
6691
                     )
6692

    
6693
    ial.Run(self.lu.op.iallocator)
6694

    
6695
    if not ial.success:
6696
      raise errors.OpPrereqError("Can't compute nodes using"
6697
                                 " iallocator '%s': %s" %
6698
                                 (self.lu.op.iallocator, ial.info),
6699
                                 errors.ECODE_NORES)
6700
    if len(ial.result) != ial.required_nodes:
6701
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6702
                                 " of nodes (%s), required %s" %
6703
                                 (self.lu.op.iallocator, len(ial.result),
6704
                                  ial.required_nodes), errors.ECODE_FAULT)
6705
    self.target_node = ial.result[0]
6706
    self.lu.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6707
                 self.instance_name, self.lu.op.iallocator,
6708
                 utils.CommaJoin(ial.result))
6709

    
6710
  def _WaitUntilSync(self):
6711
    """Poll with custom rpc for disk sync.
6712

6713
    This uses our own step-based rpc call.
6714

6715
    """
6716
    self.feedback_fn("* wait until resync is done")
6717
    all_done = False
6718
    while not all_done:
6719
      all_done = True
6720
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
6721
                                            self.nodes_ip,
6722
                                            self.instance.disks)
6723
      min_percent = 100
6724
      for node, nres in result.items():
6725
        nres.Raise("Cannot resync disks on node %s" % node)
6726
        node_done, node_percent = nres.payload
6727
        all_done = all_done and node_done
6728
        if node_percent is not None:
6729
          min_percent = min(min_percent, node_percent)
6730
      if not all_done:
6731
        if min_percent < 100:
6732
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
6733
        time.sleep(2)
6734

    
6735
  def _EnsureSecondary(self, node):
6736
    """Demote a node to secondary.
6737

6738
    """
6739
    self.feedback_fn("* switching node %s to secondary mode" % node)
6740

    
6741
    for dev in self.instance.disks:
6742
      self.cfg.SetDiskID(dev, node)
6743

    
6744
    result = self.rpc.call_blockdev_close(node, self.instance.name,
6745
                                          self.instance.disks)
6746
    result.Raise("Cannot change disk to secondary on node %s" % node)
6747

    
6748
  def _GoStandalone(self):
6749
    """Disconnect from the network.
6750

6751
    """
6752
    self.feedback_fn("* changing into standalone mode")
6753
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
6754
                                               self.instance.disks)
6755
    for node, nres in result.items():
6756
      nres.Raise("Cannot disconnect disks node %s" % node)
6757

    
6758
  def _GoReconnect(self, multimaster):
6759
    """Reconnect to the network.
6760

6761
    """
6762
    if multimaster:
6763
      msg = "dual-master"
6764
    else:
6765
      msg = "single-master"
6766
    self.feedback_fn("* changing disks into %s mode" % msg)
6767
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
6768
                                           self.instance.disks,
6769
                                           self.instance.name, multimaster)
6770
    for node, nres in result.items():
6771
      nres.Raise("Cannot change disks config on node %s" % node)
6772

    
6773
  def _ExecCleanup(self):
6774
    """Try to cleanup after a failed migration.
6775

6776
    The cleanup is done by:
6777
      - check that the instance is running only on one node
6778
        (and update the config if needed)
6779
      - change disks on its secondary node to secondary
6780
      - wait until disks are fully synchronized
6781
      - disconnect from the network
6782
      - change disks into single-master mode
6783
      - wait again until disks are fully synchronized
6784

6785
    """
6786
    instance = self.instance
6787
    target_node = self.target_node
6788
    source_node = self.source_node
6789

    
6790
    # check running on only one node
6791
    self.feedback_fn("* checking where the instance actually runs"
6792
                     " (if this hangs, the hypervisor might be in"
6793
                     " a bad state)")
6794
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
6795
    for node, result in ins_l.items():
6796
      result.Raise("Can't contact node %s" % node)
6797

    
6798
    runningon_source = instance.name in ins_l[source_node].payload
6799
    runningon_target = instance.name in ins_l[target_node].payload
6800

    
6801
    if runningon_source and runningon_target:
6802
      raise errors.OpExecError("Instance seems to be running on two nodes,"
6803
                               " or the hypervisor is confused; you will have"
6804
                               " to ensure manually that it runs only on one"
6805
                               " and restart this operation")
6806

    
6807
    if not (runningon_source or runningon_target):
6808
      raise errors.OpExecError("Instance does not seem to be running at all;"
6809
                               " in this case it's safer to repair by"
6810
                               " running 'gnt-instance stop' to ensure disk"
6811
                               " shutdown, and then restarting it")
6812

    
6813
    if runningon_target:
6814
      # the migration has actually succeeded, we need to update the config
6815
      self.feedback_fn("* instance running on secondary node (%s),"
6816
                       " updating config" % target_node)
6817
      instance.primary_node = target_node
6818
      self.cfg.Update(instance, self.feedback_fn)
6819
      demoted_node = source_node
6820
    else:
6821
      self.feedback_fn("* instance confirmed to be running on its"
6822
                       " primary node (%s)" % source_node)
6823
      demoted_node = target_node
6824

    
6825
    if instance.disk_template in constants.DTS_INT_MIRROR:
6826
      self._EnsureSecondary(demoted_node)
6827
      try:
6828
        self._WaitUntilSync()
6829
      except errors.OpExecError:
6830
        # we ignore here errors, since if the device is standalone, it
6831
        # won't be able to sync
6832
        pass
6833
      self._GoStandalone()
6834
      self._GoReconnect(False)
6835
      self._WaitUntilSync()
6836

    
6837
    self.feedback_fn("* done")
6838

    
6839
  def _RevertDiskStatus(self):
6840
    """Try to revert the disk status after a failed migration.
6841

6842
    """
6843
    target_node = self.target_node
6844
    if self.instance.disk_template in constants.DTS_EXT_MIRROR:
6845
      return
6846

    
6847
    try:
6848
      self._EnsureSecondary(target_node)
6849
      self._GoStandalone()
6850
      self._GoReconnect(False)
6851
      self._WaitUntilSync()
6852
    except errors.OpExecError, err:
6853
      self.lu.LogWarning("Migration failed and I can't reconnect the drives,"
6854
                         " please try to recover the instance manually;"
6855
                         " error '%s'" % str(err))
6856

    
6857
  def _AbortMigration(self):
6858
    """Call the hypervisor code to abort a started migration.
6859

6860
    """
6861
    instance = self.instance
6862
    target_node = self.target_node
6863
    migration_info = self.migration_info
6864

    
6865
    abort_result = self.rpc.call_finalize_migration(target_node,
6866
                                                    instance,
6867
                                                    migration_info,
6868
                                                    False)
6869
    abort_msg = abort_result.fail_msg
6870
    if abort_msg:
6871
      logging.error("Aborting migration failed on target node %s: %s",
6872
                    target_node, abort_msg)
6873
      # Don't raise an exception here, as we stil have to try to revert the
6874
      # disk status, even if this step failed.
6875

    
6876
  def _ExecMigration(self):
6877
    """Migrate an instance.
6878

6879
    The migrate is done by:
6880
      - change the disks into dual-master mode
6881
      - wait until disks are fully synchronized again
6882
      - migrate the instance
6883
      - change disks on the new secondary node (the old primary) to secondary
6884
      - wait until disks are fully synchronized
6885
      - change disks into single-master mode
6886

6887
    """
6888
    instance = self.instance
6889
    target_node = self.target_node
6890
    source_node = self.source_node
6891

    
6892
    self.feedback_fn("* checking disk consistency between source and target")
6893
    for dev in instance.disks:
6894
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6895
        raise errors.OpExecError("Disk %s is degraded or not fully"
6896
                                 " synchronized on target node,"
6897
                                 " aborting migration" % dev.iv_name)
6898

    
6899
    # First get the migration information from the remote node
6900
    result = self.rpc.call_migration_info(source_node, instance)
6901
    msg = result.fail_msg
6902
    if msg:
6903
      log_err = ("Failed fetching source migration information from %s: %s" %
6904
                 (source_node, msg))
6905
      logging.error(log_err)
6906
      raise errors.OpExecError(log_err)
6907

    
6908
    self.migration_info = migration_info = result.payload
6909

    
6910
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6911
      # Then switch the disks to master/master mode
6912
      self._EnsureSecondary(target_node)
6913
      self._GoStandalone()
6914
      self._GoReconnect(True)
6915
      self._WaitUntilSync()
6916

    
6917
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6918
    result = self.rpc.call_accept_instance(target_node,
6919
                                           instance,
6920
                                           migration_info,
6921
                                           self.nodes_ip[target_node])
6922

    
6923
    msg = result.fail_msg
6924
    if msg:
6925
      logging.error("Instance pre-migration failed, trying to revert"
6926
                    " disk status: %s", msg)
6927
      self.feedback_fn("Pre-migration failed, aborting")
6928
      self._AbortMigration()
6929
      self._RevertDiskStatus()
6930
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6931
                               (instance.name, msg))
6932

    
6933
    self.feedback_fn("* migrating instance to %s" % target_node)
6934
    result = self.rpc.call_instance_migrate(source_node, instance,
6935
                                            self.nodes_ip[target_node],
6936
                                            self.live)
6937
    msg = result.fail_msg
6938
    if msg:
6939
      logging.error("Instance migration failed, trying to revert"
6940
                    " disk status: %s", msg)
6941
      self.feedback_fn("Migration failed, aborting")
6942
      self._AbortMigration()
6943
      self._RevertDiskStatus()
6944
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6945
                               (instance.name, msg))
6946

    
6947
    instance.primary_node = target_node
6948
    # distribute new instance config to the other nodes
6949
    self.cfg.Update(instance, self.feedback_fn)
6950

    
6951
    result = self.rpc.call_finalize_migration(target_node,
6952
                                              instance,
6953
                                              migration_info,
6954
                                              True)
6955
    msg = result.fail_msg
6956
    if msg:
6957
      logging.error("Instance migration succeeded, but finalization failed:"
6958
                    " %s", msg)
6959
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6960
                               msg)
6961

    
6962
    if self.instance.disk_template not in constants.DTS_EXT_MIRROR:
6963
      self._EnsureSecondary(source_node)
6964
      self._WaitUntilSync()
6965
      self._GoStandalone()
6966
      self._GoReconnect(False)
6967
      self._WaitUntilSync()
6968

    
6969
    self.feedback_fn("* done")
6970

    
6971
  def _ExecFailover(self):
6972
    """Failover an instance.
6973

6974
    The failover is done by shutting it down on its present node and
6975
    starting it on the secondary.
6976

6977
    """
6978
    instance = self.instance
6979
    primary_node = self.cfg.GetNodeInfo(instance.primary_node)
6980

    
6981
    source_node = instance.primary_node
6982
    target_node = self.target_node
6983

    
6984
    if instance.admin_up:
6985
      self.feedback_fn("* checking disk consistency between source and target")
6986
      for dev in instance.disks:
6987
        # for drbd, these are drbd over lvm
6988
        if not _CheckDiskConsistency(self, dev, target_node, False):
6989
          if not self.ignore_consistency:
6990
            raise errors.OpExecError("Disk %s is degraded on target node,"
6991
                                     " aborting failover" % dev.iv_name)
6992
    else:
6993
      self.feedback_fn("* not checking disk consistency as instance is not"
6994
                       " running")
6995

    
6996
    self.feedback_fn("* shutting down instance on source node")
6997
    logging.info("Shutting down instance %s on node %s",
6998
                 instance.name, source_node)
6999

    
7000
    result = self.rpc.call_instance_shutdown(source_node, instance,
7001
                                             self.shutdown_timeout)
7002
    msg = result.fail_msg
7003
    if msg:
7004
      if self.ignore_consistency or primary_node.offline:
7005
        self.lu.LogWarning("Could not shutdown instance %s on node %s,"
7006
                           " proceeding anyway; please make sure node"
7007
                           " %s is down; error details: %s",
7008
                           instance.name, source_node, source_node, msg)
7009
      else:
7010
        raise errors.OpExecError("Could not shutdown instance %s on"
7011
                                 " node %s: %s" %
7012
                                 (instance.name, source_node, msg))
7013

    
7014
    self.feedback_fn("* deactivating the instance's disks on source node")
7015
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
7016
      raise errors.OpExecError("Can't shut down the instance's disks.")
7017

    
7018
    instance.primary_node = target_node
7019
    # distribute new instance config to the other nodes
7020
    self.cfg.Update(instance, self.feedback_fn)
7021

    
7022
    # Only start the instance if it's marked as up
7023
    if instance.admin_up:
7024
      self.feedback_fn("* activating the instance's disks on target node")
7025
      logging.info("Starting instance %s on node %s",
7026
                   instance.name, target_node)
7027

    
7028
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
7029
                                           ignore_secondaries=True)
7030
      if not disks_ok:
7031
        _ShutdownInstanceDisks(self, instance)
7032
        raise errors.OpExecError("Can't activate the instance's disks")
7033

    
7034
      self.feedback_fn("* starting the instance on the target node")
7035
      result = self.rpc.call_instance_start(target_node, instance, None, None)
7036
      msg = result.fail_msg
7037
      if msg:
7038
        _ShutdownInstanceDisks(self, instance)
7039
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
7040
                                 (instance.name, target_node, msg))
7041

    
7042
  def Exec(self, feedback_fn):
7043
    """Perform the migration.
7044

7045
    """
7046
    self.feedback_fn = feedback_fn
7047
    self.source_node = self.instance.primary_node
7048

    
7049
    # FIXME: if we implement migrate-to-any in DRBD, this needs fixing
7050
    if self.instance.disk_template in constants.DTS_INT_MIRROR:
7051
      self.target_node = self.instance.secondary_nodes[0]
7052
      # Otherwise self.target_node has been populated either
7053
      # directly, or through an iallocator.
7054

    
7055
    self.all_nodes = [self.source_node, self.target_node]
7056
    self.nodes_ip = {
7057
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
7058
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
7059
      }
7060

    
7061
    if self.failover:
7062
      feedback_fn("Failover instance %s" % self.instance.name)
7063
      self._ExecFailover()
7064
    else:
7065
      feedback_fn("Migrating instance %s" % self.instance.name)
7066

    
7067
      if self.cleanup:
7068
        return self._ExecCleanup()
7069
      else:
7070
        return self._ExecMigration()
7071

    
7072

    
7073
def _CreateBlockDev(lu, node, instance, device, force_create,
7074
                    info, force_open):
7075
  """Create a tree of block devices on a given node.
7076

7077
  If this device type has to be created on secondaries, create it and
7078
  all its children.
7079

7080
  If not, just recurse to children keeping the same 'force' value.
7081

7082
  @param lu: the lu on whose behalf we execute
7083
  @param node: the node on which to create the device
7084
  @type instance: L{objects.Instance}
7085
  @param instance: the instance which owns the device
7086
  @type device: L{objects.Disk}
7087
  @param device: the device to create
7088
  @type force_create: boolean
7089
  @param force_create: whether to force creation of this device; this
7090
      will be change to True whenever we find a device which has
7091
      CreateOnSecondary() attribute
7092
  @param info: the extra 'metadata' we should attach to the device
7093
      (this will be represented as a LVM tag)
7094
  @type force_open: boolean
7095
  @param force_open: this parameter will be passes to the
7096
      L{backend.BlockdevCreate} function where it specifies
7097
      whether we run on primary or not, and it affects both
7098
      the child assembly and the device own Open() execution
7099

7100
  """
7101
  if device.CreateOnSecondary():
7102
    force_create = True
7103

    
7104
  if device.children:
7105
    for child in device.children:
7106
      _CreateBlockDev(lu, node, instance, child, force_create,
7107
                      info, force_open)
7108

    
7109
  if not force_create:
7110
    return
7111

    
7112
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
7113

    
7114

    
7115
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
7116
  """Create a single block device on a given node.
7117

7118
  This will not recurse over children of the device, so they must be
7119
  created in advance.
7120

7121
  @param lu: the lu on whose behalf we execute
7122
  @param node: the node on which to create the device
7123
  @type instance: L{objects.Instance}
7124
  @param instance: the instance which owns the device
7125
  @type device: L{objects.Disk}
7126
  @param device: the device to create
7127
  @param info: the extra 'metadata' we should attach to the device
7128
      (this will be represented as a LVM tag)
7129
  @type force_open: boolean
7130
  @param force_open: this parameter will be passes to the
7131
      L{backend.BlockdevCreate} function where it specifies
7132
      whether we run on primary or not, and it affects both
7133
      the child assembly and the device own Open() execution
7134

7135
  """
7136
  lu.cfg.SetDiskID(device, node)
7137
  result = lu.rpc.call_blockdev_create(node, device, device.size,
7138
                                       instance.name, force_open, info)
7139
  result.Raise("Can't create block device %s on"
7140
               " node %s for instance %s" % (device, node, instance.name))
7141
  if device.physical_id is None:
7142
    device.physical_id = result.payload
7143

    
7144

    
7145
def _GenerateUniqueNames(lu, exts):
7146
  """Generate a suitable LV name.
7147

7148
  This will generate a logical volume name for the given instance.
7149

7150
  """
7151
  results = []
7152
  for val in exts:
7153
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
7154
    results.append("%s%s" % (new_id, val))
7155
  return results
7156

    
7157

    
7158
def _GenerateDRBD8Branch(lu, primary, secondary, size, vgnames, names,
7159
                         iv_name, p_minor, s_minor):
7160
  """Generate a drbd8 device complete with its children.
7161

7162
  """
7163
  assert len(vgnames) == len(names) == 2
7164
  port = lu.cfg.AllocatePort()
7165
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
7166
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
7167
                          logical_id=(vgnames[0], names[0]))
7168
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7169
                          logical_id=(vgnames[1], names[1]))
7170
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
7171
                          logical_id=(primary, secondary, port,
7172
                                      p_minor, s_minor,
7173
                                      shared_secret),
7174
                          children=[dev_data, dev_meta],
7175
                          iv_name=iv_name)
7176
  return drbd_dev
7177

    
7178

    
7179
def _GenerateDiskTemplate(lu, template_name,
7180
                          instance_name, primary_node,
7181
                          secondary_nodes, disk_info,
7182
                          file_storage_dir, file_driver,
7183
                          base_index, feedback_fn):
7184
  """Generate the entire disk layout for a given template type.
7185

7186
  """
7187
  #TODO: compute space requirements
7188

    
7189
  vgname = lu.cfg.GetVGName()
7190
  disk_count = len(disk_info)
7191
  disks = []
7192
  if template_name == constants.DT_DISKLESS:
7193
    pass
7194
  elif template_name == constants.DT_PLAIN:
7195
    if len(secondary_nodes) != 0:
7196
      raise errors.ProgrammerError("Wrong template configuration")
7197

    
7198
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7199
                                      for i in range(disk_count)])
7200
    for idx, disk in enumerate(disk_info):
7201
      disk_index = idx + base_index
7202
      vg = disk.get(constants.IDISK_VG, vgname)
7203
      feedback_fn("* disk %i, vg %s, name %s" % (idx, vg, names[idx]))
7204
      disk_dev = objects.Disk(dev_type=constants.LD_LV,
7205
                              size=disk[constants.IDISK_SIZE],
7206
                              logical_id=(vg, names[idx]),
7207
                              iv_name="disk/%d" % disk_index,
7208
                              mode=disk[constants.IDISK_MODE])
7209
      disks.append(disk_dev)
7210
  elif template_name == constants.DT_DRBD8:
7211
    if len(secondary_nodes) != 1:
7212
      raise errors.ProgrammerError("Wrong template configuration")
7213
    remote_node = secondary_nodes[0]
7214
    minors = lu.cfg.AllocateDRBDMinor(
7215
      [primary_node, remote_node] * len(disk_info), instance_name)
7216

    
7217
    names = []
7218
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
7219
                                               for i in range(disk_count)]):
7220
      names.append(lv_prefix + "_data")
7221
      names.append(lv_prefix + "_meta")
7222
    for idx, disk in enumerate(disk_info):
7223
      disk_index = idx + base_index
7224
      data_vg = disk.get(constants.IDISK_VG, vgname)
7225
      meta_vg = disk.get(constants.IDISK_METAVG, data_vg)
7226
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
7227
                                      disk[constants.IDISK_SIZE],
7228
                                      [data_vg, meta_vg],
7229
                                      names[idx * 2:idx * 2 + 2],
7230
                                      "disk/%d" % disk_index,
7231
                                      minors[idx * 2], minors[idx * 2 + 1])
7232
      disk_dev.mode = disk[constants.IDISK_MODE]
7233
      disks.append(disk_dev)
7234
  elif template_name == constants.DT_FILE:
7235
    if len(secondary_nodes) != 0:
7236
      raise errors.ProgrammerError("Wrong template configuration")
7237

    
7238
    opcodes.RequireFileStorage()
7239

    
7240
    for idx, disk in enumerate(disk_info):
7241
      disk_index = idx + base_index
7242
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7243
                              size=disk[constants.IDISK_SIZE],
7244
                              iv_name="disk/%d" % disk_index,
7245
                              logical_id=(file_driver,
7246
                                          "%s/disk%d" % (file_storage_dir,
7247
                                                         disk_index)),
7248
                              mode=disk[constants.IDISK_MODE])
7249
      disks.append(disk_dev)
7250
  elif template_name == constants.DT_SHARED_FILE:
7251
    if len(secondary_nodes) != 0:
7252
      raise errors.ProgrammerError("Wrong template configuration")
7253

    
7254
    opcodes.RequireSharedFileStorage()
7255

    
7256
    for idx, disk in enumerate(disk_info):
7257
      disk_index = idx + base_index
7258
      disk_dev = objects.Disk(dev_type=constants.LD_FILE,
7259
                              size=disk[constants.IDISK_SIZE],
7260
                              iv_name="disk/%d" % disk_index,
7261
                              logical_id=(file_driver,
7262
                                          "%s/disk%d" % (file_storage_dir,
7263
                                                         disk_index)),
7264
                              mode=disk[constants.IDISK_MODE])
7265
      disks.append(disk_dev)
7266
  elif template_name == constants.DT_BLOCK:
7267
    if len(secondary_nodes) != 0:
7268
      raise errors.ProgrammerError("Wrong template configuration")
7269

    
7270
    for idx, disk in enumerate(disk_info):
7271
      disk_index = idx + base_index
7272
      disk_dev = objects.Disk(dev_type=constants.LD_BLOCKDEV,
7273
                              size=disk[constants.IDISK_SIZE],
7274
                              logical_id=(constants.BLOCKDEV_DRIVER_MANUAL,
7275
                                          disk[constants.IDISK_ADOPT]),
7276
                              iv_name="disk/%d" % disk_index,
7277
                              mode=disk[constants.IDISK_MODE])
7278
      disks.append(disk_dev)
7279

    
7280
  else:
7281
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
7282
  return disks
7283

    
7284

    
7285
def _GetInstanceInfoText(instance):
7286
  """Compute that text that should be added to the disk's metadata.
7287

7288
  """
7289
  return "originstname+%s" % instance.name
7290

    
7291

    
7292
def _CalcEta(time_taken, written, total_size):
7293
  """Calculates the ETA based on size written and total size.
7294

7295
  @param time_taken: The time taken so far
7296
  @param written: amount written so far
7297
  @param total_size: The total size of data to be written
7298
  @return: The remaining time in seconds
7299

7300
  """
7301
  avg_time = time_taken / float(written)
7302
  return (total_size - written) * avg_time
7303

    
7304

    
7305
def _WipeDisks(lu, instance):
7306
  """Wipes instance disks.
7307

7308
  @type lu: L{LogicalUnit}
7309
  @param lu: the logical unit on whose behalf we execute
7310
  @type instance: L{objects.Instance}
7311
  @param instance: the instance whose disks we should create
7312
  @return: the success of the wipe
7313

7314
  """
7315
  node = instance.primary_node
7316

    
7317
  for device in instance.disks:
7318
    lu.cfg.SetDiskID(device, node)
7319

    
7320
  logging.info("Pause sync of instance %s disks", instance.name)
7321
  result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, True)
7322

    
7323
  for idx, success in enumerate(result.payload):
7324
    if not success:
7325
      logging.warn("pause-sync of instance %s for disks %d failed",
7326
                   instance.name, idx)
7327

    
7328
  try:
7329
    for idx, device in enumerate(instance.disks):
7330
      # The wipe size is MIN_WIPE_CHUNK_PERCENT % of the instance disk but
7331
      # MAX_WIPE_CHUNK at max
7332
      wipe_chunk_size = min(constants.MAX_WIPE_CHUNK, device.size / 100.0 *
7333
                            constants.MIN_WIPE_CHUNK_PERCENT)
7334
      # we _must_ make this an int, otherwise rounding errors will
7335
      # occur
7336
      wipe_chunk_size = int(wipe_chunk_size)
7337

    
7338
      lu.LogInfo("* Wiping disk %d", idx)
7339
      logging.info("Wiping disk %d for instance %s, node %s using"
7340
                   " chunk size %s", idx, instance.name, node, wipe_chunk_size)
7341

    
7342
      offset = 0
7343
      size = device.size
7344
      last_output = 0
7345
      start_time = time.time()
7346

    
7347
      while offset < size:
7348
        wipe_size = min(wipe_chunk_size, size - offset)
7349
        logging.debug("Wiping disk %d, offset %s, chunk %s",
7350
                      idx, offset, wipe_size)
7351
        result = lu.rpc.call_blockdev_wipe(node, device, offset, wipe_size)
7352
        result.Raise("Could not wipe disk %d at offset %d for size %d" %
7353
                     (idx, offset, wipe_size))
7354
        now = time.time()
7355
        offset += wipe_size
7356
        if now - last_output >= 60:
7357
          eta = _CalcEta(now - start_time, offset, size)
7358
          lu.LogInfo(" - done: %.1f%% ETA: %s" %
7359
                     (offset / float(size) * 100, utils.FormatSeconds(eta)))
7360
          last_output = now
7361
  finally:
7362
    logging.info("Resume sync of instance %s disks", instance.name)
7363

    
7364
    result = lu.rpc.call_blockdev_pause_resume_sync(node, instance.disks, False)
7365

    
7366
    for idx, success in enumerate(result.payload):
7367
      if not success:
7368
        lu.LogWarning("Resume sync of disk %d failed, please have a"
7369
                      " look at the status and troubleshoot the issue", idx)
7370
        logging.warn("resume-sync of instance %s for disks %d failed",
7371
                     instance.name, idx)
7372

    
7373

    
7374
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
7375
  """Create all disks for an instance.
7376

7377
  This abstracts away some work from AddInstance.
7378

7379
  @type lu: L{LogicalUnit}
7380
  @param lu: the logical unit on whose behalf we execute
7381
  @type instance: L{objects.Instance}
7382
  @param instance: the instance whose disks we should create
7383
  @type to_skip: list
7384
  @param to_skip: list of indices to skip
7385
  @type target_node: string
7386
  @param target_node: if passed, overrides the target node for creation
7387
  @rtype: boolean
7388
  @return: the success of the creation
7389

7390
  """
7391
  info = _GetInstanceInfoText(instance)
7392
  if target_node is None:
7393
    pnode = instance.primary_node
7394
    all_nodes = instance.all_nodes
7395
  else:
7396
    pnode = target_node
7397
    all_nodes = [pnode]
7398

    
7399
  if instance.disk_template in (constants.DT_FILE, constants.DT_SHARED_FILE):
7400
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7401
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
7402

    
7403
    result.Raise("Failed to create directory '%s' on"
7404
                 " node %s" % (file_storage_dir, pnode))
7405

    
7406
  # Note: this needs to be kept in sync with adding of disks in
7407
  # LUInstanceSetParams
7408
  for idx, device in enumerate(instance.disks):
7409
    if to_skip and idx in to_skip:
7410
      continue
7411
    logging.info("Creating volume %s for instance %s",
7412
                 device.iv_name, instance.name)
7413
    #HARDCODE
7414
    for node in all_nodes:
7415
      f_create = node == pnode
7416
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
7417

    
7418

    
7419
def _RemoveDisks(lu, instance, target_node=None):
7420
  """Remove all disks for an instance.
7421

7422
  This abstracts away some work from `AddInstance()` and
7423
  `RemoveInstance()`. Note that in case some of the devices couldn't
7424
  be removed, the removal will continue with the other ones (compare
7425
  with `_CreateDisks()`).
7426

7427
  @type lu: L{LogicalUnit}
7428
  @param lu: the logical unit on whose behalf we execute
7429
  @type instance: L{objects.Instance}
7430
  @param instance: the instance whose disks we should remove
7431
  @type target_node: string
7432
  @param target_node: used to override the node on which to remove the disks
7433
  @rtype: boolean
7434
  @return: the success of the removal
7435

7436
  """
7437
  logging.info("Removing block devices for instance %s", instance.name)
7438

    
7439
  all_result = True
7440
  for device in instance.disks:
7441
    if target_node:
7442
      edata = [(target_node, device)]
7443
    else:
7444
      edata = device.ComputeNodeTree(instance.primary_node)
7445
    for node, disk in edata:
7446
      lu.cfg.SetDiskID(disk, node)
7447
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
7448
      if msg:
7449
        lu.LogWarning("Could not remove block device %s on node %s,"
7450
                      " continuing anyway: %s", device.iv_name, node, msg)
7451
        all_result = False
7452

    
7453
  if instance.disk_template == constants.DT_FILE:
7454
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
7455
    if target_node:
7456
      tgt = target_node
7457
    else:
7458
      tgt = instance.primary_node
7459
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
7460
    if result.fail_msg:
7461
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
7462
                    file_storage_dir, instance.primary_node, result.fail_msg)
7463
      all_result = False
7464

    
7465
  return all_result
7466

    
7467

    
7468
def _ComputeDiskSizePerVG(disk_template, disks):
7469
  """Compute disk size requirements in the volume group
7470

7471
  """
7472
  def _compute(disks, payload):
7473
    """Universal algorithm.
7474

7475
    """
7476
    vgs = {}
7477
    for disk in disks:
7478
      vgs[disk[constants.IDISK_VG]] = \
7479
        vgs.get(constants.IDISK_VG, 0) + disk[constants.IDISK_SIZE] + payload
7480

    
7481
    return vgs
7482

    
7483
  # Required free disk space as a function of disk and swap space
7484
  req_size_dict = {
7485
    constants.DT_DISKLESS: {},
7486
    constants.DT_PLAIN: _compute(disks, 0),
7487
    # 128 MB are added for drbd metadata for each disk
7488
    constants.DT_DRBD8: _compute(disks, 128),
7489
    constants.DT_FILE: {},
7490
    constants.DT_SHARED_FILE: {},
7491
  }
7492

    
7493
  if disk_template not in req_size_dict:
7494
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7495
                                 " is unknown" %  disk_template)
7496

    
7497
  return req_size_dict[disk_template]
7498

    
7499

    
7500
def _ComputeDiskSize(disk_template, disks):
7501
  """Compute disk size requirements in the volume group
7502

7503
  """
7504
  # Required free disk space as a function of disk and swap space
7505
  req_size_dict = {
7506
    constants.DT_DISKLESS: None,
7507
    constants.DT_PLAIN: sum(d[constants.IDISK_SIZE] for d in disks),
7508
    # 128 MB are added for drbd metadata for each disk
7509
    constants.DT_DRBD8: sum(d[constants.IDISK_SIZE] + 128 for d in disks),
7510
    constants.DT_FILE: None,
7511
    constants.DT_SHARED_FILE: 0,
7512
    constants.DT_BLOCK: 0,
7513
  }
7514

    
7515
  if disk_template not in req_size_dict:
7516
    raise errors.ProgrammerError("Disk template '%s' size requirement"
7517
                                 " is unknown" %  disk_template)
7518

    
7519
  return req_size_dict[disk_template]
7520

    
7521

    
7522
def _FilterVmNodes(lu, nodenames):
7523
  """Filters out non-vm_capable nodes from a list.
7524

7525
  @type lu: L{LogicalUnit}
7526
  @param lu: the logical unit for which we check
7527
  @type nodenames: list
7528
  @param nodenames: the list of nodes on which we should check
7529
  @rtype: list
7530
  @return: the list of vm-capable nodes
7531

7532
  """
7533
  vm_nodes = frozenset(lu.cfg.GetNonVmCapableNodeList())
7534
  return [name for name in nodenames if name not in vm_nodes]
7535

    
7536

    
7537
def _CheckHVParams(lu, nodenames, hvname, hvparams):
7538
  """Hypervisor parameter validation.
7539

7540
  This function abstract the hypervisor parameter validation to be
7541
  used in both instance create and instance modify.
7542

7543
  @type lu: L{LogicalUnit}
7544
  @param lu: the logical unit for which we check
7545
  @type nodenames: list
7546
  @param nodenames: the list of nodes on which we should check
7547
  @type hvname: string
7548
  @param hvname: the name of the hypervisor we should use
7549
  @type hvparams: dict
7550
  @param hvparams: the parameters which we need to check
7551
  @raise errors.OpPrereqError: if the parameters are not valid
7552

7553
  """
7554
  nodenames = _FilterVmNodes(lu, nodenames)
7555
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
7556
                                                  hvname,
7557
                                                  hvparams)
7558
  for node in nodenames:
7559
    info = hvinfo[node]
7560
    if info.offline:
7561
      continue
7562
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
7563

    
7564

    
7565
def _CheckOSParams(lu, required, nodenames, osname, osparams):
7566
  """OS parameters validation.
7567

7568
  @type lu: L{LogicalUnit}
7569
  @param lu: the logical unit for which we check
7570
  @type required: boolean
7571
  @param required: whether the validation should fail if the OS is not
7572
      found
7573
  @type nodenames: list
7574
  @param nodenames: the list of nodes on which we should check
7575
  @type osname: string
7576
  @param osname: the name of the hypervisor we should use
7577
  @type osparams: dict
7578
  @param osparams: the parameters which we need to check
7579
  @raise errors.OpPrereqError: if the parameters are not valid
7580

7581
  """
7582
  nodenames = _FilterVmNodes(lu, nodenames)
7583
  result = lu.rpc.call_os_validate(required, nodenames, osname,
7584
                                   [constants.OS_VALIDATE_PARAMETERS],
7585
                                   osparams)
7586
  for node, nres in result.items():
7587
    # we don't check for offline cases since this should be run only
7588
    # against the master node and/or an instance's nodes
7589
    nres.Raise("OS Parameters validation failed on node %s" % node)
7590
    if not nres.payload:
7591
      lu.LogInfo("OS %s not found on node %s, validation skipped",
7592
                 osname, node)
7593

    
7594

    
7595
class LUInstanceCreate(LogicalUnit):
7596
  """Create an instance.
7597

7598
  """
7599
  HPATH = "instance-add"
7600
  HTYPE = constants.HTYPE_INSTANCE
7601
  REQ_BGL = False
7602

    
7603
  def CheckArguments(self):
7604
    """Check arguments.
7605

7606
    """
7607
    # do not require name_check to ease forward/backward compatibility
7608
    # for tools
7609
    if self.op.no_install and self.op.start:
7610
      self.LogInfo("No-installation mode selected, disabling startup")
7611
      self.op.start = False
7612
    # validate/normalize the instance name
7613
    self.op.instance_name = \
7614
      netutils.Hostname.GetNormalizedName(self.op.instance_name)
7615

    
7616
    if self.op.ip_check and not self.op.name_check:
7617
      # TODO: make the ip check more flexible and not depend on the name check
7618
      raise errors.OpPrereqError("Cannot do IP address check without a name"
7619
                                 " check", errors.ECODE_INVAL)
7620

    
7621
    # check nics' parameter names
7622
    for nic in self.op.nics:
7623
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
7624

    
7625
    # check disks. parameter names and consistent adopt/no-adopt strategy
7626
    has_adopt = has_no_adopt = False
7627
    for disk in self.op.disks:
7628
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
7629
      if constants.IDISK_ADOPT in disk:
7630
        has_adopt = True
7631
      else:
7632
        has_no_adopt = True
7633
    if has_adopt and has_no_adopt:
7634
      raise errors.OpPrereqError("Either all disks are adopted or none is",
7635
                                 errors.ECODE_INVAL)
7636
    if has_adopt:
7637
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
7638
        raise errors.OpPrereqError("Disk adoption is not supported for the"
7639
                                   " '%s' disk template" %
7640
                                   self.op.disk_template,
7641
                                   errors.ECODE_INVAL)
7642
      if self.op.iallocator is not None:
7643
        raise errors.OpPrereqError("Disk adoption not allowed with an"
7644
                                   " iallocator script", errors.ECODE_INVAL)
7645
      if self.op.mode == constants.INSTANCE_IMPORT:
7646
        raise errors.OpPrereqError("Disk adoption not allowed for"
7647
                                   " instance import", errors.ECODE_INVAL)
7648
    else:
7649
      if self.op.disk_template in constants.DTS_MUST_ADOPT:
7650
        raise errors.OpPrereqError("Disk template %s requires disk adoption,"
7651
                                   " but no 'adopt' parameter given" %
7652
                                   self.op.disk_template,
7653
                                   errors.ECODE_INVAL)
7654

    
7655
    self.adopt_disks = has_adopt
7656

    
7657
    # instance name verification
7658
    if self.op.name_check:
7659
      self.hostname1 = netutils.GetHostname(name=self.op.instance_name)
7660
      self.op.instance_name = self.hostname1.name
7661
      # used in CheckPrereq for ip ping check
7662
      self.check_ip = self.hostname1.ip
7663
    else:
7664
      self.check_ip = None
7665

    
7666
    # file storage checks
7667
    if (self.op.file_driver and
7668
        not self.op.file_driver in constants.FILE_DRIVER):
7669
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
7670
                                 self.op.file_driver, errors.ECODE_INVAL)
7671

    
7672
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
7673
      raise errors.OpPrereqError("File storage directory path not absolute",
7674
                                 errors.ECODE_INVAL)
7675

    
7676
    ### Node/iallocator related checks
7677
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
7678

    
7679
    if self.op.pnode is not None:
7680
      if self.op.disk_template in constants.DTS_INT_MIRROR:
7681
        if self.op.snode is None:
7682
          raise errors.OpPrereqError("The networked disk templates need"
7683
                                     " a mirror node", errors.ECODE_INVAL)
7684
      elif self.op.snode:
7685
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
7686
                        " template")
7687
        self.op.snode = None
7688

    
7689
    self._cds = _GetClusterDomainSecret()
7690

    
7691
    if self.op.mode == constants.INSTANCE_IMPORT:
7692
      # On import force_variant must be True, because if we forced it at
7693
      # initial install, our only chance when importing it back is that it
7694
      # works again!
7695
      self.op.force_variant = True
7696

    
7697
      if self.op.no_install:
7698
        self.LogInfo("No-installation mode has no effect during import")
7699

    
7700
    elif self.op.mode == constants.INSTANCE_CREATE:
7701
      if self.op.os_type is None:
7702
        raise errors.OpPrereqError("No guest OS specified",
7703
                                   errors.ECODE_INVAL)
7704
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_os:
7705
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
7706
                                   " installation" % self.op.os_type,
7707
                                   errors.ECODE_STATE)
7708
      if self.op.disk_template is None:
7709
        raise errors.OpPrereqError("No disk template specified",
7710
                                   errors.ECODE_INVAL)
7711

    
7712
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7713
      # Check handshake to ensure both clusters have the same domain secret
7714
      src_handshake = self.op.source_handshake
7715
      if not src_handshake:
7716
        raise errors.OpPrereqError("Missing source handshake",
7717
                                   errors.ECODE_INVAL)
7718

    
7719
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
7720
                                                           src_handshake)
7721
      if errmsg:
7722
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
7723
                                   errors.ECODE_INVAL)
7724

    
7725
      # Load and check source CA
7726
      self.source_x509_ca_pem = self.op.source_x509_ca
7727
      if not self.source_x509_ca_pem:
7728
        raise errors.OpPrereqError("Missing source X509 CA",
7729
                                   errors.ECODE_INVAL)
7730

    
7731
      try:
7732
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
7733
                                                    self._cds)
7734
      except OpenSSL.crypto.Error, err:
7735
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
7736
                                   (err, ), errors.ECODE_INVAL)
7737

    
7738
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
7739
      if errcode is not None:
7740
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
7741
                                   errors.ECODE_INVAL)
7742

    
7743
      self.source_x509_ca = cert
7744

    
7745
      src_instance_name = self.op.source_instance_name
7746
      if not src_instance_name:
7747
        raise errors.OpPrereqError("Missing source instance name",
7748
                                   errors.ECODE_INVAL)
7749

    
7750
      self.source_instance_name = \
7751
          netutils.GetHostname(name=src_instance_name).name
7752

    
7753
    else:
7754
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
7755
                                 self.op.mode, errors.ECODE_INVAL)
7756

    
7757
  def ExpandNames(self):
7758
    """ExpandNames for CreateInstance.
7759

7760
    Figure out the right locks for instance creation.
7761

7762
    """
7763
    self.needed_locks = {}
7764

    
7765
    instance_name = self.op.instance_name
7766
    # this is just a preventive check, but someone might still add this
7767
    # instance in the meantime, and creation will fail at lock-add time
7768
    if instance_name in self.cfg.GetInstanceList():
7769
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
7770
                                 instance_name, errors.ECODE_EXISTS)
7771

    
7772
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
7773

    
7774
    if self.op.iallocator:
7775
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7776
    else:
7777
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
7778
      nodelist = [self.op.pnode]
7779
      if self.op.snode is not None:
7780
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
7781
        nodelist.append(self.op.snode)
7782
      self.needed_locks[locking.LEVEL_NODE] = nodelist
7783

    
7784
    # in case of import lock the source node too
7785
    if self.op.mode == constants.INSTANCE_IMPORT:
7786
      src_node = self.op.src_node
7787
      src_path = self.op.src_path
7788

    
7789
      if src_path is None:
7790
        self.op.src_path = src_path = self.op.instance_name
7791

    
7792
      if src_node is None:
7793
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7794
        self.op.src_node = None
7795
        if os.path.isabs(src_path):
7796
          raise errors.OpPrereqError("Importing an instance from an absolute"
7797
                                     " path requires a source node option",
7798
                                     errors.ECODE_INVAL)
7799
      else:
7800
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
7801
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
7802
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
7803
        if not os.path.isabs(src_path):
7804
          self.op.src_path = src_path = \
7805
            utils.PathJoin(constants.EXPORT_DIR, src_path)
7806

    
7807
  def _RunAllocator(self):
7808
    """Run the allocator based on input opcode.
7809

7810
    """
7811
    nics = [n.ToDict() for n in self.nics]
7812
    ial = IAllocator(self.cfg, self.rpc,
7813
                     mode=constants.IALLOCATOR_MODE_ALLOC,
7814
                     name=self.op.instance_name,
7815
                     disk_template=self.op.disk_template,
7816
                     tags=[],
7817
                     os=self.op.os_type,
7818
                     vcpus=self.be_full[constants.BE_VCPUS],
7819
                     mem_size=self.be_full[constants.BE_MEMORY],
7820
                     disks=self.disks,
7821
                     nics=nics,
7822
                     hypervisor=self.op.hypervisor,
7823
                     )
7824

    
7825
    ial.Run(self.op.iallocator)
7826

    
7827
    if not ial.success:
7828
      raise errors.OpPrereqError("Can't compute nodes using"
7829
                                 " iallocator '%s': %s" %
7830
                                 (self.op.iallocator, ial.info),
7831
                                 errors.ECODE_NORES)
7832
    if len(ial.result) != ial.required_nodes:
7833
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7834
                                 " of nodes (%s), required %s" %
7835
                                 (self.op.iallocator, len(ial.result),
7836
                                  ial.required_nodes), errors.ECODE_FAULT)
7837
    self.op.pnode = ial.result[0]
7838
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
7839
                 self.op.instance_name, self.op.iallocator,
7840
                 utils.CommaJoin(ial.result))
7841
    if ial.required_nodes == 2:
7842
      self.op.snode = ial.result[1]
7843

    
7844
  def BuildHooksEnv(self):
7845
    """Build hooks env.
7846

7847
    This runs on master, primary and secondary nodes of the instance.
7848

7849
    """
7850
    env = {
7851
      "ADD_MODE": self.op.mode,
7852
      }
7853
    if self.op.mode == constants.INSTANCE_IMPORT:
7854
      env["SRC_NODE"] = self.op.src_node
7855
      env["SRC_PATH"] = self.op.src_path
7856
      env["SRC_IMAGES"] = self.src_images
7857

    
7858
    env.update(_BuildInstanceHookEnv(
7859
      name=self.op.instance_name,
7860
      primary_node=self.op.pnode,
7861
      secondary_nodes=self.secondaries,
7862
      status=self.op.start,
7863
      os_type=self.op.os_type,
7864
      memory=self.be_full[constants.BE_MEMORY],
7865
      vcpus=self.be_full[constants.BE_VCPUS],
7866
      nics=_NICListToTuple(self, self.nics),
7867
      disk_template=self.op.disk_template,
7868
      disks=[(d[constants.IDISK_SIZE], d[constants.IDISK_MODE])
7869
             for d in self.disks],
7870
      bep=self.be_full,
7871
      hvp=self.hv_full,
7872
      hypervisor_name=self.op.hypervisor,
7873
    ))
7874

    
7875
    return env
7876

    
7877
  def BuildHooksNodes(self):
7878
    """Build hooks nodes.
7879

7880
    """
7881
    nl = [self.cfg.GetMasterNode(), self.op.pnode] + self.secondaries
7882
    return nl, nl
7883

    
7884
  def _ReadExportInfo(self):
7885
    """Reads the export information from disk.
7886

7887
    It will override the opcode source node and path with the actual
7888
    information, if these two were not specified before.
7889

7890
    @return: the export information
7891

7892
    """
7893
    assert self.op.mode == constants.INSTANCE_IMPORT
7894

    
7895
    src_node = self.op.src_node
7896
    src_path = self.op.src_path
7897

    
7898
    if src_node is None:
7899
      locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
7900
      exp_list = self.rpc.call_export_list(locked_nodes)
7901
      found = False
7902
      for node in exp_list:
7903
        if exp_list[node].fail_msg:
7904
          continue
7905
        if src_path in exp_list[node].payload:
7906
          found = True
7907
          self.op.src_node = src_node = node
7908
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
7909
                                                       src_path)
7910
          break
7911
      if not found:
7912
        raise errors.OpPrereqError("No export found for relative path %s" %
7913
                                    src_path, errors.ECODE_INVAL)
7914

    
7915
    _CheckNodeOnline(self, src_node)
7916
    result = self.rpc.call_export_info(src_node, src_path)
7917
    result.Raise("No export or invalid export found in dir %s" % src_path)
7918

    
7919
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
7920
    if not export_info.has_section(constants.INISECT_EXP):
7921
      raise errors.ProgrammerError("Corrupted export config",
7922
                                   errors.ECODE_ENVIRON)
7923

    
7924
    ei_version = export_info.get(constants.INISECT_EXP, "version")
7925
    if (int(ei_version) != constants.EXPORT_VERSION):
7926
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
7927
                                 (ei_version, constants.EXPORT_VERSION),
7928
                                 errors.ECODE_ENVIRON)
7929
    return export_info
7930

    
7931
  def _ReadExportParams(self, einfo):
7932
    """Use export parameters as defaults.
7933

7934
    In case the opcode doesn't specify (as in override) some instance
7935
    parameters, then try to use them from the export information, if
7936
    that declares them.
7937

7938
    """
7939
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
7940

    
7941
    if self.op.disk_template is None:
7942
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
7943
        self.op.disk_template = einfo.get(constants.INISECT_INS,
7944
                                          "disk_template")
7945
      else:
7946
        raise errors.OpPrereqError("No disk template specified and the export"
7947
                                   " is missing the disk_template information",
7948
                                   errors.ECODE_INVAL)
7949

    
7950
    if not self.op.disks:
7951
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
7952
        disks = []
7953
        # TODO: import the disk iv_name too
7954
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
7955
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
7956
          disks.append({constants.IDISK_SIZE: disk_sz})
7957
        self.op.disks = disks
7958
      else:
7959
        raise errors.OpPrereqError("No disk info specified and the export"
7960
                                   " is missing the disk information",
7961
                                   errors.ECODE_INVAL)
7962

    
7963
    if (not self.op.nics and
7964
        einfo.has_option(constants.INISECT_INS, "nic_count")):
7965
      nics = []
7966
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
7967
        ndict = {}
7968
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
7969
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
7970
          ndict[name] = v
7971
        nics.append(ndict)
7972
      self.op.nics = nics
7973

    
7974
    if (self.op.hypervisor is None and
7975
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
7976
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
7977
    if einfo.has_section(constants.INISECT_HYP):
7978
      # use the export parameters but do not override the ones
7979
      # specified by the user
7980
      for name, value in einfo.items(constants.INISECT_HYP):
7981
        if name not in self.op.hvparams:
7982
          self.op.hvparams[name] = value
7983

    
7984
    if einfo.has_section(constants.INISECT_BEP):
7985
      # use the parameters, without overriding
7986
      for name, value in einfo.items(constants.INISECT_BEP):
7987
        if name not in self.op.beparams:
7988
          self.op.beparams[name] = value
7989
    else:
7990
      # try to read the parameters old style, from the main section
7991
      for name in constants.BES_PARAMETERS:
7992
        if (name not in self.op.beparams and
7993
            einfo.has_option(constants.INISECT_INS, name)):
7994
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
7995

    
7996
    if einfo.has_section(constants.INISECT_OSP):
7997
      # use the parameters, without overriding
7998
      for name, value in einfo.items(constants.INISECT_OSP):
7999
        if name not in self.op.osparams:
8000
          self.op.osparams[name] = value
8001

    
8002
  def _RevertToDefaults(self, cluster):
8003
    """Revert the instance parameters to the default values.
8004

8005
    """
8006
    # hvparams
8007
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
8008
    for name in self.op.hvparams.keys():
8009
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
8010
        del self.op.hvparams[name]
8011
    # beparams
8012
    be_defs = cluster.SimpleFillBE({})
8013
    for name in self.op.beparams.keys():
8014
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
8015
        del self.op.beparams[name]
8016
    # nic params
8017
    nic_defs = cluster.SimpleFillNIC({})
8018
    for nic in self.op.nics:
8019
      for name in constants.NICS_PARAMETERS:
8020
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
8021
          del nic[name]
8022
    # osparams
8023
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
8024
    for name in self.op.osparams.keys():
8025
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
8026
        del self.op.osparams[name]
8027

    
8028
  def CheckPrereq(self):
8029
    """Check prerequisites.
8030

8031
    """
8032
    if self.op.mode == constants.INSTANCE_IMPORT:
8033
      export_info = self._ReadExportInfo()
8034
      self._ReadExportParams(export_info)
8035

    
8036
    if (not self.cfg.GetVGName() and
8037
        self.op.disk_template not in constants.DTS_NOT_LVM):
8038
      raise errors.OpPrereqError("Cluster does not support lvm-based"
8039
                                 " instances", errors.ECODE_STATE)
8040

    
8041
    if self.op.hypervisor is None:
8042
      self.op.hypervisor = self.cfg.GetHypervisorType()
8043

    
8044
    cluster = self.cfg.GetClusterInfo()
8045
    enabled_hvs = cluster.enabled_hypervisors
8046
    if self.op.hypervisor not in enabled_hvs:
8047
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
8048
                                 " cluster (%s)" % (self.op.hypervisor,
8049
                                  ",".join(enabled_hvs)),
8050
                                 errors.ECODE_STATE)
8051

    
8052
    # check hypervisor parameter syntax (locally)
8053
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
8054
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
8055
                                      self.op.hvparams)
8056
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
8057
    hv_type.CheckParameterSyntax(filled_hvp)
8058
    self.hv_full = filled_hvp
8059
    # check that we don't specify global parameters on an instance
8060
    _CheckGlobalHvParams(self.op.hvparams)
8061

    
8062
    # fill and remember the beparams dict
8063
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
8064
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
8065

    
8066
    # build os parameters
8067
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
8068

    
8069
    # now that hvp/bep are in final format, let's reset to defaults,
8070
    # if told to do so
8071
    if self.op.identify_defaults:
8072
      self._RevertToDefaults(cluster)
8073

    
8074
    # NIC buildup
8075
    self.nics = []
8076
    for idx, nic in enumerate(self.op.nics):
8077
      nic_mode_req = nic.get(constants.INIC_MODE, None)
8078
      nic_mode = nic_mode_req
8079
      if nic_mode is None:
8080
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
8081

    
8082
      # in routed mode, for the first nic, the default ip is 'auto'
8083
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
8084
        default_ip_mode = constants.VALUE_AUTO
8085
      else:
8086
        default_ip_mode = constants.VALUE_NONE
8087

    
8088
      # ip validity checks
8089
      ip = nic.get(constants.INIC_IP, default_ip_mode)
8090
      if ip is None or ip.lower() == constants.VALUE_NONE:
8091
        nic_ip = None
8092
      elif ip.lower() == constants.VALUE_AUTO:
8093
        if not self.op.name_check:
8094
          raise errors.OpPrereqError("IP address set to auto but name checks"
8095
                                     " have been skipped",
8096
                                     errors.ECODE_INVAL)
8097
        nic_ip = self.hostname1.ip
8098
      else:
8099
        if not netutils.IPAddress.IsValid(ip):
8100
          raise errors.OpPrereqError("Invalid IP address '%s'" % ip,
8101
                                     errors.ECODE_INVAL)
8102
        nic_ip = ip
8103

    
8104
      # TODO: check the ip address for uniqueness
8105
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
8106
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
8107
                                   errors.ECODE_INVAL)
8108

    
8109
      # MAC address verification
8110
      mac = nic.get(constants.INIC_MAC, constants.VALUE_AUTO)
8111
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8112
        mac = utils.NormalizeAndValidateMac(mac)
8113

    
8114
        try:
8115
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
8116
        except errors.ReservationError:
8117
          raise errors.OpPrereqError("MAC address %s already in use"
8118
                                     " in cluster" % mac,
8119
                                     errors.ECODE_NOTUNIQUE)
8120

    
8121
      #  Build nic parameters
8122
      link = nic.get(constants.INIC_LINK, None)
8123
      nicparams = {}
8124
      if nic_mode_req:
8125
        nicparams[constants.NIC_MODE] = nic_mode_req
8126
      if link:
8127
        nicparams[constants.NIC_LINK] = link
8128

    
8129
      check_params = cluster.SimpleFillNIC(nicparams)
8130
      objects.NIC.CheckParameterSyntax(check_params)
8131
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
8132

    
8133
    # disk checks/pre-build
8134
    default_vg = self.cfg.GetVGName()
8135
    self.disks = []
8136
    for disk in self.op.disks:
8137
      mode = disk.get(constants.IDISK_MODE, constants.DISK_RDWR)
8138
      if mode not in constants.DISK_ACCESS_SET:
8139
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
8140
                                   mode, errors.ECODE_INVAL)
8141
      size = disk.get(constants.IDISK_SIZE, None)
8142
      if size is None:
8143
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
8144
      try:
8145
        size = int(size)
8146
      except (TypeError, ValueError):
8147
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
8148
                                   errors.ECODE_INVAL)
8149

    
8150
      data_vg = disk.get(constants.IDISK_VG, default_vg)
8151
      new_disk = {
8152
        constants.IDISK_SIZE: size,
8153
        constants.IDISK_MODE: mode,
8154
        constants.IDISK_VG: data_vg,
8155
        constants.IDISK_METAVG: disk.get(constants.IDISK_METAVG, data_vg),
8156
        }
8157
      if constants.IDISK_ADOPT in disk:
8158
        new_disk[constants.IDISK_ADOPT] = disk[constants.IDISK_ADOPT]
8159
      self.disks.append(new_disk)
8160

    
8161
    if self.op.mode == constants.INSTANCE_IMPORT:
8162

    
8163
      # Check that the new instance doesn't have less disks than the export
8164
      instance_disks = len(self.disks)
8165
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
8166
      if instance_disks < export_disks:
8167
        raise errors.OpPrereqError("Not enough disks to import."
8168
                                   " (instance: %d, export: %d)" %
8169
                                   (instance_disks, export_disks),
8170
                                   errors.ECODE_INVAL)
8171

    
8172
      disk_images = []
8173
      for idx in range(export_disks):
8174
        option = 'disk%d_dump' % idx
8175
        if export_info.has_option(constants.INISECT_INS, option):
8176
          # FIXME: are the old os-es, disk sizes, etc. useful?
8177
          export_name = export_info.get(constants.INISECT_INS, option)
8178
          image = utils.PathJoin(self.op.src_path, export_name)
8179
          disk_images.append(image)
8180
        else:
8181
          disk_images.append(False)
8182

    
8183
      self.src_images = disk_images
8184

    
8185
      old_name = export_info.get(constants.INISECT_INS, 'name')
8186
      try:
8187
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
8188
      except (TypeError, ValueError), err:
8189
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
8190
                                   " an integer: %s" % str(err),
8191
                                   errors.ECODE_STATE)
8192
      if self.op.instance_name == old_name:
8193
        for idx, nic in enumerate(self.nics):
8194
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
8195
            nic_mac_ini = 'nic%d_mac' % idx
8196
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
8197

    
8198
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
8199

    
8200
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
8201
    if self.op.ip_check:
8202
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
8203
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
8204
                                   (self.check_ip, self.op.instance_name),
8205
                                   errors.ECODE_NOTUNIQUE)
8206

    
8207
    #### mac address generation
8208
    # By generating here the mac address both the allocator and the hooks get
8209
    # the real final mac address rather than the 'auto' or 'generate' value.
8210
    # There is a race condition between the generation and the instance object
8211
    # creation, which means that we know the mac is valid now, but we're not
8212
    # sure it will be when we actually add the instance. If things go bad
8213
    # adding the instance will abort because of a duplicate mac, and the
8214
    # creation job will fail.
8215
    for nic in self.nics:
8216
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8217
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
8218

    
8219
    #### allocator run
8220

    
8221
    if self.op.iallocator is not None:
8222
      self._RunAllocator()
8223

    
8224
    #### node related checks
8225

    
8226
    # check primary node
8227
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
8228
    assert self.pnode is not None, \
8229
      "Cannot retrieve locked node %s" % self.op.pnode
8230
    if pnode.offline:
8231
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
8232
                                 pnode.name, errors.ECODE_STATE)
8233
    if pnode.drained:
8234
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
8235
                                 pnode.name, errors.ECODE_STATE)
8236
    if not pnode.vm_capable:
8237
      raise errors.OpPrereqError("Cannot use non-vm_capable primary node"
8238
                                 " '%s'" % pnode.name, errors.ECODE_STATE)
8239

    
8240
    self.secondaries = []
8241

    
8242
    # mirror node verification
8243
    if self.op.disk_template in constants.DTS_INT_MIRROR:
8244
      if self.op.snode == pnode.name:
8245
        raise errors.OpPrereqError("The secondary node cannot be the"
8246
                                   " primary node", errors.ECODE_INVAL)
8247
      _CheckNodeOnline(self, self.op.snode)
8248
      _CheckNodeNotDrained(self, self.op.snode)
8249
      _CheckNodeVmCapable(self, self.op.snode)
8250
      self.secondaries.append(self.op.snode)
8251

    
8252
    nodenames = [pnode.name] + self.secondaries
8253

    
8254
    if not self.adopt_disks:
8255
      # Check lv size requirements, if not adopting
8256
      req_sizes = _ComputeDiskSizePerVG(self.op.disk_template, self.disks)
8257
      _CheckNodesFreeDiskPerVG(self, nodenames, req_sizes)
8258

    
8259
    elif self.op.disk_template == constants.DT_PLAIN: # Check the adoption data
8260
      all_lvs = set(["%s/%s" % (disk[constants.IDISK_VG],
8261
                                disk[constants.IDISK_ADOPT])
8262
                     for disk in self.disks])
8263
      if len(all_lvs) != len(self.disks):
8264
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
8265
                                   errors.ECODE_INVAL)
8266
      for lv_name in all_lvs:
8267
        try:
8268
          # FIXME: lv_name here is "vg/lv" need to ensure that other calls
8269
          # to ReserveLV uses the same syntax
8270
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
8271
        except errors.ReservationError:
8272
          raise errors.OpPrereqError("LV named %s used by another instance" %
8273
                                     lv_name, errors.ECODE_NOTUNIQUE)
8274

    
8275
      vg_names = self.rpc.call_vg_list([pnode.name])[pnode.name]
8276
      vg_names.Raise("Cannot get VG information from node %s" % pnode.name)
8277

    
8278
      node_lvs = self.rpc.call_lv_list([pnode.name],
8279
                                       vg_names.payload.keys())[pnode.name]
8280
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
8281
      node_lvs = node_lvs.payload
8282

    
8283
      delta = all_lvs.difference(node_lvs.keys())
8284
      if delta:
8285
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
8286
                                   utils.CommaJoin(delta),
8287
                                   errors.ECODE_INVAL)
8288
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
8289
      if online_lvs:
8290
        raise errors.OpPrereqError("Online logical volumes found, cannot"
8291
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
8292
                                   errors.ECODE_STATE)
8293
      # update the size of disk based on what is found
8294
      for dsk in self.disks:
8295
        dsk[constants.IDISK_SIZE] = \
8296
          int(float(node_lvs["%s/%s" % (dsk[constants.IDISK_VG],
8297
                                        dsk[constants.IDISK_ADOPT])][0]))
8298

    
8299
    elif self.op.disk_template == constants.DT_BLOCK:
8300
      # Normalize and de-duplicate device paths
8301
      all_disks = set([os.path.abspath(disk[constants.IDISK_ADOPT])
8302
                       for disk in self.disks])
8303
      if len(all_disks) != len(self.disks):
8304
        raise errors.OpPrereqError("Duplicate disk names given for adoption",
8305
                                   errors.ECODE_INVAL)
8306
      baddisks = [d for d in all_disks
8307
                  if not d.startswith(constants.ADOPTABLE_BLOCKDEV_ROOT)]
8308
      if baddisks:
8309
        raise errors.OpPrereqError("Device node(s) %s lie outside %s and"
8310
                                   " cannot be adopted" %
8311
                                   (", ".join(baddisks),
8312
                                    constants.ADOPTABLE_BLOCKDEV_ROOT),
8313
                                   errors.ECODE_INVAL)
8314

    
8315
      node_disks = self.rpc.call_bdev_sizes([pnode.name],
8316
                                            list(all_disks))[pnode.name]
8317
      node_disks.Raise("Cannot get block device information from node %s" %
8318
                       pnode.name)
8319
      node_disks = node_disks.payload
8320
      delta = all_disks.difference(node_disks.keys())
8321
      if delta:
8322
        raise errors.OpPrereqError("Missing block device(s): %s" %
8323
                                   utils.CommaJoin(delta),
8324
                                   errors.ECODE_INVAL)
8325
      for dsk in self.disks:
8326
        dsk[constants.IDISK_SIZE] = \
8327
          int(float(node_disks[dsk[constants.IDISK_ADOPT]]))
8328

    
8329
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
8330

    
8331
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
8332
    # check OS parameters (remotely)
8333
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
8334

    
8335
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
8336

    
8337
    # memory check on primary node
8338
    if self.op.start:
8339
      _CheckNodeFreeMemory(self, self.pnode.name,
8340
                           "creating instance %s" % self.op.instance_name,
8341
                           self.be_full[constants.BE_MEMORY],
8342
                           self.op.hypervisor)
8343

    
8344
    self.dry_run_result = list(nodenames)
8345

    
8346
  def Exec(self, feedback_fn):
8347
    """Create and add the instance to the cluster.
8348

8349
    """
8350
    instance = self.op.instance_name
8351
    pnode_name = self.pnode.name
8352

    
8353
    ht_kind = self.op.hypervisor
8354
    if ht_kind in constants.HTS_REQ_PORT:
8355
      network_port = self.cfg.AllocatePort()
8356
    else:
8357
      network_port = None
8358

    
8359
    if constants.ENABLE_FILE_STORAGE or constants.ENABLE_SHARED_FILE_STORAGE:
8360
      # this is needed because os.path.join does not accept None arguments
8361
      if self.op.file_storage_dir is None:
8362
        string_file_storage_dir = ""
8363
      else:
8364
        string_file_storage_dir = self.op.file_storage_dir
8365

    
8366
      # build the full file storage dir path
8367
      if self.op.disk_template == constants.DT_SHARED_FILE:
8368
        get_fsd_fn = self.cfg.GetSharedFileStorageDir
8369
      else:
8370
        get_fsd_fn = self.cfg.GetFileStorageDir
8371

    
8372
      file_storage_dir = utils.PathJoin(get_fsd_fn(),
8373
                                        string_file_storage_dir, instance)
8374
    else:
8375
      file_storage_dir = ""
8376

    
8377
    disks = _GenerateDiskTemplate(self,
8378
                                  self.op.disk_template,
8379
                                  instance, pnode_name,
8380
                                  self.secondaries,
8381
                                  self.disks,
8382
                                  file_storage_dir,
8383
                                  self.op.file_driver,
8384
                                  0,
8385
                                  feedback_fn)
8386

    
8387
    iobj = objects.Instance(name=instance, os=self.op.os_type,
8388
                            primary_node=pnode_name,
8389
                            nics=self.nics, disks=disks,
8390
                            disk_template=self.op.disk_template,
8391
                            admin_up=False,
8392
                            network_port=network_port,
8393
                            beparams=self.op.beparams,
8394
                            hvparams=self.op.hvparams,
8395
                            hypervisor=self.op.hypervisor,
8396
                            osparams=self.op.osparams,
8397
                            )
8398

    
8399
    if self.adopt_disks:
8400
      if self.op.disk_template == constants.DT_PLAIN:
8401
        # rename LVs to the newly-generated names; we need to construct
8402
        # 'fake' LV disks with the old data, plus the new unique_id
8403
        tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
8404
        rename_to = []
8405
        for t_dsk, a_dsk in zip (tmp_disks, self.disks):
8406
          rename_to.append(t_dsk.logical_id)
8407
          t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk[constants.IDISK_ADOPT])
8408
          self.cfg.SetDiskID(t_dsk, pnode_name)
8409
        result = self.rpc.call_blockdev_rename(pnode_name,
8410
                                               zip(tmp_disks, rename_to))
8411
        result.Raise("Failed to rename adoped LVs")
8412
    else:
8413
      feedback_fn("* creating instance disks...")
8414
      try:
8415
        _CreateDisks(self, iobj)
8416
      except errors.OpExecError:
8417
        self.LogWarning("Device creation failed, reverting...")
8418
        try:
8419
          _RemoveDisks(self, iobj)
8420
        finally:
8421
          self.cfg.ReleaseDRBDMinors(instance)
8422
          raise
8423

    
8424
    feedback_fn("adding instance %s to cluster config" % instance)
8425

    
8426
    self.cfg.AddInstance(iobj, self.proc.GetECId())
8427

    
8428
    # Declare that we don't want to remove the instance lock anymore, as we've
8429
    # added the instance to the config
8430
    del self.remove_locks[locking.LEVEL_INSTANCE]
8431

    
8432
    if self.op.mode == constants.INSTANCE_IMPORT:
8433
      # Release unused nodes
8434
      _ReleaseLocks(self, locking.LEVEL_NODE, keep=[self.op.src_node])
8435
    else:
8436
      # Release all nodes
8437
      _ReleaseLocks(self, locking.LEVEL_NODE)
8438

    
8439
    disk_abort = False
8440
    if not self.adopt_disks and self.cfg.GetClusterInfo().prealloc_wipe_disks:
8441
      feedback_fn("* wiping instance disks...")
8442
      try:
8443
        _WipeDisks(self, iobj)
8444
      except errors.OpExecError, err:
8445
        logging.exception("Wiping disks failed")
8446
        self.LogWarning("Wiping instance disks failed (%s)", err)
8447
        disk_abort = True
8448

    
8449
    if disk_abort:
8450
      # Something is already wrong with the disks, don't do anything else
8451
      pass
8452
    elif self.op.wait_for_sync:
8453
      disk_abort = not _WaitForSync(self, iobj)
8454
    elif iobj.disk_template in constants.DTS_INT_MIRROR:
8455
      # make sure the disks are not degraded (still sync-ing is ok)
8456
      time.sleep(15)
8457
      feedback_fn("* checking mirrors status")
8458
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
8459
    else:
8460
      disk_abort = False
8461

    
8462
    if disk_abort:
8463
      _RemoveDisks(self, iobj)
8464
      self.cfg.RemoveInstance(iobj.name)
8465
      # Make sure the instance lock gets removed
8466
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
8467
      raise errors.OpExecError("There are some degraded disks for"
8468
                               " this instance")
8469

    
8470
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
8471
      if self.op.mode == constants.INSTANCE_CREATE:
8472
        if not self.op.no_install:
8473
          feedback_fn("* running the instance OS create scripts...")
8474
          # FIXME: pass debug option from opcode to backend
8475
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
8476
                                                 self.op.debug_level)
8477
          result.Raise("Could not add os for instance %s"
8478
                       " on node %s" % (instance, pnode_name))
8479

    
8480
      elif self.op.mode == constants.INSTANCE_IMPORT:
8481
        feedback_fn("* running the instance OS import scripts...")
8482

    
8483
        transfers = []
8484

    
8485
        for idx, image in enumerate(self.src_images):
8486
          if not image:
8487
            continue
8488

    
8489
          # FIXME: pass debug option from opcode to backend
8490
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
8491
                                             constants.IEIO_FILE, (image, ),
8492
                                             constants.IEIO_SCRIPT,
8493
                                             (iobj.disks[idx], idx),
8494
                                             None)
8495
          transfers.append(dt)
8496

    
8497
        import_result = \
8498
          masterd.instance.TransferInstanceData(self, feedback_fn,
8499
                                                self.op.src_node, pnode_name,
8500
                                                self.pnode.secondary_ip,
8501
                                                iobj, transfers)
8502
        if not compat.all(import_result):
8503
          self.LogWarning("Some disks for instance %s on node %s were not"
8504
                          " imported successfully" % (instance, pnode_name))
8505

    
8506
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
8507
        feedback_fn("* preparing remote import...")
8508
        # The source cluster will stop the instance before attempting to make a
8509
        # connection. In some cases stopping an instance can take a long time,
8510
        # hence the shutdown timeout is added to the connection timeout.
8511
        connect_timeout = (constants.RIE_CONNECT_TIMEOUT +
8512
                           self.op.source_shutdown_timeout)
8513
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
8514

    
8515
        assert iobj.primary_node == self.pnode.name
8516
        disk_results = \
8517
          masterd.instance.RemoteImport(self, feedback_fn, iobj, self.pnode,
8518
                                        self.source_x509_ca,
8519
                                        self._cds, timeouts)
8520
        if not compat.all(disk_results):
8521
          # TODO: Should the instance still be started, even if some disks
8522
          # failed to import (valid for local imports, too)?
8523
          self.LogWarning("Some disks for instance %s on node %s were not"
8524
                          " imported successfully" % (instance, pnode_name))
8525

    
8526
        # Run rename script on newly imported instance
8527
        assert iobj.name == instance
8528
        feedback_fn("Running rename script for %s" % instance)
8529
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
8530
                                                   self.source_instance_name,
8531
                                                   self.op.debug_level)
8532
        if result.fail_msg:
8533
          self.LogWarning("Failed to run rename script for %s on node"
8534
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
8535

    
8536
      else:
8537
        # also checked in the prereq part
8538
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
8539
                                     % self.op.mode)
8540

    
8541
    if self.op.start:
8542
      iobj.admin_up = True
8543
      self.cfg.Update(iobj, feedback_fn)
8544
      logging.info("Starting instance %s on node %s", instance, pnode_name)
8545
      feedback_fn("* starting instance...")
8546
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
8547
      result.Raise("Could not start instance")
8548

    
8549
    return list(iobj.all_nodes)
8550

    
8551

    
8552
class LUInstanceConsole(NoHooksLU):
8553
  """Connect to an instance's console.
8554

8555
  This is somewhat special in that it returns the command line that
8556
  you need to run on the master node in order to connect to the
8557
  console.
8558

8559
  """
8560
  REQ_BGL = False
8561

    
8562
  def ExpandNames(self):
8563
    self._ExpandAndLockInstance()
8564

    
8565
  def CheckPrereq(self):
8566
    """Check prerequisites.
8567

8568
    This checks that the instance is in the cluster.
8569

8570
    """
8571
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8572
    assert self.instance is not None, \
8573
      "Cannot retrieve locked instance %s" % self.op.instance_name
8574
    _CheckNodeOnline(self, self.instance.primary_node)
8575

    
8576
  def Exec(self, feedback_fn):
8577
    """Connect to the console of an instance
8578

8579
    """
8580
    instance = self.instance
8581
    node = instance.primary_node
8582

    
8583
    node_insts = self.rpc.call_instance_list([node],
8584
                                             [instance.hypervisor])[node]
8585
    node_insts.Raise("Can't get node information from %s" % node)
8586

    
8587
    if instance.name not in node_insts.payload:
8588
      if instance.admin_up:
8589
        state = constants.INSTST_ERRORDOWN
8590
      else:
8591
        state = constants.INSTST_ADMINDOWN
8592
      raise errors.OpExecError("Instance %s is not running (state %s)" %
8593
                               (instance.name, state))
8594

    
8595
    logging.debug("Connecting to console of %s on %s", instance.name, node)
8596

    
8597
    return _GetInstanceConsole(self.cfg.GetClusterInfo(), instance)
8598

    
8599

    
8600
def _GetInstanceConsole(cluster, instance):
8601
  """Returns console information for an instance.
8602

8603
  @type cluster: L{objects.Cluster}
8604
  @type instance: L{objects.Instance}
8605
  @rtype: dict
8606

8607
  """
8608
  hyper = hypervisor.GetHypervisor(instance.hypervisor)
8609
  # beparams and hvparams are passed separately, to avoid editing the
8610
  # instance and then saving the defaults in the instance itself.
8611
  hvparams = cluster.FillHV(instance)
8612
  beparams = cluster.FillBE(instance)
8613
  console = hyper.GetInstanceConsole(instance, hvparams, beparams)
8614

    
8615
  assert console.instance == instance.name
8616
  assert console.Validate()
8617

    
8618
  return console.ToDict()
8619

    
8620

    
8621
class LUInstanceReplaceDisks(LogicalUnit):
8622
  """Replace the disks of an instance.
8623

8624
  """
8625
  HPATH = "mirrors-replace"
8626
  HTYPE = constants.HTYPE_INSTANCE
8627
  REQ_BGL = False
8628

    
8629
  def CheckArguments(self):
8630
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
8631
                                  self.op.iallocator)
8632

    
8633
  def ExpandNames(self):
8634
    self._ExpandAndLockInstance()
8635

    
8636
    assert locking.LEVEL_NODE not in self.needed_locks
8637
    assert locking.LEVEL_NODEGROUP not in self.needed_locks
8638

    
8639
    assert self.op.iallocator is None or self.op.remote_node is None, \
8640
      "Conflicting options"
8641

    
8642
    if self.op.remote_node is not None:
8643
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8644

    
8645
      # Warning: do not remove the locking of the new secondary here
8646
      # unless DRBD8.AddChildren is changed to work in parallel;
8647
      # currently it doesn't since parallel invocations of
8648
      # FindUnusedMinor will conflict
8649
      self.needed_locks[locking.LEVEL_NODE] = [self.op.remote_node]
8650
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
8651
    else:
8652
      self.needed_locks[locking.LEVEL_NODE] = []
8653
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8654

    
8655
      if self.op.iallocator is not None:
8656
        # iallocator will select a new node in the same group
8657
        self.needed_locks[locking.LEVEL_NODEGROUP] = []
8658

    
8659
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
8660
                                   self.op.iallocator, self.op.remote_node,
8661
                                   self.op.disks, False, self.op.early_release)
8662

    
8663
    self.tasklets = [self.replacer]
8664

    
8665
  def DeclareLocks(self, level):
8666
    if level == locking.LEVEL_NODEGROUP:
8667
      assert self.op.remote_node is None
8668
      assert self.op.iallocator is not None
8669
      assert not self.needed_locks[locking.LEVEL_NODEGROUP]
8670

    
8671
      self.share_locks[locking.LEVEL_NODEGROUP] = 1
8672
      self.needed_locks[locking.LEVEL_NODEGROUP] = \
8673
        self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8674

    
8675
    elif level == locking.LEVEL_NODE:
8676
      if self.op.iallocator is not None:
8677
        assert self.op.remote_node is None
8678
        assert not self.needed_locks[locking.LEVEL_NODE]
8679

    
8680
        # Lock member nodes of all locked groups
8681
        self.needed_locks[locking.LEVEL_NODE] = [node_name
8682
          for group_uuid in self.glm.list_owned(locking.LEVEL_NODEGROUP)
8683
          for node_name in self.cfg.GetNodeGroup(group_uuid).members]
8684
      else:
8685
        self._LockInstancesNodes()
8686

    
8687
  def BuildHooksEnv(self):
8688
    """Build hooks env.
8689

8690
    This runs on the master, the primary and all the secondaries.
8691

8692
    """
8693
    instance = self.replacer.instance
8694
    env = {
8695
      "MODE": self.op.mode,
8696
      "NEW_SECONDARY": self.op.remote_node,
8697
      "OLD_SECONDARY": instance.secondary_nodes[0],
8698
      }
8699
    env.update(_BuildInstanceHookEnvByObject(self, instance))
8700
    return env
8701

    
8702
  def BuildHooksNodes(self):
8703
    """Build hooks nodes.
8704

8705
    """
8706
    instance = self.replacer.instance
8707
    nl = [
8708
      self.cfg.GetMasterNode(),
8709
      instance.primary_node,
8710
      ]
8711
    if self.op.remote_node is not None:
8712
      nl.append(self.op.remote_node)
8713
    return nl, nl
8714

    
8715
  def CheckPrereq(self):
8716
    """Check prerequisites.
8717

8718
    """
8719
    assert (self.glm.is_owned(locking.LEVEL_NODEGROUP) or
8720
            self.op.iallocator is None)
8721

    
8722
    owned_groups = self.glm.list_owned(locking.LEVEL_NODEGROUP)
8723
    if owned_groups:
8724
      groups = self.cfg.GetInstanceNodeGroups(self.op.instance_name)
8725
      if owned_groups != groups:
8726
        raise errors.OpExecError("Node groups used by instance '%s' changed"
8727
                                 " since lock was acquired, current list is %r,"
8728
                                 " used to be '%s'" %
8729
                                 (self.op.instance_name,
8730
                                  utils.CommaJoin(groups),
8731
                                  utils.CommaJoin(owned_groups)))
8732

    
8733
    return LogicalUnit.CheckPrereq(self)
8734

    
8735

    
8736
class TLReplaceDisks(Tasklet):
8737
  """Replaces disks for an instance.
8738

8739
  Note: Locking is not within the scope of this class.
8740

8741
  """
8742
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
8743
               disks, delay_iallocator, early_release):
8744
    """Initializes this class.
8745

8746
    """
8747
    Tasklet.__init__(self, lu)
8748

    
8749
    # Parameters
8750
    self.instance_name = instance_name
8751
    self.mode = mode
8752
    self.iallocator_name = iallocator_name
8753
    self.remote_node = remote_node
8754
    self.disks = disks
8755
    self.delay_iallocator = delay_iallocator
8756
    self.early_release = early_release
8757

    
8758
    # Runtime data
8759
    self.instance = None
8760
    self.new_node = None
8761
    self.target_node = None
8762
    self.other_node = None
8763
    self.remote_node_info = None
8764
    self.node_secondary_ip = None
8765

    
8766
  @staticmethod
8767
  def CheckArguments(mode, remote_node, iallocator):
8768
    """Helper function for users of this class.
8769

8770
    """
8771
    # check for valid parameter combination
8772
    if mode == constants.REPLACE_DISK_CHG:
8773
      if remote_node is None and iallocator is None:
8774
        raise errors.OpPrereqError("When changing the secondary either an"
8775
                                   " iallocator script must be used or the"
8776
                                   " new node given", errors.ECODE_INVAL)
8777

    
8778
      if remote_node is not None and iallocator is not None:
8779
        raise errors.OpPrereqError("Give either the iallocator or the new"
8780
                                   " secondary, not both", errors.ECODE_INVAL)
8781

    
8782
    elif remote_node is not None or iallocator is not None:
8783
      # Not replacing the secondary
8784
      raise errors.OpPrereqError("The iallocator and new node options can"
8785
                                 " only be used when changing the"
8786
                                 " secondary node", errors.ECODE_INVAL)
8787

    
8788
  @staticmethod
8789
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
8790
    """Compute a new secondary node using an IAllocator.
8791

8792
    """
8793
    ial = IAllocator(lu.cfg, lu.rpc,
8794
                     mode=constants.IALLOCATOR_MODE_RELOC,
8795
                     name=instance_name,
8796
                     relocate_from=relocate_from)
8797

    
8798
    ial.Run(iallocator_name)
8799

    
8800
    if not ial.success:
8801
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
8802
                                 " %s" % (iallocator_name, ial.info),
8803
                                 errors.ECODE_NORES)
8804

    
8805
    if len(ial.result) != ial.required_nodes:
8806
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
8807
                                 " of nodes (%s), required %s" %
8808
                                 (iallocator_name,
8809
                                  len(ial.result), ial.required_nodes),
8810
                                 errors.ECODE_FAULT)
8811

    
8812
    remote_node_name = ial.result[0]
8813

    
8814
    lu.LogInfo("Selected new secondary for instance '%s': %s",
8815
               instance_name, remote_node_name)
8816

    
8817
    return remote_node_name
8818

    
8819
  def _FindFaultyDisks(self, node_name):
8820
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
8821
                                    node_name, True)
8822

    
8823
  def _CheckDisksActivated(self, instance):
8824
    """Checks if the instance disks are activated.
8825

8826
    @param instance: The instance to check disks
8827
    @return: True if they are activated, False otherwise
8828

8829
    """
8830
    nodes = instance.all_nodes
8831

    
8832
    for idx, dev in enumerate(instance.disks):
8833
      for node in nodes:
8834
        self.lu.LogInfo("Checking disk/%d on %s", idx, node)
8835
        self.cfg.SetDiskID(dev, node)
8836

    
8837
        result = self.rpc.call_blockdev_find(node, dev)
8838

    
8839
        if result.offline:
8840
          continue
8841
        elif result.fail_msg or not result.payload:
8842
          return False
8843

    
8844
    return True
8845

    
8846
  def CheckPrereq(self):
8847
    """Check prerequisites.
8848

8849
    This checks that the instance is in the cluster.
8850

8851
    """
8852
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
8853
    assert instance is not None, \
8854
      "Cannot retrieve locked instance %s" % self.instance_name
8855

    
8856
    if instance.disk_template != constants.DT_DRBD8:
8857
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
8858
                                 " instances", errors.ECODE_INVAL)
8859

    
8860
    if len(instance.secondary_nodes) != 1:
8861
      raise errors.OpPrereqError("The instance has a strange layout,"
8862
                                 " expected one secondary but found %d" %
8863
                                 len(instance.secondary_nodes),
8864
                                 errors.ECODE_FAULT)
8865

    
8866
    if not self.delay_iallocator:
8867
      self._CheckPrereq2()
8868

    
8869
  def _CheckPrereq2(self):
8870
    """Check prerequisites, second part.
8871

8872
    This function should always be part of CheckPrereq. It was separated and is
8873
    now called from Exec because during node evacuation iallocator was only
8874
    called with an unmodified cluster model, not taking planned changes into
8875
    account.
8876

8877
    """
8878
    instance = self.instance
8879
    secondary_node = instance.secondary_nodes[0]
8880

    
8881
    if self.iallocator_name is None:
8882
      remote_node = self.remote_node
8883
    else:
8884
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
8885
                                       instance.name, instance.secondary_nodes)
8886

    
8887
    if remote_node is None:
8888
      self.remote_node_info = None
8889
    else:
8890
      assert remote_node in self.lu.glm.list_owned(locking.LEVEL_NODE), \
8891
             "Remote node '%s' is not locked" % remote_node
8892

    
8893
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
8894
      assert self.remote_node_info is not None, \
8895
        "Cannot retrieve locked node %s" % remote_node
8896

    
8897
    if remote_node == self.instance.primary_node:
8898
      raise errors.OpPrereqError("The specified node is the primary node of"
8899
                                 " the instance", errors.ECODE_INVAL)
8900

    
8901
    if remote_node == secondary_node:
8902
      raise errors.OpPrereqError("The specified node is already the"
8903
                                 " secondary node of the instance",
8904
                                 errors.ECODE_INVAL)
8905

    
8906
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
8907
                                    constants.REPLACE_DISK_CHG):
8908
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
8909
                                 errors.ECODE_INVAL)
8910

    
8911
    if self.mode == constants.REPLACE_DISK_AUTO:
8912
      if not self._CheckDisksActivated(instance):
8913
        raise errors.OpPrereqError("Please run activate-disks on instance %s"
8914
                                   " first" % self.instance_name,
8915
                                   errors.ECODE_STATE)
8916
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
8917
      faulty_secondary = self._FindFaultyDisks(secondary_node)
8918

    
8919
      if faulty_primary and faulty_secondary:
8920
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
8921
                                   " one node and can not be repaired"
8922
                                   " automatically" % self.instance_name,
8923
                                   errors.ECODE_STATE)
8924

    
8925
      if faulty_primary:
8926
        self.disks = faulty_primary
8927
        self.target_node = instance.primary_node
8928
        self.other_node = secondary_node
8929
        check_nodes = [self.target_node, self.other_node]
8930
      elif faulty_secondary:
8931
        self.disks = faulty_secondary
8932
        self.target_node = secondary_node
8933
        self.other_node = instance.primary_node
8934
        check_nodes = [self.target_node, self.other_node]
8935
      else:
8936
        self.disks = []
8937
        check_nodes = []
8938

    
8939
    else:
8940
      # Non-automatic modes
8941
      if self.mode == constants.REPLACE_DISK_PRI:
8942
        self.target_node = instance.primary_node
8943
        self.other_node = secondary_node
8944
        check_nodes = [self.target_node, self.other_node]
8945

    
8946
      elif self.mode == constants.REPLACE_DISK_SEC:
8947
        self.target_node = secondary_node
8948
        self.other_node = instance.primary_node
8949
        check_nodes = [self.target_node, self.other_node]
8950

    
8951
      elif self.mode == constants.REPLACE_DISK_CHG:
8952
        self.new_node = remote_node
8953
        self.other_node = instance.primary_node
8954
        self.target_node = secondary_node
8955
        check_nodes = [self.new_node, self.other_node]
8956

    
8957
        _CheckNodeNotDrained(self.lu, remote_node)
8958
        _CheckNodeVmCapable(self.lu, remote_node)
8959

    
8960
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
8961
        assert old_node_info is not None
8962
        if old_node_info.offline and not self.early_release:
8963
          # doesn't make sense to delay the release
8964
          self.early_release = True
8965
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
8966
                          " early-release mode", secondary_node)
8967

    
8968
      else:
8969
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
8970
                                     self.mode)
8971

    
8972
      # If not specified all disks should be replaced
8973
      if not self.disks:
8974
        self.disks = range(len(self.instance.disks))
8975

    
8976
    for node in check_nodes:
8977
      _CheckNodeOnline(self.lu, node)
8978

    
8979
    touched_nodes = frozenset(node_name for node_name in [self.new_node,
8980
                                                          self.other_node,
8981
                                                          self.target_node]
8982
                              if node_name is not None)
8983

    
8984
    # Release unneeded node locks
8985
    _ReleaseLocks(self.lu, locking.LEVEL_NODE, keep=touched_nodes)
8986

    
8987
    # Release any owned node group
8988
    if self.lu.glm.is_owned(locking.LEVEL_NODEGROUP):
8989
      _ReleaseLocks(self.lu, locking.LEVEL_NODEGROUP)
8990

    
8991
    # Check whether disks are valid
8992
    for disk_idx in self.disks:
8993
      instance.FindDisk(disk_idx)
8994

    
8995
    # Get secondary node IP addresses
8996
    self.node_secondary_ip = \
8997
      dict((node_name, self.cfg.GetNodeInfo(node_name).secondary_ip)
8998
           for node_name in touched_nodes)
8999

    
9000
  def Exec(self, feedback_fn):
9001
    """Execute disk replacement.
9002

9003
    This dispatches the disk replacement to the appropriate handler.
9004

9005
    """
9006
    if self.delay_iallocator:
9007
      self._CheckPrereq2()
9008

    
9009
    if __debug__:
9010
      # Verify owned locks before starting operation
9011
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9012
      assert set(owned_locks) == set(self.node_secondary_ip), \
9013
          ("Incorrect node locks, owning %s, expected %s" %
9014
           (owned_locks, self.node_secondary_ip.keys()))
9015

    
9016
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_INSTANCE)
9017
      assert list(owned_locks) == [self.instance_name], \
9018
          "Instance '%s' not locked" % self.instance_name
9019

    
9020
      assert not self.lu.glm.is_owned(locking.LEVEL_NODEGROUP), \
9021
          "Should not own any node group lock at this point"
9022

    
9023
    if not self.disks:
9024
      feedback_fn("No disks need replacement")
9025
      return
9026

    
9027
    feedback_fn("Replacing disk(s) %s for %s" %
9028
                (utils.CommaJoin(self.disks), self.instance.name))
9029

    
9030
    activate_disks = (not self.instance.admin_up)
9031

    
9032
    # Activate the instance disks if we're replacing them on a down instance
9033
    if activate_disks:
9034
      _StartInstanceDisks(self.lu, self.instance, True)
9035

    
9036
    try:
9037
      # Should we replace the secondary node?
9038
      if self.new_node is not None:
9039
        fn = self._ExecDrbd8Secondary
9040
      else:
9041
        fn = self._ExecDrbd8DiskOnly
9042

    
9043
      result = fn(feedback_fn)
9044
    finally:
9045
      # Deactivate the instance disks if we're replacing them on a
9046
      # down instance
9047
      if activate_disks:
9048
        _SafeShutdownInstanceDisks(self.lu, self.instance)
9049

    
9050
    if __debug__:
9051
      # Verify owned locks
9052
      owned_locks = self.lu.glm.list_owned(locking.LEVEL_NODE)
9053
      nodes = frozenset(self.node_secondary_ip)
9054
      assert ((self.early_release and not owned_locks) or
9055
              (not self.early_release and not (set(owned_locks) - nodes))), \
9056
        ("Not owning the correct locks, early_release=%s, owned=%r,"
9057
         " nodes=%r" % (self.early_release, owned_locks, nodes))
9058

    
9059
    return result
9060

    
9061
  def _CheckVolumeGroup(self, nodes):
9062
    self.lu.LogInfo("Checking volume groups")
9063

    
9064
    vgname = self.cfg.GetVGName()
9065

    
9066
    # Make sure volume group exists on all involved nodes
9067
    results = self.rpc.call_vg_list(nodes)
9068
    if not results:
9069
      raise errors.OpExecError("Can't list volume groups on the nodes")
9070

    
9071
    for node in nodes:
9072
      res = results[node]
9073
      res.Raise("Error checking node %s" % node)
9074
      if vgname not in res.payload:
9075
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
9076
                                 (vgname, node))
9077

    
9078
  def _CheckDisksExistence(self, nodes):
9079
    # Check disk existence
9080
    for idx, dev in enumerate(self.instance.disks):
9081
      if idx not in self.disks:
9082
        continue
9083

    
9084
      for node in nodes:
9085
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
9086
        self.cfg.SetDiskID(dev, node)
9087

    
9088
        result = self.rpc.call_blockdev_find(node, dev)
9089

    
9090
        msg = result.fail_msg
9091
        if msg or not result.payload:
9092
          if not msg:
9093
            msg = "disk not found"
9094
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
9095
                                   (idx, node, msg))
9096

    
9097
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
9098
    for idx, dev in enumerate(self.instance.disks):
9099
      if idx not in self.disks:
9100
        continue
9101

    
9102
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
9103
                      (idx, node_name))
9104

    
9105
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
9106
                                   ldisk=ldisk):
9107
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
9108
                                 " replace disks for instance %s" %
9109
                                 (node_name, self.instance.name))
9110

    
9111
  def _CreateNewStorage(self, node_name):
9112
    iv_names = {}
9113

    
9114
    for idx, dev in enumerate(self.instance.disks):
9115
      if idx not in self.disks:
9116
        continue
9117

    
9118
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
9119

    
9120
      self.cfg.SetDiskID(dev, node_name)
9121

    
9122
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
9123
      names = _GenerateUniqueNames(self.lu, lv_names)
9124

    
9125
      vg_data = dev.children[0].logical_id[0]
9126
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
9127
                             logical_id=(vg_data, names[0]))
9128
      vg_meta = dev.children[1].logical_id[0]
9129
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
9130
                             logical_id=(vg_meta, names[1]))
9131

    
9132
      new_lvs = [lv_data, lv_meta]
9133
      old_lvs = dev.children
9134
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
9135

    
9136
      # we pass force_create=True to force the LVM creation
9137
      for new_lv in new_lvs:
9138
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
9139
                        _GetInstanceInfoText(self.instance), False)
9140

    
9141
    return iv_names
9142

    
9143
  def _CheckDevices(self, node_name, iv_names):
9144
    for name, (dev, _, _) in iv_names.iteritems():
9145
      self.cfg.SetDiskID(dev, node_name)
9146

    
9147
      result = self.rpc.call_blockdev_find(node_name, dev)
9148

    
9149
      msg = result.fail_msg
9150
      if msg or not result.payload:
9151
        if not msg:
9152
          msg = "disk not found"
9153
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
9154
                                 (name, msg))
9155

    
9156
      if result.payload.is_degraded:
9157
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
9158

    
9159
  def _RemoveOldStorage(self, node_name, iv_names):
9160
    for name, (_, old_lvs, _) in iv_names.iteritems():
9161
      self.lu.LogInfo("Remove logical volumes for %s" % name)
9162

    
9163
      for lv in old_lvs:
9164
        self.cfg.SetDiskID(lv, node_name)
9165

    
9166
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
9167
        if msg:
9168
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
9169
                             hint="remove unused LVs manually")
9170

    
9171
  def _ExecDrbd8DiskOnly(self, feedback_fn):
9172
    """Replace a disk on the primary or secondary for DRBD 8.
9173

9174
    The algorithm for replace is quite complicated:
9175

9176
      1. for each disk to be replaced:
9177

9178
        1. create new LVs on the target node with unique names
9179
        1. detach old LVs from the drbd device
9180
        1. rename old LVs to name_replaced.<time_t>
9181
        1. rename new LVs to old LVs
9182
        1. attach the new LVs (with the old names now) to the drbd device
9183

9184
      1. wait for sync across all devices
9185

9186
      1. for each modified disk:
9187

9188
        1. remove old LVs (which have the name name_replaces.<time_t>)
9189

9190
    Failures are not very well handled.
9191

9192
    """
9193
    steps_total = 6
9194

    
9195
    # Step: check device activation
9196
    self.lu.LogStep(1, steps_total, "Check device existence")
9197
    self._CheckDisksExistence([self.other_node, self.target_node])
9198
    self._CheckVolumeGroup([self.target_node, self.other_node])
9199

    
9200
    # Step: check other node consistency
9201
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9202
    self._CheckDisksConsistency(self.other_node,
9203
                                self.other_node == self.instance.primary_node,
9204
                                False)
9205

    
9206
    # Step: create new storage
9207
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9208
    iv_names = self._CreateNewStorage(self.target_node)
9209

    
9210
    # Step: for each lv, detach+rename*2+attach
9211
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9212
    for dev, old_lvs, new_lvs in iv_names.itervalues():
9213
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
9214

    
9215
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
9216
                                                     old_lvs)
9217
      result.Raise("Can't detach drbd from local storage on node"
9218
                   " %s for device %s" % (self.target_node, dev.iv_name))
9219
      #dev.children = []
9220
      #cfg.Update(instance)
9221

    
9222
      # ok, we created the new LVs, so now we know we have the needed
9223
      # storage; as such, we proceed on the target node to rename
9224
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
9225
      # using the assumption that logical_id == physical_id (which in
9226
      # turn is the unique_id on that node)
9227

    
9228
      # FIXME(iustin): use a better name for the replaced LVs
9229
      temp_suffix = int(time.time())
9230
      ren_fn = lambda d, suff: (d.physical_id[0],
9231
                                d.physical_id[1] + "_replaced-%s" % suff)
9232

    
9233
      # Build the rename list based on what LVs exist on the node
9234
      rename_old_to_new = []
9235
      for to_ren in old_lvs:
9236
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
9237
        if not result.fail_msg and result.payload:
9238
          # device exists
9239
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
9240

    
9241
      self.lu.LogInfo("Renaming the old LVs on the target node")
9242
      result = self.rpc.call_blockdev_rename(self.target_node,
9243
                                             rename_old_to_new)
9244
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
9245

    
9246
      # Now we rename the new LVs to the old LVs
9247
      self.lu.LogInfo("Renaming the new LVs on the target node")
9248
      rename_new_to_old = [(new, old.physical_id)
9249
                           for old, new in zip(old_lvs, new_lvs)]
9250
      result = self.rpc.call_blockdev_rename(self.target_node,
9251
                                             rename_new_to_old)
9252
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
9253

    
9254
      for old, new in zip(old_lvs, new_lvs):
9255
        new.logical_id = old.logical_id
9256
        self.cfg.SetDiskID(new, self.target_node)
9257

    
9258
      for disk in old_lvs:
9259
        disk.logical_id = ren_fn(disk, temp_suffix)
9260
        self.cfg.SetDiskID(disk, self.target_node)
9261

    
9262
      # Now that the new lvs have the old name, we can add them to the device
9263
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
9264
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
9265
                                                  new_lvs)
9266
      msg = result.fail_msg
9267
      if msg:
9268
        for new_lv in new_lvs:
9269
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
9270
                                               new_lv).fail_msg
9271
          if msg2:
9272
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
9273
                               hint=("cleanup manually the unused logical"
9274
                                     "volumes"))
9275
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
9276

    
9277
      dev.children = new_lvs
9278

    
9279
      self.cfg.Update(self.instance, feedback_fn)
9280

    
9281
    cstep = 5
9282
    if self.early_release:
9283
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9284
      cstep += 1
9285
      self._RemoveOldStorage(self.target_node, iv_names)
9286
      # WARNING: we release both node locks here, do not do other RPCs
9287
      # than WaitForSync to the primary node
9288
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9289
                    names=[self.target_node, self.other_node])
9290

    
9291
    # Wait for sync
9292
    # This can fail as the old devices are degraded and _WaitForSync
9293
    # does a combined result over all disks, so we don't check its return value
9294
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9295
    cstep += 1
9296
    _WaitForSync(self.lu, self.instance)
9297

    
9298
    # Check all devices manually
9299
    self._CheckDevices(self.instance.primary_node, iv_names)
9300

    
9301
    # Step: remove old storage
9302
    if not self.early_release:
9303
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9304
      cstep += 1
9305
      self._RemoveOldStorage(self.target_node, iv_names)
9306

    
9307
  def _ExecDrbd8Secondary(self, feedback_fn):
9308
    """Replace the secondary node for DRBD 8.
9309

9310
    The algorithm for replace is quite complicated:
9311
      - for all disks of the instance:
9312
        - create new LVs on the new node with same names
9313
        - shutdown the drbd device on the old secondary
9314
        - disconnect the drbd network on the primary
9315
        - create the drbd device on the new secondary
9316
        - network attach the drbd on the primary, using an artifice:
9317
          the drbd code for Attach() will connect to the network if it
9318
          finds a device which is connected to the good local disks but
9319
          not network enabled
9320
      - wait for sync across all devices
9321
      - remove all disks from the old secondary
9322

9323
    Failures are not very well handled.
9324

9325
    """
9326
    steps_total = 6
9327

    
9328
    # Step: check device activation
9329
    self.lu.LogStep(1, steps_total, "Check device existence")
9330
    self._CheckDisksExistence([self.instance.primary_node])
9331
    self._CheckVolumeGroup([self.instance.primary_node])
9332

    
9333
    # Step: check other node consistency
9334
    self.lu.LogStep(2, steps_total, "Check peer consistency")
9335
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
9336

    
9337
    # Step: create new storage
9338
    self.lu.LogStep(3, steps_total, "Allocate new storage")
9339
    for idx, dev in enumerate(self.instance.disks):
9340
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
9341
                      (self.new_node, idx))
9342
      # we pass force_create=True to force LVM creation
9343
      for new_lv in dev.children:
9344
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
9345
                        _GetInstanceInfoText(self.instance), False)
9346

    
9347
    # Step 4: dbrd minors and drbd setups changes
9348
    # after this, we must manually remove the drbd minors on both the
9349
    # error and the success paths
9350
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
9351
    minors = self.cfg.AllocateDRBDMinor([self.new_node
9352
                                         for dev in self.instance.disks],
9353
                                        self.instance.name)
9354
    logging.debug("Allocated minors %r", minors)
9355

    
9356
    iv_names = {}
9357
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
9358
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
9359
                      (self.new_node, idx))
9360
      # create new devices on new_node; note that we create two IDs:
9361
      # one without port, so the drbd will be activated without
9362
      # networking information on the new node at this stage, and one
9363
      # with network, for the latter activation in step 4
9364
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
9365
      if self.instance.primary_node == o_node1:
9366
        p_minor = o_minor1
9367
      else:
9368
        assert self.instance.primary_node == o_node2, "Three-node instance?"
9369
        p_minor = o_minor2
9370

    
9371
      new_alone_id = (self.instance.primary_node, self.new_node, None,
9372
                      p_minor, new_minor, o_secret)
9373
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
9374
                    p_minor, new_minor, o_secret)
9375

    
9376
      iv_names[idx] = (dev, dev.children, new_net_id)
9377
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
9378
                    new_net_id)
9379
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
9380
                              logical_id=new_alone_id,
9381
                              children=dev.children,
9382
                              size=dev.size)
9383
      try:
9384
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
9385
                              _GetInstanceInfoText(self.instance), False)
9386
      except errors.GenericError:
9387
        self.cfg.ReleaseDRBDMinors(self.instance.name)
9388
        raise
9389

    
9390
    # We have new devices, shutdown the drbd on the old secondary
9391
    for idx, dev in enumerate(self.instance.disks):
9392
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
9393
      self.cfg.SetDiskID(dev, self.target_node)
9394
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
9395
      if msg:
9396
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
9397
                           "node: %s" % (idx, msg),
9398
                           hint=("Please cleanup this device manually as"
9399
                                 " soon as possible"))
9400

    
9401
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
9402
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
9403
                                               self.node_secondary_ip,
9404
                                               self.instance.disks)\
9405
                                              [self.instance.primary_node]
9406

    
9407
    msg = result.fail_msg
9408
    if msg:
9409
      # detaches didn't succeed (unlikely)
9410
      self.cfg.ReleaseDRBDMinors(self.instance.name)
9411
      raise errors.OpExecError("Can't detach the disks from the network on"
9412
                               " old node: %s" % (msg,))
9413

    
9414
    # if we managed to detach at least one, we update all the disks of
9415
    # the instance to point to the new secondary
9416
    self.lu.LogInfo("Updating instance configuration")
9417
    for dev, _, new_logical_id in iv_names.itervalues():
9418
      dev.logical_id = new_logical_id
9419
      self.cfg.SetDiskID(dev, self.instance.primary_node)
9420

    
9421
    self.cfg.Update(self.instance, feedback_fn)
9422

    
9423
    # and now perform the drbd attach
9424
    self.lu.LogInfo("Attaching primary drbds to new secondary"
9425
                    " (standalone => connected)")
9426
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
9427
                                            self.new_node],
9428
                                           self.node_secondary_ip,
9429
                                           self.instance.disks,
9430
                                           self.instance.name,
9431
                                           False)
9432
    for to_node, to_result in result.items():
9433
      msg = to_result.fail_msg
9434
      if msg:
9435
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
9436
                           to_node, msg,
9437
                           hint=("please do a gnt-instance info to see the"
9438
                                 " status of disks"))
9439
    cstep = 5
9440
    if self.early_release:
9441
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9442
      cstep += 1
9443
      self._RemoveOldStorage(self.target_node, iv_names)
9444
      # WARNING: we release all node locks here, do not do other RPCs
9445
      # than WaitForSync to the primary node
9446
      _ReleaseLocks(self.lu, locking.LEVEL_NODE,
9447
                    names=[self.instance.primary_node,
9448
                           self.target_node,
9449
                           self.new_node])
9450

    
9451
    # Wait for sync
9452
    # This can fail as the old devices are degraded and _WaitForSync
9453
    # does a combined result over all disks, so we don't check its return value
9454
    self.lu.LogStep(cstep, steps_total, "Sync devices")
9455
    cstep += 1
9456
    _WaitForSync(self.lu, self.instance)
9457

    
9458
    # Check all devices manually
9459
    self._CheckDevices(self.instance.primary_node, iv_names)
9460

    
9461
    # Step: remove old storage
9462
    if not self.early_release:
9463
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
9464
      self._RemoveOldStorage(self.target_node, iv_names)
9465

    
9466

    
9467
class LURepairNodeStorage(NoHooksLU):
9468
  """Repairs the volume group on a node.
9469

9470
  """
9471
  REQ_BGL = False
9472

    
9473
  def CheckArguments(self):
9474
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
9475

    
9476
    storage_type = self.op.storage_type
9477

    
9478
    if (constants.SO_FIX_CONSISTENCY not in
9479
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
9480
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
9481
                                 " repaired" % storage_type,
9482
                                 errors.ECODE_INVAL)
9483

    
9484
  def ExpandNames(self):
9485
    self.needed_locks = {
9486
      locking.LEVEL_NODE: [self.op.node_name],
9487
      }
9488

    
9489
  def _CheckFaultyDisks(self, instance, node_name):
9490
    """Ensure faulty disks abort the opcode or at least warn."""
9491
    try:
9492
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
9493
                                  node_name, True):
9494
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
9495
                                   " node '%s'" % (instance.name, node_name),
9496
                                   errors.ECODE_STATE)
9497
    except errors.OpPrereqError, err:
9498
      if self.op.ignore_consistency:
9499
        self.proc.LogWarning(str(err.args[0]))
9500
      else:
9501
        raise
9502

    
9503
  def CheckPrereq(self):
9504
    """Check prerequisites.
9505

9506
    """
9507
    # Check whether any instance on this node has faulty disks
9508
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
9509
      if not inst.admin_up:
9510
        continue
9511
      check_nodes = set(inst.all_nodes)
9512
      check_nodes.discard(self.op.node_name)
9513
      for inst_node_name in check_nodes:
9514
        self._CheckFaultyDisks(inst, inst_node_name)
9515

    
9516
  def Exec(self, feedback_fn):
9517
    feedback_fn("Repairing storage unit '%s' on %s ..." %
9518
                (self.op.name, self.op.node_name))
9519

    
9520
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
9521
    result = self.rpc.call_storage_execute(self.op.node_name,
9522
                                           self.op.storage_type, st_args,
9523
                                           self.op.name,
9524
                                           constants.SO_FIX_CONSISTENCY)
9525
    result.Raise("Failed to repair storage unit '%s' on %s" %
9526
                 (self.op.name, self.op.node_name))
9527

    
9528

    
9529
class LUNodeEvacStrategy(NoHooksLU):
9530
  """Computes the node evacuation strategy.
9531

9532
  """
9533
  REQ_BGL = False
9534

    
9535
  def CheckArguments(self):
9536
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
9537

    
9538
  def ExpandNames(self):
9539
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
9540
    self.needed_locks = locks = {}
9541
    if self.op.remote_node is None:
9542
      locks[locking.LEVEL_NODE] = locking.ALL_SET
9543
    else:
9544
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9545
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
9546

    
9547
  def Exec(self, feedback_fn):
9548
    if self.op.remote_node is not None:
9549
      instances = []
9550
      for node in self.op.nodes:
9551
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
9552
      result = []
9553
      for i in instances:
9554
        if i.primary_node == self.op.remote_node:
9555
          raise errors.OpPrereqError("Node %s is the primary node of"
9556
                                     " instance %s, cannot use it as"
9557
                                     " secondary" %
9558
                                     (self.op.remote_node, i.name),
9559
                                     errors.ECODE_INVAL)
9560
        result.append([i.name, self.op.remote_node])
9561
    else:
9562
      ial = IAllocator(self.cfg, self.rpc,
9563
                       mode=constants.IALLOCATOR_MODE_MEVAC,
9564
                       evac_nodes=self.op.nodes)
9565
      ial.Run(self.op.iallocator, validate=True)
9566
      if not ial.success:
9567
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
9568
                                 errors.ECODE_NORES)
9569
      result = ial.result
9570
    return result
9571

    
9572

    
9573
class LUInstanceGrowDisk(LogicalUnit):
9574
  """Grow a disk of an instance.
9575

9576
  """
9577
  HPATH = "disk-grow"
9578
  HTYPE = constants.HTYPE_INSTANCE
9579
  REQ_BGL = False
9580

    
9581
  def ExpandNames(self):
9582
    self._ExpandAndLockInstance()
9583
    self.needed_locks[locking.LEVEL_NODE] = []
9584
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9585

    
9586
  def DeclareLocks(self, level):
9587
    if level == locking.LEVEL_NODE:
9588
      self._LockInstancesNodes()
9589

    
9590
  def BuildHooksEnv(self):
9591
    """Build hooks env.
9592

9593
    This runs on the master, the primary and all the secondaries.
9594

9595
    """
9596
    env = {
9597
      "DISK": self.op.disk,
9598
      "AMOUNT": self.op.amount,
9599
      }
9600
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9601
    return env
9602

    
9603
  def BuildHooksNodes(self):
9604
    """Build hooks nodes.
9605

9606
    """
9607
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
9608
    return (nl, nl)
9609

    
9610
  def CheckPrereq(self):
9611
    """Check prerequisites.
9612

9613
    This checks that the instance is in the cluster.
9614

9615
    """
9616
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
9617
    assert instance is not None, \
9618
      "Cannot retrieve locked instance %s" % self.op.instance_name
9619
    nodenames = list(instance.all_nodes)
9620
    for node in nodenames:
9621
      _CheckNodeOnline(self, node)
9622

    
9623
    self.instance = instance
9624

    
9625
    if instance.disk_template not in constants.DTS_GROWABLE:
9626
      raise errors.OpPrereqError("Instance's disk layout does not support"
9627
                                 " growing", errors.ECODE_INVAL)
9628

    
9629
    self.disk = instance.FindDisk(self.op.disk)
9630

    
9631
    if instance.disk_template not in (constants.DT_FILE,
9632
                                      constants.DT_SHARED_FILE):
9633
      # TODO: check the free disk space for file, when that feature will be
9634
      # supported
9635
      _CheckNodesFreeDiskPerVG(self, nodenames,
9636
                               self.disk.ComputeGrowth(self.op.amount))
9637

    
9638
  def Exec(self, feedback_fn):
9639
    """Execute disk grow.
9640

9641
    """
9642
    instance = self.instance
9643
    disk = self.disk
9644

    
9645
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
9646
    if not disks_ok:
9647
      raise errors.OpExecError("Cannot activate block device to grow")
9648

    
9649
    # First run all grow ops in dry-run mode
9650
    for node in instance.all_nodes:
9651
      self.cfg.SetDiskID(disk, node)
9652
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, True)
9653
      result.Raise("Grow request failed to node %s" % node)
9654

    
9655
    # We know that (as far as we can test) operations across different
9656
    # nodes will succeed, time to run it for real
9657
    for node in instance.all_nodes:
9658
      self.cfg.SetDiskID(disk, node)
9659
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount, False)
9660
      result.Raise("Grow request failed to node %s" % node)
9661

    
9662
      # TODO: Rewrite code to work properly
9663
      # DRBD goes into sync mode for a short amount of time after executing the
9664
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
9665
      # calling "resize" in sync mode fails. Sleeping for a short amount of
9666
      # time is a work-around.
9667
      time.sleep(5)
9668

    
9669
    disk.RecordGrow(self.op.amount)
9670
    self.cfg.Update(instance, feedback_fn)
9671
    if self.op.wait_for_sync:
9672
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
9673
      if disk_abort:
9674
        self.proc.LogWarning("Disk sync-ing has not returned a good"
9675
                             " status; please check the instance")
9676
      if not instance.admin_up:
9677
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
9678
    elif not instance.admin_up:
9679
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
9680
                           " not supposed to be running because no wait for"
9681
                           " sync mode was requested")
9682

    
9683

    
9684
class LUInstanceQueryData(NoHooksLU):
9685
  """Query runtime instance data.
9686

9687
  """
9688
  REQ_BGL = False
9689

    
9690
  def ExpandNames(self):
9691
    self.needed_locks = {}
9692

    
9693
    # Use locking if requested or when non-static information is wanted
9694
    if not (self.op.static or self.op.use_locking):
9695
      self.LogWarning("Non-static data requested, locks need to be acquired")
9696
      self.op.use_locking = True
9697

    
9698
    if self.op.instances or not self.op.use_locking:
9699
      # Expand instance names right here
9700
      self.wanted_names = _GetWantedInstances(self, self.op.instances)
9701
    else:
9702
      # Will use acquired locks
9703
      self.wanted_names = None
9704

    
9705
    if self.op.use_locking:
9706
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9707

    
9708
      if self.wanted_names is None:
9709
        self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
9710
      else:
9711
        self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
9712

    
9713
      self.needed_locks[locking.LEVEL_NODE] = []
9714
      self.share_locks = dict.fromkeys(locking.LEVELS, 1)
9715
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9716

    
9717
  def DeclareLocks(self, level):
9718
    if self.op.use_locking and level == locking.LEVEL_NODE:
9719
      self._LockInstancesNodes()
9720

    
9721
  def CheckPrereq(self):
9722
    """Check prerequisites.
9723

9724
    This only checks the optional instance list against the existing names.
9725

9726
    """
9727
    if self.wanted_names is None:
9728
      assert self.op.use_locking, "Locking was not used"
9729
      self.wanted_names = self.glm.list_owned(locking.LEVEL_INSTANCE)
9730

    
9731
    self.wanted_instances = [self.cfg.GetInstanceInfo(name)
9732
                             for name in self.wanted_names]
9733

    
9734
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
9735
    """Returns the status of a block device
9736

9737
    """
9738
    if self.op.static or not node:
9739
      return None
9740

    
9741
    self.cfg.SetDiskID(dev, node)
9742

    
9743
    result = self.rpc.call_blockdev_find(node, dev)
9744
    if result.offline:
9745
      return None
9746

    
9747
    result.Raise("Can't compute disk status for %s" % instance_name)
9748

    
9749
    status = result.payload
9750
    if status is None:
9751
      return None
9752

    
9753
    return (status.dev_path, status.major, status.minor,
9754
            status.sync_percent, status.estimated_time,
9755
            status.is_degraded, status.ldisk_status)
9756

    
9757
  def _ComputeDiskStatus(self, instance, snode, dev):
9758
    """Compute block device status.
9759

9760
    """
9761
    if dev.dev_type in constants.LDS_DRBD:
9762
      # we change the snode then (otherwise we use the one passed in)
9763
      if dev.logical_id[0] == instance.primary_node:
9764
        snode = dev.logical_id[1]
9765
      else:
9766
        snode = dev.logical_id[0]
9767

    
9768
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
9769
                                              instance.name, dev)
9770
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
9771

    
9772
    if dev.children:
9773
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
9774
                      for child in dev.children]
9775
    else:
9776
      dev_children = []
9777

    
9778
    return {
9779
      "iv_name": dev.iv_name,
9780
      "dev_type": dev.dev_type,
9781
      "logical_id": dev.logical_id,
9782
      "physical_id": dev.physical_id,
9783
      "pstatus": dev_pstatus,
9784
      "sstatus": dev_sstatus,
9785
      "children": dev_children,
9786
      "mode": dev.mode,
9787
      "size": dev.size,
9788
      }
9789

    
9790
  def Exec(self, feedback_fn):
9791
    """Gather and return data"""
9792
    result = {}
9793

    
9794
    cluster = self.cfg.GetClusterInfo()
9795

    
9796
    for instance in self.wanted_instances:
9797
      if not self.op.static:
9798
        remote_info = self.rpc.call_instance_info(instance.primary_node,
9799
                                                  instance.name,
9800
                                                  instance.hypervisor)
9801
        remote_info.Raise("Error checking node %s" % instance.primary_node)
9802
        remote_info = remote_info.payload
9803
        if remote_info and "state" in remote_info:
9804
          remote_state = "up"
9805
        else:
9806
          remote_state = "down"
9807
      else:
9808
        remote_state = None
9809
      if instance.admin_up:
9810
        config_state = "up"
9811
      else:
9812
        config_state = "down"
9813

    
9814
      disks = [self._ComputeDiskStatus(instance, None, device)
9815
               for device in instance.disks]
9816

    
9817
      result[instance.name] = {
9818
        "name": instance.name,
9819
        "config_state": config_state,
9820
        "run_state": remote_state,
9821
        "pnode": instance.primary_node,
9822
        "snodes": instance.secondary_nodes,
9823
        "os": instance.os,
9824
        # this happens to be the same format used for hooks
9825
        "nics": _NICListToTuple(self, instance.nics),
9826
        "disk_template": instance.disk_template,
9827
        "disks": disks,
9828
        "hypervisor": instance.hypervisor,
9829
        "network_port": instance.network_port,
9830
        "hv_instance": instance.hvparams,
9831
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
9832
        "be_instance": instance.beparams,
9833
        "be_actual": cluster.FillBE(instance),
9834
        "os_instance": instance.osparams,
9835
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
9836
        "serial_no": instance.serial_no,
9837
        "mtime": instance.mtime,
9838
        "ctime": instance.ctime,
9839
        "uuid": instance.uuid,
9840
        }
9841

    
9842
    return result
9843

    
9844

    
9845
class LUInstanceSetParams(LogicalUnit):
9846
  """Modifies an instances's parameters.
9847

9848
  """
9849
  HPATH = "instance-modify"
9850
  HTYPE = constants.HTYPE_INSTANCE
9851
  REQ_BGL = False
9852

    
9853
  def CheckArguments(self):
9854
    if not (self.op.nics or self.op.disks or self.op.disk_template or
9855
            self.op.hvparams or self.op.beparams or self.op.os_name):
9856
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
9857

    
9858
    if self.op.hvparams:
9859
      _CheckGlobalHvParams(self.op.hvparams)
9860

    
9861
    # Disk validation
9862
    disk_addremove = 0
9863
    for disk_op, disk_dict in self.op.disks:
9864
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
9865
      if disk_op == constants.DDM_REMOVE:
9866
        disk_addremove += 1
9867
        continue
9868
      elif disk_op == constants.DDM_ADD:
9869
        disk_addremove += 1
9870
      else:
9871
        if not isinstance(disk_op, int):
9872
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
9873
        if not isinstance(disk_dict, dict):
9874
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
9875
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9876

    
9877
      if disk_op == constants.DDM_ADD:
9878
        mode = disk_dict.setdefault(constants.IDISK_MODE, constants.DISK_RDWR)
9879
        if mode not in constants.DISK_ACCESS_SET:
9880
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
9881
                                     errors.ECODE_INVAL)
9882
        size = disk_dict.get(constants.IDISK_SIZE, None)
9883
        if size is None:
9884
          raise errors.OpPrereqError("Required disk parameter size missing",
9885
                                     errors.ECODE_INVAL)
9886
        try:
9887
          size = int(size)
9888
        except (TypeError, ValueError), err:
9889
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
9890
                                     str(err), errors.ECODE_INVAL)
9891
        disk_dict[constants.IDISK_SIZE] = size
9892
      else:
9893
        # modification of disk
9894
        if constants.IDISK_SIZE in disk_dict:
9895
          raise errors.OpPrereqError("Disk size change not possible, use"
9896
                                     " grow-disk", errors.ECODE_INVAL)
9897

    
9898
    if disk_addremove > 1:
9899
      raise errors.OpPrereqError("Only one disk add or remove operation"
9900
                                 " supported at a time", errors.ECODE_INVAL)
9901

    
9902
    if self.op.disks and self.op.disk_template is not None:
9903
      raise errors.OpPrereqError("Disk template conversion and other disk"
9904
                                 " changes not supported at the same time",
9905
                                 errors.ECODE_INVAL)
9906

    
9907
    if (self.op.disk_template and
9908
        self.op.disk_template in constants.DTS_INT_MIRROR and
9909
        self.op.remote_node is None):
9910
      raise errors.OpPrereqError("Changing the disk template to a mirrored"
9911
                                 " one requires specifying a secondary node",
9912
                                 errors.ECODE_INVAL)
9913

    
9914
    # NIC validation
9915
    nic_addremove = 0
9916
    for nic_op, nic_dict in self.op.nics:
9917
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
9918
      if nic_op == constants.DDM_REMOVE:
9919
        nic_addremove += 1
9920
        continue
9921
      elif nic_op == constants.DDM_ADD:
9922
        nic_addremove += 1
9923
      else:
9924
        if not isinstance(nic_op, int):
9925
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
9926
        if not isinstance(nic_dict, dict):
9927
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
9928
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
9929

    
9930
      # nic_dict should be a dict
9931
      nic_ip = nic_dict.get(constants.INIC_IP, None)
9932
      if nic_ip is not None:
9933
        if nic_ip.lower() == constants.VALUE_NONE:
9934
          nic_dict[constants.INIC_IP] = None
9935
        else:
9936
          if not netutils.IPAddress.IsValid(nic_ip):
9937
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
9938
                                       errors.ECODE_INVAL)
9939

    
9940
      nic_bridge = nic_dict.get('bridge', None)
9941
      nic_link = nic_dict.get(constants.INIC_LINK, None)
9942
      if nic_bridge and nic_link:
9943
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
9944
                                   " at the same time", errors.ECODE_INVAL)
9945
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
9946
        nic_dict['bridge'] = None
9947
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
9948
        nic_dict[constants.INIC_LINK] = None
9949

    
9950
      if nic_op == constants.DDM_ADD:
9951
        nic_mac = nic_dict.get(constants.INIC_MAC, None)
9952
        if nic_mac is None:
9953
          nic_dict[constants.INIC_MAC] = constants.VALUE_AUTO
9954

    
9955
      if constants.INIC_MAC in nic_dict:
9956
        nic_mac = nic_dict[constants.INIC_MAC]
9957
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9958
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
9959

    
9960
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
9961
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
9962
                                     " modifying an existing nic",
9963
                                     errors.ECODE_INVAL)
9964

    
9965
    if nic_addremove > 1:
9966
      raise errors.OpPrereqError("Only one NIC add or remove operation"
9967
                                 " supported at a time", errors.ECODE_INVAL)
9968

    
9969
  def ExpandNames(self):
9970
    self._ExpandAndLockInstance()
9971
    self.needed_locks[locking.LEVEL_NODE] = []
9972
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
9973

    
9974
  def DeclareLocks(self, level):
9975
    if level == locking.LEVEL_NODE:
9976
      self._LockInstancesNodes()
9977
      if self.op.disk_template and self.op.remote_node:
9978
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
9979
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
9980

    
9981
  def BuildHooksEnv(self):
9982
    """Build hooks env.
9983

9984
    This runs on the master, primary and secondaries.
9985

9986
    """
9987
    args = dict()
9988
    if constants.BE_MEMORY in self.be_new:
9989
      args['memory'] = self.be_new[constants.BE_MEMORY]
9990
    if constants.BE_VCPUS in self.be_new:
9991
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
9992
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
9993
    # information at all.
9994
    if self.op.nics:
9995
      args['nics'] = []
9996
      nic_override = dict(self.op.nics)
9997
      for idx, nic in enumerate(self.instance.nics):
9998
        if idx in nic_override:
9999
          this_nic_override = nic_override[idx]
10000
        else:
10001
          this_nic_override = {}
10002
        if constants.INIC_IP in this_nic_override:
10003
          ip = this_nic_override[constants.INIC_IP]
10004
        else:
10005
          ip = nic.ip
10006
        if constants.INIC_MAC in this_nic_override:
10007
          mac = this_nic_override[constants.INIC_MAC]
10008
        else:
10009
          mac = nic.mac
10010
        if idx in self.nic_pnew:
10011
          nicparams = self.nic_pnew[idx]
10012
        else:
10013
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
10014
        mode = nicparams[constants.NIC_MODE]
10015
        link = nicparams[constants.NIC_LINK]
10016
        args['nics'].append((ip, mac, mode, link))
10017
      if constants.DDM_ADD in nic_override:
10018
        ip = nic_override[constants.DDM_ADD].get(constants.INIC_IP, None)
10019
        mac = nic_override[constants.DDM_ADD][constants.INIC_MAC]
10020
        nicparams = self.nic_pnew[constants.DDM_ADD]
10021
        mode = nicparams[constants.NIC_MODE]
10022
        link = nicparams[constants.NIC_LINK]
10023
        args['nics'].append((ip, mac, mode, link))
10024
      elif constants.DDM_REMOVE in nic_override:
10025
        del args['nics'][-1]
10026

    
10027
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
10028
    if self.op.disk_template:
10029
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
10030

    
10031
    return env
10032

    
10033
  def BuildHooksNodes(self):
10034
    """Build hooks nodes.
10035

10036
    """
10037
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
10038
    return (nl, nl)
10039

    
10040
  def CheckPrereq(self):
10041
    """Check prerequisites.
10042

10043
    This only checks the instance list against the existing names.
10044

10045
    """
10046
    # checking the new params on the primary/secondary nodes
10047

    
10048
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
10049
    cluster = self.cluster = self.cfg.GetClusterInfo()
10050
    assert self.instance is not None, \
10051
      "Cannot retrieve locked instance %s" % self.op.instance_name
10052
    pnode = instance.primary_node
10053
    nodelist = list(instance.all_nodes)
10054

    
10055
    # OS change
10056
    if self.op.os_name and not self.op.force:
10057
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
10058
                      self.op.force_variant)
10059
      instance_os = self.op.os_name
10060
    else:
10061
      instance_os = instance.os
10062

    
10063
    if self.op.disk_template:
10064
      if instance.disk_template == self.op.disk_template:
10065
        raise errors.OpPrereqError("Instance already has disk template %s" %
10066
                                   instance.disk_template, errors.ECODE_INVAL)
10067

    
10068
      if (instance.disk_template,
10069
          self.op.disk_template) not in self._DISK_CONVERSIONS:
10070
        raise errors.OpPrereqError("Unsupported disk template conversion from"
10071
                                   " %s to %s" % (instance.disk_template,
10072
                                                  self.op.disk_template),
10073
                                   errors.ECODE_INVAL)
10074
      _CheckInstanceDown(self, instance, "cannot change disk template")
10075
      if self.op.disk_template in constants.DTS_INT_MIRROR:
10076
        if self.op.remote_node == pnode:
10077
          raise errors.OpPrereqError("Given new secondary node %s is the same"
10078
                                     " as the primary node of the instance" %
10079
                                     self.op.remote_node, errors.ECODE_STATE)
10080
        _CheckNodeOnline(self, self.op.remote_node)
10081
        _CheckNodeNotDrained(self, self.op.remote_node)
10082
        # FIXME: here we assume that the old instance type is DT_PLAIN
10083
        assert instance.disk_template == constants.DT_PLAIN
10084
        disks = [{constants.IDISK_SIZE: d.size,
10085
                  constants.IDISK_VG: d.logical_id[0]}
10086
                 for d in instance.disks]
10087
        required = _ComputeDiskSizePerVG(self.op.disk_template, disks)
10088
        _CheckNodesFreeDiskPerVG(self, [self.op.remote_node], required)
10089

    
10090
    # hvparams processing
10091
    if self.op.hvparams:
10092
      hv_type = instance.hypervisor
10093
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
10094
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
10095
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
10096

    
10097
      # local check
10098
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
10099
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
10100
      self.hv_new = hv_new # the new actual values
10101
      self.hv_inst = i_hvdict # the new dict (without defaults)
10102
    else:
10103
      self.hv_new = self.hv_inst = {}
10104

    
10105
    # beparams processing
10106
    if self.op.beparams:
10107
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
10108
                                   use_none=True)
10109
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
10110
      be_new = cluster.SimpleFillBE(i_bedict)
10111
      self.be_new = be_new # the new actual values
10112
      self.be_inst = i_bedict # the new dict (without defaults)
10113
    else:
10114
      self.be_new = self.be_inst = {}
10115
    be_old = cluster.FillBE(instance)
10116

    
10117
    # osparams processing
10118
    if self.op.osparams:
10119
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
10120
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
10121
      self.os_inst = i_osdict # the new dict (without defaults)
10122
    else:
10123
      self.os_inst = {}
10124

    
10125
    self.warn = []
10126

    
10127
    if (constants.BE_MEMORY in self.op.beparams and not self.op.force and
10128
        be_new[constants.BE_MEMORY] > be_old[constants.BE_MEMORY]):
10129
      mem_check_list = [pnode]
10130
      if be_new[constants.BE_AUTO_BALANCE]:
10131
        # either we changed auto_balance to yes or it was from before
10132
        mem_check_list.extend(instance.secondary_nodes)
10133
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
10134
                                                  instance.hypervisor)
10135
      nodeinfo = self.rpc.call_node_info(mem_check_list, None,
10136
                                         instance.hypervisor)
10137
      pninfo = nodeinfo[pnode]
10138
      msg = pninfo.fail_msg
10139
      if msg:
10140
        # Assume the primary node is unreachable and go ahead
10141
        self.warn.append("Can't get info from primary node %s: %s" %
10142
                         (pnode,  msg))
10143
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
10144
        self.warn.append("Node data from primary node %s doesn't contain"
10145
                         " free memory information" % pnode)
10146
      elif instance_info.fail_msg:
10147
        self.warn.append("Can't get instance runtime information: %s" %
10148
                        instance_info.fail_msg)
10149
      else:
10150
        if instance_info.payload:
10151
          current_mem = int(instance_info.payload['memory'])
10152
        else:
10153
          # Assume instance not running
10154
          # (there is a slight race condition here, but it's not very probable,
10155
          # and we have no other way to check)
10156
          current_mem = 0
10157
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
10158
                    pninfo.payload['memory_free'])
10159
        if miss_mem > 0:
10160
          raise errors.OpPrereqError("This change will prevent the instance"
10161
                                     " from starting, due to %d MB of memory"
10162
                                     " missing on its primary node" % miss_mem,
10163
                                     errors.ECODE_NORES)
10164

    
10165
      if be_new[constants.BE_AUTO_BALANCE]:
10166
        for node, nres in nodeinfo.items():
10167
          if node not in instance.secondary_nodes:
10168
            continue
10169
          nres.Raise("Can't get info from secondary node %s" % node,
10170
                     prereq=True, ecode=errors.ECODE_STATE)
10171
          if not isinstance(nres.payload.get('memory_free', None), int):
10172
            raise errors.OpPrereqError("Secondary node %s didn't return free"
10173
                                       " memory information" % node,
10174
                                       errors.ECODE_STATE)
10175
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
10176
            raise errors.OpPrereqError("This change will prevent the instance"
10177
                                       " from failover to its secondary node"
10178
                                       " %s, due to not enough memory" % node,
10179
                                       errors.ECODE_STATE)
10180

    
10181
    # NIC processing
10182
    self.nic_pnew = {}
10183
    self.nic_pinst = {}
10184
    for nic_op, nic_dict in self.op.nics:
10185
      if nic_op == constants.DDM_REMOVE:
10186
        if not instance.nics:
10187
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
10188
                                     errors.ECODE_INVAL)
10189
        continue
10190
      if nic_op != constants.DDM_ADD:
10191
        # an existing nic
10192
        if not instance.nics:
10193
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
10194
                                     " no NICs" % nic_op,
10195
                                     errors.ECODE_INVAL)
10196
        if nic_op < 0 or nic_op >= len(instance.nics):
10197
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
10198
                                     " are 0 to %d" %
10199
                                     (nic_op, len(instance.nics) - 1),
10200
                                     errors.ECODE_INVAL)
10201
        old_nic_params = instance.nics[nic_op].nicparams
10202
        old_nic_ip = instance.nics[nic_op].ip
10203
      else:
10204
        old_nic_params = {}
10205
        old_nic_ip = None
10206

    
10207
      update_params_dict = dict([(key, nic_dict[key])
10208
                                 for key in constants.NICS_PARAMETERS
10209
                                 if key in nic_dict])
10210

    
10211
      if 'bridge' in nic_dict:
10212
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
10213

    
10214
      new_nic_params = _GetUpdatedParams(old_nic_params,
10215
                                         update_params_dict)
10216
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
10217
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
10218
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
10219
      self.nic_pinst[nic_op] = new_nic_params
10220
      self.nic_pnew[nic_op] = new_filled_nic_params
10221
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
10222

    
10223
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
10224
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
10225
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
10226
        if msg:
10227
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
10228
          if self.op.force:
10229
            self.warn.append(msg)
10230
          else:
10231
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
10232
      if new_nic_mode == constants.NIC_MODE_ROUTED:
10233
        if constants.INIC_IP in nic_dict:
10234
          nic_ip = nic_dict[constants.INIC_IP]
10235
        else:
10236
          nic_ip = old_nic_ip
10237
        if nic_ip is None:
10238
          raise errors.OpPrereqError('Cannot set the nic ip to None'
10239
                                     ' on a routed nic', errors.ECODE_INVAL)
10240
      if constants.INIC_MAC in nic_dict:
10241
        nic_mac = nic_dict[constants.INIC_MAC]
10242
        if nic_mac is None:
10243
          raise errors.OpPrereqError('Cannot set the nic mac to None',
10244
                                     errors.ECODE_INVAL)
10245
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
10246
          # otherwise generate the mac
10247
          nic_dict[constants.INIC_MAC] = \
10248
            self.cfg.GenerateMAC(self.proc.GetECId())
10249
        else:
10250
          # or validate/reserve the current one
10251
          try:
10252
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
10253
          except errors.ReservationError:
10254
            raise errors.OpPrereqError("MAC address %s already in use"
10255
                                       " in cluster" % nic_mac,
10256
                                       errors.ECODE_NOTUNIQUE)
10257

    
10258
    # DISK processing
10259
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
10260
      raise errors.OpPrereqError("Disk operations not supported for"
10261
                                 " diskless instances",
10262
                                 errors.ECODE_INVAL)
10263
    for disk_op, _ in self.op.disks:
10264
      if disk_op == constants.DDM_REMOVE:
10265
        if len(instance.disks) == 1:
10266
          raise errors.OpPrereqError("Cannot remove the last disk of"
10267
                                     " an instance", errors.ECODE_INVAL)
10268
        _CheckInstanceDown(self, instance, "cannot remove disks")
10269

    
10270
      if (disk_op == constants.DDM_ADD and
10271
          len(instance.disks) >= constants.MAX_DISKS):
10272
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
10273
                                   " add more" % constants.MAX_DISKS,
10274
                                   errors.ECODE_STATE)
10275
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
10276
        # an existing disk
10277
        if disk_op < 0 or disk_op >= len(instance.disks):
10278
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
10279
                                     " are 0 to %d" %
10280
                                     (disk_op, len(instance.disks)),
10281
                                     errors.ECODE_INVAL)
10282

    
10283
    return
10284

    
10285
  def _ConvertPlainToDrbd(self, feedback_fn):
10286
    """Converts an instance from plain to drbd.
10287

10288
    """
10289
    feedback_fn("Converting template to drbd")
10290
    instance = self.instance
10291
    pnode = instance.primary_node
10292
    snode = self.op.remote_node
10293

    
10294
    # create a fake disk info for _GenerateDiskTemplate
10295
    disk_info = [{constants.IDISK_SIZE: d.size, constants.IDISK_MODE: d.mode,
10296
                  constants.IDISK_VG: d.logical_id[0]}
10297
                 for d in instance.disks]
10298
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
10299
                                      instance.name, pnode, [snode],
10300
                                      disk_info, None, None, 0, feedback_fn)
10301
    info = _GetInstanceInfoText(instance)
10302
    feedback_fn("Creating aditional volumes...")
10303
    # first, create the missing data and meta devices
10304
    for disk in new_disks:
10305
      # unfortunately this is... not too nice
10306
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
10307
                            info, True)
10308
      for child in disk.children:
10309
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
10310
    # at this stage, all new LVs have been created, we can rename the
10311
    # old ones
10312
    feedback_fn("Renaming original volumes...")
10313
    rename_list = [(o, n.children[0].logical_id)
10314
                   for (o, n) in zip(instance.disks, new_disks)]
10315
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
10316
    result.Raise("Failed to rename original LVs")
10317

    
10318
    feedback_fn("Initializing DRBD devices...")
10319
    # all child devices are in place, we can now create the DRBD devices
10320
    for disk in new_disks:
10321
      for node in [pnode, snode]:
10322
        f_create = node == pnode
10323
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
10324

    
10325
    # at this point, the instance has been modified
10326
    instance.disk_template = constants.DT_DRBD8
10327
    instance.disks = new_disks
10328
    self.cfg.Update(instance, feedback_fn)
10329

    
10330
    # disks are created, waiting for sync
10331
    disk_abort = not _WaitForSync(self, instance,
10332
                                  oneshot=not self.op.wait_for_sync)
10333
    if disk_abort:
10334
      raise errors.OpExecError("There are some degraded disks for"
10335
                               " this instance, please cleanup manually")
10336

    
10337
  def _ConvertDrbdToPlain(self, feedback_fn):
10338
    """Converts an instance from drbd to plain.
10339

10340
    """
10341
    instance = self.instance
10342
    assert len(instance.secondary_nodes) == 1
10343
    pnode = instance.primary_node
10344
    snode = instance.secondary_nodes[0]
10345
    feedback_fn("Converting template to plain")
10346

    
10347
    old_disks = instance.disks
10348
    new_disks = [d.children[0] for d in old_disks]
10349

    
10350
    # copy over size and mode
10351
    for parent, child in zip(old_disks, new_disks):
10352
      child.size = parent.size
10353
      child.mode = parent.mode
10354

    
10355
    # update instance structure
10356
    instance.disks = new_disks
10357
    instance.disk_template = constants.DT_PLAIN
10358
    self.cfg.Update(instance, feedback_fn)
10359

    
10360
    feedback_fn("Removing volumes on the secondary node...")
10361
    for disk in old_disks:
10362
      self.cfg.SetDiskID(disk, snode)
10363
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
10364
      if msg:
10365
        self.LogWarning("Could not remove block device %s on node %s,"
10366
                        " continuing anyway: %s", disk.iv_name, snode, msg)
10367

    
10368
    feedback_fn("Removing unneeded volumes on the primary node...")
10369
    for idx, disk in enumerate(old_disks):
10370
      meta = disk.children[1]
10371
      self.cfg.SetDiskID(meta, pnode)
10372
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
10373
      if msg:
10374
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
10375
                        " continuing anyway: %s", idx, pnode, msg)
10376

    
10377
  def Exec(self, feedback_fn):
10378
    """Modifies an instance.
10379

10380
    All parameters take effect only at the next restart of the instance.
10381

10382
    """
10383
    # Process here the warnings from CheckPrereq, as we don't have a
10384
    # feedback_fn there.
10385
    for warn in self.warn:
10386
      feedback_fn("WARNING: %s" % warn)
10387

    
10388
    result = []
10389
    instance = self.instance
10390
    # disk changes
10391
    for disk_op, disk_dict in self.op.disks:
10392
      if disk_op == constants.DDM_REMOVE:
10393
        # remove the last disk
10394
        device = instance.disks.pop()
10395
        device_idx = len(instance.disks)
10396
        for node, disk in device.ComputeNodeTree(instance.primary_node):
10397
          self.cfg.SetDiskID(disk, node)
10398
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
10399
          if msg:
10400
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
10401
                            " continuing anyway", device_idx, node, msg)
10402
        result.append(("disk/%d" % device_idx, "remove"))
10403
      elif disk_op == constants.DDM_ADD:
10404
        # add a new disk
10405
        if instance.disk_template in (constants.DT_FILE,
10406
                                        constants.DT_SHARED_FILE):
10407
          file_driver, file_path = instance.disks[0].logical_id
10408
          file_path = os.path.dirname(file_path)
10409
        else:
10410
          file_driver = file_path = None
10411
        disk_idx_base = len(instance.disks)
10412
        new_disk = _GenerateDiskTemplate(self,
10413
                                         instance.disk_template,
10414
                                         instance.name, instance.primary_node,
10415
                                         instance.secondary_nodes,
10416
                                         [disk_dict],
10417
                                         file_path,
10418
                                         file_driver,
10419
                                         disk_idx_base, feedback_fn)[0]
10420
        instance.disks.append(new_disk)
10421
        info = _GetInstanceInfoText(instance)
10422

    
10423
        logging.info("Creating volume %s for instance %s",
10424
                     new_disk.iv_name, instance.name)
10425
        # Note: this needs to be kept in sync with _CreateDisks
10426
        #HARDCODE
10427
        for node in instance.all_nodes:
10428
          f_create = node == instance.primary_node
10429
          try:
10430
            _CreateBlockDev(self, node, instance, new_disk,
10431
                            f_create, info, f_create)
10432
          except errors.OpExecError, err:
10433
            self.LogWarning("Failed to create volume %s (%s) on"
10434
                            " node %s: %s",
10435
                            new_disk.iv_name, new_disk, node, err)
10436
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
10437
                       (new_disk.size, new_disk.mode)))
10438
      else:
10439
        # change a given disk
10440
        instance.disks[disk_op].mode = disk_dict[constants.IDISK_MODE]
10441
        result.append(("disk.mode/%d" % disk_op,
10442
                       disk_dict[constants.IDISK_MODE]))
10443

    
10444
    if self.op.disk_template:
10445
      r_shut = _ShutdownInstanceDisks(self, instance)
10446
      if not r_shut:
10447
        raise errors.OpExecError("Cannot shutdown instance disks, unable to"
10448
                                 " proceed with disk template conversion")
10449
      mode = (instance.disk_template, self.op.disk_template)
10450
      try:
10451
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
10452
      except:
10453
        self.cfg.ReleaseDRBDMinors(instance.name)
10454
        raise
10455
      result.append(("disk_template", self.op.disk_template))
10456

    
10457
    # NIC changes
10458
    for nic_op, nic_dict in self.op.nics:
10459
      if nic_op == constants.DDM_REMOVE:
10460
        # remove the last nic
10461
        del instance.nics[-1]
10462
        result.append(("nic.%d" % len(instance.nics), "remove"))
10463
      elif nic_op == constants.DDM_ADD:
10464
        # mac and bridge should be set, by now
10465
        mac = nic_dict[constants.INIC_MAC]
10466
        ip = nic_dict.get(constants.INIC_IP, None)
10467
        nicparams = self.nic_pinst[constants.DDM_ADD]
10468
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
10469
        instance.nics.append(new_nic)
10470
        result.append(("nic.%d" % (len(instance.nics) - 1),
10471
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
10472
                       (new_nic.mac, new_nic.ip,
10473
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
10474
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
10475
                       )))
10476
      else:
10477
        for key in (constants.INIC_MAC, constants.INIC_IP):
10478
          if key in nic_dict:
10479
            setattr(instance.nics[nic_op], key, nic_dict[key])
10480
        if nic_op in self.nic_pinst:
10481
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
10482
        for key, val in nic_dict.iteritems():
10483
          result.append(("nic.%s/%d" % (key, nic_op), val))
10484

    
10485
    # hvparams changes
10486
    if self.op.hvparams:
10487
      instance.hvparams = self.hv_inst
10488
      for key, val in self.op.hvparams.iteritems():
10489
        result.append(("hv/%s" % key, val))
10490

    
10491
    # beparams changes
10492
    if self.op.beparams:
10493
      instance.beparams = self.be_inst
10494
      for key, val in self.op.beparams.iteritems():
10495
        result.append(("be/%s" % key, val))
10496

    
10497
    # OS change
10498
    if self.op.os_name:
10499
      instance.os = self.op.os_name
10500

    
10501
    # osparams changes
10502
    if self.op.osparams:
10503
      instance.osparams = self.os_inst
10504
      for key, val in self.op.osparams.iteritems():
10505
        result.append(("os/%s" % key, val))
10506

    
10507
    self.cfg.Update(instance, feedback_fn)
10508

    
10509
    return result
10510

    
10511
  _DISK_CONVERSIONS = {
10512
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
10513
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
10514
    }
10515

    
10516

    
10517
class LUBackupQuery(NoHooksLU):
10518
  """Query the exports list
10519

10520
  """
10521
  REQ_BGL = False
10522

    
10523
  def ExpandNames(self):
10524
    self.needed_locks = {}
10525
    self.share_locks[locking.LEVEL_NODE] = 1
10526
    if not self.op.nodes:
10527
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10528
    else:
10529
      self.needed_locks[locking.LEVEL_NODE] = \
10530
        _GetWantedNodes(self, self.op.nodes)
10531

    
10532
  def Exec(self, feedback_fn):
10533
    """Compute the list of all the exported system images.
10534

10535
    @rtype: dict
10536
    @return: a dictionary with the structure node->(export-list)
10537
        where export-list is a list of the instances exported on
10538
        that node.
10539

10540
    """
10541
    self.nodes = self.glm.list_owned(locking.LEVEL_NODE)
10542
    rpcresult = self.rpc.call_export_list(self.nodes)
10543
    result = {}
10544
    for node in rpcresult:
10545
      if rpcresult[node].fail_msg:
10546
        result[node] = False
10547
      else:
10548
        result[node] = rpcresult[node].payload
10549

    
10550
    return result
10551

    
10552

    
10553
class LUBackupPrepare(NoHooksLU):
10554
  """Prepares an instance for an export and returns useful information.
10555

10556
  """
10557
  REQ_BGL = False
10558

    
10559
  def ExpandNames(self):
10560
    self._ExpandAndLockInstance()
10561

    
10562
  def CheckPrereq(self):
10563
    """Check prerequisites.
10564

10565
    """
10566
    instance_name = self.op.instance_name
10567

    
10568
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10569
    assert self.instance is not None, \
10570
          "Cannot retrieve locked instance %s" % self.op.instance_name
10571
    _CheckNodeOnline(self, self.instance.primary_node)
10572

    
10573
    self._cds = _GetClusterDomainSecret()
10574

    
10575
  def Exec(self, feedback_fn):
10576
    """Prepares an instance for an export.
10577

10578
    """
10579
    instance = self.instance
10580

    
10581
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10582
      salt = utils.GenerateSecret(8)
10583

    
10584
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
10585
      result = self.rpc.call_x509_cert_create(instance.primary_node,
10586
                                              constants.RIE_CERT_VALIDITY)
10587
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
10588

    
10589
      (name, cert_pem) = result.payload
10590

    
10591
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
10592
                                             cert_pem)
10593

    
10594
      return {
10595
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
10596
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
10597
                          salt),
10598
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
10599
        }
10600

    
10601
    return None
10602

    
10603

    
10604
class LUBackupExport(LogicalUnit):
10605
  """Export an instance to an image in the cluster.
10606

10607
  """
10608
  HPATH = "instance-export"
10609
  HTYPE = constants.HTYPE_INSTANCE
10610
  REQ_BGL = False
10611

    
10612
  def CheckArguments(self):
10613
    """Check the arguments.
10614

10615
    """
10616
    self.x509_key_name = self.op.x509_key_name
10617
    self.dest_x509_ca_pem = self.op.destination_x509_ca
10618

    
10619
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
10620
      if not self.x509_key_name:
10621
        raise errors.OpPrereqError("Missing X509 key name for encryption",
10622
                                   errors.ECODE_INVAL)
10623

    
10624
      if not self.dest_x509_ca_pem:
10625
        raise errors.OpPrereqError("Missing destination X509 CA",
10626
                                   errors.ECODE_INVAL)
10627

    
10628
  def ExpandNames(self):
10629
    self._ExpandAndLockInstance()
10630

    
10631
    # Lock all nodes for local exports
10632
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10633
      # FIXME: lock only instance primary and destination node
10634
      #
10635
      # Sad but true, for now we have do lock all nodes, as we don't know where
10636
      # the previous export might be, and in this LU we search for it and
10637
      # remove it from its current node. In the future we could fix this by:
10638
      #  - making a tasklet to search (share-lock all), then create the
10639
      #    new one, then one to remove, after
10640
      #  - removing the removal operation altogether
10641
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10642

    
10643
  def DeclareLocks(self, level):
10644
    """Last minute lock declaration."""
10645
    # All nodes are locked anyway, so nothing to do here.
10646

    
10647
  def BuildHooksEnv(self):
10648
    """Build hooks env.
10649

10650
    This will run on the master, primary node and target node.
10651

10652
    """
10653
    env = {
10654
      "EXPORT_MODE": self.op.mode,
10655
      "EXPORT_NODE": self.op.target_node,
10656
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
10657
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
10658
      # TODO: Generic function for boolean env variables
10659
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
10660
      }
10661

    
10662
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
10663

    
10664
    return env
10665

    
10666
  def BuildHooksNodes(self):
10667
    """Build hooks nodes.
10668

10669
    """
10670
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
10671

    
10672
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10673
      nl.append(self.op.target_node)
10674

    
10675
    return (nl, nl)
10676

    
10677
  def CheckPrereq(self):
10678
    """Check prerequisites.
10679

10680
    This checks that the instance and node names are valid.
10681

10682
    """
10683
    instance_name = self.op.instance_name
10684

    
10685
    self.instance = self.cfg.GetInstanceInfo(instance_name)
10686
    assert self.instance is not None, \
10687
          "Cannot retrieve locked instance %s" % self.op.instance_name
10688
    _CheckNodeOnline(self, self.instance.primary_node)
10689

    
10690
    if (self.op.remove_instance and self.instance.admin_up and
10691
        not self.op.shutdown):
10692
      raise errors.OpPrereqError("Can not remove instance without shutting it"
10693
                                 " down before")
10694

    
10695
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10696
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
10697
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
10698
      assert self.dst_node is not None
10699

    
10700
      _CheckNodeOnline(self, self.dst_node.name)
10701
      _CheckNodeNotDrained(self, self.dst_node.name)
10702

    
10703
      self._cds = None
10704
      self.dest_disk_info = None
10705
      self.dest_x509_ca = None
10706

    
10707
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10708
      self.dst_node = None
10709

    
10710
      if len(self.op.target_node) != len(self.instance.disks):
10711
        raise errors.OpPrereqError(("Received destination information for %s"
10712
                                    " disks, but instance %s has %s disks") %
10713
                                   (len(self.op.target_node), instance_name,
10714
                                    len(self.instance.disks)),
10715
                                   errors.ECODE_INVAL)
10716

    
10717
      cds = _GetClusterDomainSecret()
10718

    
10719
      # Check X509 key name
10720
      try:
10721
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
10722
      except (TypeError, ValueError), err:
10723
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
10724

    
10725
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
10726
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
10727
                                   errors.ECODE_INVAL)
10728

    
10729
      # Load and verify CA
10730
      try:
10731
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
10732
      except OpenSSL.crypto.Error, err:
10733
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
10734
                                   (err, ), errors.ECODE_INVAL)
10735

    
10736
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
10737
      if errcode is not None:
10738
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
10739
                                   (msg, ), errors.ECODE_INVAL)
10740

    
10741
      self.dest_x509_ca = cert
10742

    
10743
      # Verify target information
10744
      disk_info = []
10745
      for idx, disk_data in enumerate(self.op.target_node):
10746
        try:
10747
          (host, port, magic) = \
10748
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
10749
        except errors.GenericError, err:
10750
          raise errors.OpPrereqError("Target info for disk %s: %s" %
10751
                                     (idx, err), errors.ECODE_INVAL)
10752

    
10753
        disk_info.append((host, port, magic))
10754

    
10755
      assert len(disk_info) == len(self.op.target_node)
10756
      self.dest_disk_info = disk_info
10757

    
10758
    else:
10759
      raise errors.ProgrammerError("Unhandled export mode %r" %
10760
                                   self.op.mode)
10761

    
10762
    # instance disk type verification
10763
    # TODO: Implement export support for file-based disks
10764
    for disk in self.instance.disks:
10765
      if disk.dev_type == constants.LD_FILE:
10766
        raise errors.OpPrereqError("Export not supported for instances with"
10767
                                   " file-based disks", errors.ECODE_INVAL)
10768

    
10769
  def _CleanupExports(self, feedback_fn):
10770
    """Removes exports of current instance from all other nodes.
10771

10772
    If an instance in a cluster with nodes A..D was exported to node C, its
10773
    exports will be removed from the nodes A, B and D.
10774

10775
    """
10776
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
10777

    
10778
    nodelist = self.cfg.GetNodeList()
10779
    nodelist.remove(self.dst_node.name)
10780

    
10781
    # on one-node clusters nodelist will be empty after the removal
10782
    # if we proceed the backup would be removed because OpBackupQuery
10783
    # substitutes an empty list with the full cluster node list.
10784
    iname = self.instance.name
10785
    if nodelist:
10786
      feedback_fn("Removing old exports for instance %s" % iname)
10787
      exportlist = self.rpc.call_export_list(nodelist)
10788
      for node in exportlist:
10789
        if exportlist[node].fail_msg:
10790
          continue
10791
        if iname in exportlist[node].payload:
10792
          msg = self.rpc.call_export_remove(node, iname).fail_msg
10793
          if msg:
10794
            self.LogWarning("Could not remove older export for instance %s"
10795
                            " on node %s: %s", iname, node, msg)
10796

    
10797
  def Exec(self, feedback_fn):
10798
    """Export an instance to an image in the cluster.
10799

10800
    """
10801
    assert self.op.mode in constants.EXPORT_MODES
10802

    
10803
    instance = self.instance
10804
    src_node = instance.primary_node
10805

    
10806
    if self.op.shutdown:
10807
      # shutdown the instance, but not the disks
10808
      feedback_fn("Shutting down instance %s" % instance.name)
10809
      result = self.rpc.call_instance_shutdown(src_node, instance,
10810
                                               self.op.shutdown_timeout)
10811
      # TODO: Maybe ignore failures if ignore_remove_failures is set
10812
      result.Raise("Could not shutdown instance %s on"
10813
                   " node %s" % (instance.name, src_node))
10814

    
10815
    # set the disks ID correctly since call_instance_start needs the
10816
    # correct drbd minor to create the symlinks
10817
    for disk in instance.disks:
10818
      self.cfg.SetDiskID(disk, src_node)
10819

    
10820
    activate_disks = (not instance.admin_up)
10821

    
10822
    if activate_disks:
10823
      # Activate the instance disks if we'exporting a stopped instance
10824
      feedback_fn("Activating disks for %s" % instance.name)
10825
      _StartInstanceDisks(self, instance, None)
10826

    
10827
    try:
10828
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
10829
                                                     instance)
10830

    
10831
      helper.CreateSnapshots()
10832
      try:
10833
        if (self.op.shutdown and instance.admin_up and
10834
            not self.op.remove_instance):
10835
          assert not activate_disks
10836
          feedback_fn("Starting instance %s" % instance.name)
10837
          result = self.rpc.call_instance_start(src_node, instance, None, None)
10838
          msg = result.fail_msg
10839
          if msg:
10840
            feedback_fn("Failed to start instance: %s" % msg)
10841
            _ShutdownInstanceDisks(self, instance)
10842
            raise errors.OpExecError("Could not start instance: %s" % msg)
10843

    
10844
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
10845
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
10846
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
10847
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
10848
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
10849

    
10850
          (key_name, _, _) = self.x509_key_name
10851

    
10852
          dest_ca_pem = \
10853
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
10854
                                            self.dest_x509_ca)
10855

    
10856
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
10857
                                                     key_name, dest_ca_pem,
10858
                                                     timeouts)
10859
      finally:
10860
        helper.Cleanup()
10861

    
10862
      # Check for backwards compatibility
10863
      assert len(dresults) == len(instance.disks)
10864
      assert compat.all(isinstance(i, bool) for i in dresults), \
10865
             "Not all results are boolean: %r" % dresults
10866

    
10867
    finally:
10868
      if activate_disks:
10869
        feedback_fn("Deactivating disks for %s" % instance.name)
10870
        _ShutdownInstanceDisks(self, instance)
10871

    
10872
    if not (compat.all(dresults) and fin_resu):
10873
      failures = []
10874
      if not fin_resu:
10875
        failures.append("export finalization")
10876
      if not compat.all(dresults):
10877
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
10878
                               if not dsk)
10879
        failures.append("disk export: disk(s) %s" % fdsk)
10880

    
10881
      raise errors.OpExecError("Export failed, errors in %s" %
10882
                               utils.CommaJoin(failures))
10883

    
10884
    # At this point, the export was successful, we can cleanup/finish
10885

    
10886
    # Remove instance if requested
10887
    if self.op.remove_instance:
10888
      feedback_fn("Removing instance %s" % instance.name)
10889
      _RemoveInstance(self, feedback_fn, instance,
10890
                      self.op.ignore_remove_failures)
10891

    
10892
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
10893
      self._CleanupExports(feedback_fn)
10894

    
10895
    return fin_resu, dresults
10896

    
10897

    
10898
class LUBackupRemove(NoHooksLU):
10899
  """Remove exports related to the named instance.
10900

10901
  """
10902
  REQ_BGL = False
10903

    
10904
  def ExpandNames(self):
10905
    self.needed_locks = {}
10906
    # We need all nodes to be locked in order for RemoveExport to work, but we
10907
    # don't need to lock the instance itself, as nothing will happen to it (and
10908
    # we can remove exports also for a removed instance)
10909
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
10910

    
10911
  def Exec(self, feedback_fn):
10912
    """Remove any export.
10913

10914
    """
10915
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
10916
    # If the instance was not found we'll try with the name that was passed in.
10917
    # This will only work if it was an FQDN, though.
10918
    fqdn_warn = False
10919
    if not instance_name:
10920
      fqdn_warn = True
10921
      instance_name = self.op.instance_name
10922

    
10923
    locked_nodes = self.glm.list_owned(locking.LEVEL_NODE)
10924
    exportlist = self.rpc.call_export_list(locked_nodes)
10925
    found = False
10926
    for node in exportlist:
10927
      msg = exportlist[node].fail_msg
10928
      if msg:
10929
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
10930
        continue
10931
      if instance_name in exportlist[node].payload:
10932
        found = True
10933
        result = self.rpc.call_export_remove(node, instance_name)
10934
        msg = result.fail_msg
10935
        if msg:
10936
          logging.error("Could not remove export for instance %s"
10937
                        " on node %s: %s", instance_name, node, msg)
10938

    
10939
    if fqdn_warn and not found:
10940
      feedback_fn("Export not found. If trying to remove an export belonging"
10941
                  " to a deleted instance please use its Fully Qualified"
10942
                  " Domain Name.")
10943

    
10944

    
10945
class LUGroupAdd(LogicalUnit):
10946
  """Logical unit for creating node groups.
10947

10948
  """
10949
  HPATH = "group-add"
10950
  HTYPE = constants.HTYPE_GROUP
10951
  REQ_BGL = False
10952

    
10953
  def ExpandNames(self):
10954
    # We need the new group's UUID here so that we can create and acquire the
10955
    # corresponding lock. Later, in Exec(), we'll indicate to cfg.AddNodeGroup
10956
    # that it should not check whether the UUID exists in the configuration.
10957
    self.group_uuid = self.cfg.GenerateUniqueID(self.proc.GetECId())
10958
    self.needed_locks = {}
10959
    self.add_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
10960

    
10961
  def CheckPrereq(self):
10962
    """Check prerequisites.
10963

10964
    This checks that the given group name is not an existing node group
10965
    already.
10966

10967
    """
10968
    try:
10969
      existing_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
10970
    except errors.OpPrereqError:
10971
      pass
10972
    else:
10973
      raise errors.OpPrereqError("Desired group name '%s' already exists as a"
10974
                                 " node group (UUID: %s)" %
10975
                                 (self.op.group_name, existing_uuid),
10976
                                 errors.ECODE_EXISTS)
10977

    
10978
    if self.op.ndparams:
10979
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
10980

    
10981
  def BuildHooksEnv(self):
10982
    """Build hooks env.
10983

10984
    """
10985
    return {
10986
      "GROUP_NAME": self.op.group_name,
10987
      }
10988

    
10989
  def BuildHooksNodes(self):
10990
    """Build hooks nodes.
10991

10992
    """
10993
    mn = self.cfg.GetMasterNode()
10994
    return ([mn], [mn])
10995

    
10996
  def Exec(self, feedback_fn):
10997
    """Add the node group to the cluster.
10998

10999
    """
11000
    group_obj = objects.NodeGroup(name=self.op.group_name, members=[],
11001
                                  uuid=self.group_uuid,
11002
                                  alloc_policy=self.op.alloc_policy,
11003
                                  ndparams=self.op.ndparams)
11004

    
11005
    self.cfg.AddNodeGroup(group_obj, self.proc.GetECId(), check_uuid=False)
11006
    del self.remove_locks[locking.LEVEL_NODEGROUP]
11007

    
11008

    
11009
class LUGroupAssignNodes(NoHooksLU):
11010
  """Logical unit for assigning nodes to groups.
11011

11012
  """
11013
  REQ_BGL = False
11014

    
11015
  def ExpandNames(self):
11016
    # These raise errors.OpPrereqError on their own:
11017
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11018
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
11019

    
11020
    # We want to lock all the affected nodes and groups. We have readily
11021
    # available the list of nodes, and the *destination* group. To gather the
11022
    # list of "source" groups, we need to fetch node information later on.
11023
    self.needed_locks = {
11024
      locking.LEVEL_NODEGROUP: set([self.group_uuid]),
11025
      locking.LEVEL_NODE: self.op.nodes,
11026
      }
11027

    
11028
  def DeclareLocks(self, level):
11029
    if level == locking.LEVEL_NODEGROUP:
11030
      assert len(self.needed_locks[locking.LEVEL_NODEGROUP]) == 1
11031

    
11032
      # Try to get all affected nodes' groups without having the group or node
11033
      # lock yet. Needs verification later in the code flow.
11034
      groups = self.cfg.GetNodeGroupsFromNodes(self.op.nodes)
11035

    
11036
      self.needed_locks[locking.LEVEL_NODEGROUP].update(groups)
11037

    
11038
  def CheckPrereq(self):
11039
    """Check prerequisites.
11040

11041
    """
11042
    assert self.needed_locks[locking.LEVEL_NODEGROUP]
11043
    assert (frozenset(self.glm.list_owned(locking.LEVEL_NODE)) ==
11044
            frozenset(self.op.nodes))
11045

    
11046
    expected_locks = (set([self.group_uuid]) |
11047
                      self.cfg.GetNodeGroupsFromNodes(self.op.nodes))
11048
    actual_locks = self.glm.list_owned(locking.LEVEL_NODEGROUP)
11049
    if actual_locks != expected_locks:
11050
      raise errors.OpExecError("Nodes changed groups since locks were acquired,"
11051
                               " current groups are '%s', used to be '%s'" %
11052
                               (utils.CommaJoin(expected_locks),
11053
                                utils.CommaJoin(actual_locks)))
11054

    
11055
    self.node_data = self.cfg.GetAllNodesInfo()
11056
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11057
    instance_data = self.cfg.GetAllInstancesInfo()
11058

    
11059
    if self.group is None:
11060
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11061
                               (self.op.group_name, self.group_uuid))
11062

    
11063
    (new_splits, previous_splits) = \
11064
      self.CheckAssignmentForSplitInstances([(node, self.group_uuid)
11065
                                             for node in self.op.nodes],
11066
                                            self.node_data, instance_data)
11067

    
11068
    if new_splits:
11069
      fmt_new_splits = utils.CommaJoin(utils.NiceSort(new_splits))
11070

    
11071
      if not self.op.force:
11072
        raise errors.OpExecError("The following instances get split by this"
11073
                                 " change and --force was not given: %s" %
11074
                                 fmt_new_splits)
11075
      else:
11076
        self.LogWarning("This operation will split the following instances: %s",
11077
                        fmt_new_splits)
11078

    
11079
        if previous_splits:
11080
          self.LogWarning("In addition, these already-split instances continue"
11081
                          " to be split across groups: %s",
11082
                          utils.CommaJoin(utils.NiceSort(previous_splits)))
11083

    
11084
  def Exec(self, feedback_fn):
11085
    """Assign nodes to a new group.
11086

11087
    """
11088
    for node in self.op.nodes:
11089
      self.node_data[node].group = self.group_uuid
11090

    
11091
    # FIXME: Depends on side-effects of modifying the result of
11092
    # C{cfg.GetAllNodesInfo}
11093

    
11094
    self.cfg.Update(self.group, feedback_fn) # Saves all modified nodes.
11095

    
11096
  @staticmethod
11097
  def CheckAssignmentForSplitInstances(changes, node_data, instance_data):
11098
    """Check for split instances after a node assignment.
11099

11100
    This method considers a series of node assignments as an atomic operation,
11101
    and returns information about split instances after applying the set of
11102
    changes.
11103

11104
    In particular, it returns information about newly split instances, and
11105
    instances that were already split, and remain so after the change.
11106

11107
    Only instances whose disk template is listed in constants.DTS_INT_MIRROR are
11108
    considered.
11109

11110
    @type changes: list of (node_name, new_group_uuid) pairs.
11111
    @param changes: list of node assignments to consider.
11112
    @param node_data: a dict with data for all nodes
11113
    @param instance_data: a dict with all instances to consider
11114
    @rtype: a two-tuple
11115
    @return: a list of instances that were previously okay and result split as a
11116
      consequence of this change, and a list of instances that were previously
11117
      split and this change does not fix.
11118

11119
    """
11120
    changed_nodes = dict((node, group) for node, group in changes
11121
                         if node_data[node].group != group)
11122

    
11123
    all_split_instances = set()
11124
    previously_split_instances = set()
11125

    
11126
    def InstanceNodes(instance):
11127
      return [instance.primary_node] + list(instance.secondary_nodes)
11128

    
11129
    for inst in instance_data.values():
11130
      if inst.disk_template not in constants.DTS_INT_MIRROR:
11131
        continue
11132

    
11133
      instance_nodes = InstanceNodes(inst)
11134

    
11135
      if len(set(node_data[node].group for node in instance_nodes)) > 1:
11136
        previously_split_instances.add(inst.name)
11137

    
11138
      if len(set(changed_nodes.get(node, node_data[node].group)
11139
                 for node in instance_nodes)) > 1:
11140
        all_split_instances.add(inst.name)
11141

    
11142
    return (list(all_split_instances - previously_split_instances),
11143
            list(previously_split_instances & all_split_instances))
11144

    
11145

    
11146
class _GroupQuery(_QueryBase):
11147
  FIELDS = query.GROUP_FIELDS
11148

    
11149
  def ExpandNames(self, lu):
11150
    lu.needed_locks = {}
11151

    
11152
    self._all_groups = lu.cfg.GetAllNodeGroupsInfo()
11153
    name_to_uuid = dict((g.name, g.uuid) for g in self._all_groups.values())
11154

    
11155
    if not self.names:
11156
      self.wanted = [name_to_uuid[name]
11157
                     for name in utils.NiceSort(name_to_uuid.keys())]
11158
    else:
11159
      # Accept names to be either names or UUIDs.
11160
      missing = []
11161
      self.wanted = []
11162
      all_uuid = frozenset(self._all_groups.keys())
11163

    
11164
      for name in self.names:
11165
        if name in all_uuid:
11166
          self.wanted.append(name)
11167
        elif name in name_to_uuid:
11168
          self.wanted.append(name_to_uuid[name])
11169
        else:
11170
          missing.append(name)
11171

    
11172
      if missing:
11173
        raise errors.OpPrereqError("Some groups do not exist: %s" %
11174
                                   utils.CommaJoin(missing),
11175
                                   errors.ECODE_NOENT)
11176

    
11177
  def DeclareLocks(self, lu, level):
11178
    pass
11179

    
11180
  def _GetQueryData(self, lu):
11181
    """Computes the list of node groups and their attributes.
11182

11183
    """
11184
    do_nodes = query.GQ_NODE in self.requested_data
11185
    do_instances = query.GQ_INST in self.requested_data
11186

    
11187
    group_to_nodes = None
11188
    group_to_instances = None
11189

    
11190
    # For GQ_NODE, we need to map group->[nodes], and group->[instances] for
11191
    # GQ_INST. The former is attainable with just GetAllNodesInfo(), but for the
11192
    # latter GetAllInstancesInfo() is not enough, for we have to go through
11193
    # instance->node. Hence, we will need to process nodes even if we only need
11194
    # instance information.
11195
    if do_nodes or do_instances:
11196
      all_nodes = lu.cfg.GetAllNodesInfo()
11197
      group_to_nodes = dict((uuid, []) for uuid in self.wanted)
11198
      node_to_group = {}
11199

    
11200
      for node in all_nodes.values():
11201
        if node.group in group_to_nodes:
11202
          group_to_nodes[node.group].append(node.name)
11203
          node_to_group[node.name] = node.group
11204

    
11205
      if do_instances:
11206
        all_instances = lu.cfg.GetAllInstancesInfo()
11207
        group_to_instances = dict((uuid, []) for uuid in self.wanted)
11208

    
11209
        for instance in all_instances.values():
11210
          node = instance.primary_node
11211
          if node in node_to_group:
11212
            group_to_instances[node_to_group[node]].append(instance.name)
11213

    
11214
        if not do_nodes:
11215
          # Do not pass on node information if it was not requested.
11216
          group_to_nodes = None
11217

    
11218
    return query.GroupQueryData([self._all_groups[uuid]
11219
                                 for uuid in self.wanted],
11220
                                group_to_nodes, group_to_instances)
11221

    
11222

    
11223
class LUGroupQuery(NoHooksLU):
11224
  """Logical unit for querying node groups.
11225

11226
  """
11227
  REQ_BGL = False
11228

    
11229
  def CheckArguments(self):
11230
    self.gq = _GroupQuery(qlang.MakeSimpleFilter("name", self.op.names),
11231
                          self.op.output_fields, False)
11232

    
11233
  def ExpandNames(self):
11234
    self.gq.ExpandNames(self)
11235

    
11236
  def Exec(self, feedback_fn):
11237
    return self.gq.OldStyleQuery(self)
11238

    
11239

    
11240
class LUGroupSetParams(LogicalUnit):
11241
  """Modifies the parameters of a node group.
11242

11243
  """
11244
  HPATH = "group-modify"
11245
  HTYPE = constants.HTYPE_GROUP
11246
  REQ_BGL = False
11247

    
11248
  def CheckArguments(self):
11249
    all_changes = [
11250
      self.op.ndparams,
11251
      self.op.alloc_policy,
11252
      ]
11253

    
11254
    if all_changes.count(None) == len(all_changes):
11255
      raise errors.OpPrereqError("Please pass at least one modification",
11256
                                 errors.ECODE_INVAL)
11257

    
11258
  def ExpandNames(self):
11259
    # This raises errors.OpPrereqError on its own:
11260
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11261

    
11262
    self.needed_locks = {
11263
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11264
      }
11265

    
11266
  def CheckPrereq(self):
11267
    """Check prerequisites.
11268

11269
    """
11270
    self.group = self.cfg.GetNodeGroup(self.group_uuid)
11271

    
11272
    if self.group is None:
11273
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11274
                               (self.op.group_name, self.group_uuid))
11275

    
11276
    if self.op.ndparams:
11277
      new_ndparams = _GetUpdatedParams(self.group.ndparams, self.op.ndparams)
11278
      utils.ForceDictType(self.op.ndparams, constants.NDS_PARAMETER_TYPES)
11279
      self.new_ndparams = new_ndparams
11280

    
11281
  def BuildHooksEnv(self):
11282
    """Build hooks env.
11283

11284
    """
11285
    return {
11286
      "GROUP_NAME": self.op.group_name,
11287
      "NEW_ALLOC_POLICY": self.op.alloc_policy,
11288
      }
11289

    
11290
  def BuildHooksNodes(self):
11291
    """Build hooks nodes.
11292

11293
    """
11294
    mn = self.cfg.GetMasterNode()
11295
    return ([mn], [mn])
11296

    
11297
  def Exec(self, feedback_fn):
11298
    """Modifies the node group.
11299

11300
    """
11301
    result = []
11302

    
11303
    if self.op.ndparams:
11304
      self.group.ndparams = self.new_ndparams
11305
      result.append(("ndparams", str(self.group.ndparams)))
11306

    
11307
    if self.op.alloc_policy:
11308
      self.group.alloc_policy = self.op.alloc_policy
11309

    
11310
    self.cfg.Update(self.group, feedback_fn)
11311
    return result
11312

    
11313

    
11314

    
11315
class LUGroupRemove(LogicalUnit):
11316
  HPATH = "group-remove"
11317
  HTYPE = constants.HTYPE_GROUP
11318
  REQ_BGL = False
11319

    
11320
  def ExpandNames(self):
11321
    # This will raises errors.OpPrereqError on its own:
11322
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11323
    self.needed_locks = {
11324
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11325
      }
11326

    
11327
  def CheckPrereq(self):
11328
    """Check prerequisites.
11329

11330
    This checks that the given group name exists as a node group, that is
11331
    empty (i.e., contains no nodes), and that is not the last group of the
11332
    cluster.
11333

11334
    """
11335
    # Verify that the group is empty.
11336
    group_nodes = [node.name
11337
                   for node in self.cfg.GetAllNodesInfo().values()
11338
                   if node.group == self.group_uuid]
11339

    
11340
    if group_nodes:
11341
      raise errors.OpPrereqError("Group '%s' not empty, has the following"
11342
                                 " nodes: %s" %
11343
                                 (self.op.group_name,
11344
                                  utils.CommaJoin(utils.NiceSort(group_nodes))),
11345
                                 errors.ECODE_STATE)
11346

    
11347
    # Verify the cluster would not be left group-less.
11348
    if len(self.cfg.GetNodeGroupList()) == 1:
11349
      raise errors.OpPrereqError("Group '%s' is the only group,"
11350
                                 " cannot be removed" %
11351
                                 self.op.group_name,
11352
                                 errors.ECODE_STATE)
11353

    
11354
  def BuildHooksEnv(self):
11355
    """Build hooks env.
11356

11357
    """
11358
    return {
11359
      "GROUP_NAME": self.op.group_name,
11360
      }
11361

    
11362
  def BuildHooksNodes(self):
11363
    """Build hooks nodes.
11364

11365
    """
11366
    mn = self.cfg.GetMasterNode()
11367
    return ([mn], [mn])
11368

    
11369
  def Exec(self, feedback_fn):
11370
    """Remove the node group.
11371

11372
    """
11373
    try:
11374
      self.cfg.RemoveNodeGroup(self.group_uuid)
11375
    except errors.ConfigurationError:
11376
      raise errors.OpExecError("Group '%s' with UUID %s disappeared" %
11377
                               (self.op.group_name, self.group_uuid))
11378

    
11379
    self.remove_locks[locking.LEVEL_NODEGROUP] = self.group_uuid
11380

    
11381

    
11382
class LUGroupRename(LogicalUnit):
11383
  HPATH = "group-rename"
11384
  HTYPE = constants.HTYPE_GROUP
11385
  REQ_BGL = False
11386

    
11387
  def ExpandNames(self):
11388
    # This raises errors.OpPrereqError on its own:
11389
    self.group_uuid = self.cfg.LookupNodeGroup(self.op.group_name)
11390

    
11391
    self.needed_locks = {
11392
      locking.LEVEL_NODEGROUP: [self.group_uuid],
11393
      }
11394

    
11395
  def CheckPrereq(self):
11396
    """Check prerequisites.
11397

11398
    Ensures requested new name is not yet used.
11399

11400
    """
11401
    try:
11402
      new_name_uuid = self.cfg.LookupNodeGroup(self.op.new_name)
11403
    except errors.OpPrereqError:
11404
      pass
11405
    else:
11406
      raise errors.OpPrereqError("Desired new name '%s' clashes with existing"
11407
                                 " node group (UUID: %s)" %
11408
                                 (self.op.new_name, new_name_uuid),
11409
                                 errors.ECODE_EXISTS)
11410

    
11411
  def BuildHooksEnv(self):
11412
    """Build hooks env.
11413

11414
    """
11415
    return {
11416
      "OLD_NAME": self.op.group_name,
11417
      "NEW_NAME": self.op.new_name,
11418
      }
11419

    
11420
  def BuildHooksNodes(self):
11421
    """Build hooks nodes.
11422

11423
    """
11424
    mn = self.cfg.GetMasterNode()
11425

    
11426
    all_nodes = self.cfg.GetAllNodesInfo()
11427
    all_nodes.pop(mn, None)
11428

    
11429
    run_nodes = [mn]
11430
    run_nodes.extend(node.name for node in all_nodes.values()
11431
                     if node.group == self.group_uuid)
11432

    
11433
    return (run_nodes, run_nodes)
11434

    
11435
  def Exec(self, feedback_fn):
11436
    """Rename the node group.
11437

11438
    """
11439
    group = self.cfg.GetNodeGroup(self.group_uuid)
11440

    
11441
    if group is None:
11442
      raise errors.OpExecError("Could not retrieve group '%s' (UUID: %s)" %
11443
                               (self.op.group_name, self.group_uuid))
11444

    
11445
    group.name = self.op.new_name
11446
    self.cfg.Update(group, feedback_fn)
11447

    
11448
    return self.op.new_name
11449

    
11450

    
11451
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
11452
  """Generic tags LU.
11453

11454
  This is an abstract class which is the parent of all the other tags LUs.
11455

11456
  """
11457
  def ExpandNames(self):
11458
    self.group_uuid = None
11459
    self.needed_locks = {}
11460
    if self.op.kind == constants.TAG_NODE:
11461
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
11462
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
11463
    elif self.op.kind == constants.TAG_INSTANCE:
11464
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
11465
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
11466
    elif self.op.kind == constants.TAG_NODEGROUP:
11467
      self.group_uuid = self.cfg.LookupNodeGroup(self.op.name)
11468

    
11469
    # FIXME: Acquire BGL for cluster tag operations (as of this writing it's
11470
    # not possible to acquire the BGL based on opcode parameters)
11471

    
11472
  def CheckPrereq(self):
11473
    """Check prerequisites.
11474

11475
    """
11476
    if self.op.kind == constants.TAG_CLUSTER:
11477
      self.target = self.cfg.GetClusterInfo()
11478
    elif self.op.kind == constants.TAG_NODE:
11479
      self.target = self.cfg.GetNodeInfo(self.op.name)
11480
    elif self.op.kind == constants.TAG_INSTANCE:
11481
      self.target = self.cfg.GetInstanceInfo(self.op.name)
11482
    elif self.op.kind == constants.TAG_NODEGROUP:
11483
      self.target = self.cfg.GetNodeGroup(self.group_uuid)
11484
    else:
11485
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
11486
                                 str(self.op.kind), errors.ECODE_INVAL)
11487

    
11488

    
11489
class LUTagsGet(TagsLU):
11490
  """Returns the tags of a given object.
11491

11492
  """
11493
  REQ_BGL = False
11494

    
11495
  def ExpandNames(self):
11496
    TagsLU.ExpandNames(self)
11497

    
11498
    # Share locks as this is only a read operation
11499
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
11500

    
11501
  def Exec(self, feedback_fn):
11502
    """Returns the tag list.
11503

11504
    """
11505
    return list(self.target.GetTags())
11506

    
11507

    
11508
class LUTagsSearch(NoHooksLU):
11509
  """Searches the tags for a given pattern.
11510

11511
  """
11512
  REQ_BGL = False
11513

    
11514
  def ExpandNames(self):
11515
    self.needed_locks = {}
11516

    
11517
  def CheckPrereq(self):
11518
    """Check prerequisites.
11519

11520
    This checks the pattern passed for validity by compiling it.
11521

11522
    """
11523
    try:
11524
      self.re = re.compile(self.op.pattern)
11525
    except re.error, err:
11526
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
11527
                                 (self.op.pattern, err), errors.ECODE_INVAL)
11528

    
11529
  def Exec(self, feedback_fn):
11530
    """Returns the tag list.
11531

11532
    """
11533
    cfg = self.cfg
11534
    tgts = [("/cluster", cfg.GetClusterInfo())]
11535
    ilist = cfg.GetAllInstancesInfo().values()
11536
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
11537
    nlist = cfg.GetAllNodesInfo().values()
11538
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
11539
    tgts.extend(("/nodegroup/%s" % n.name, n)
11540
                for n in cfg.GetAllNodeGroupsInfo().values())
11541
    results = []
11542
    for path, target in tgts:
11543
      for tag in target.GetTags():
11544
        if self.re.search(tag):
11545
          results.append((path, tag))
11546
    return results
11547

    
11548

    
11549
class LUTagsSet(TagsLU):
11550
  """Sets a tag on a given object.
11551

11552
  """
11553
  REQ_BGL = False
11554

    
11555
  def CheckPrereq(self):
11556
    """Check prerequisites.
11557

11558
    This checks the type and length of the tag name and value.
11559

11560
    """
11561
    TagsLU.CheckPrereq(self)
11562
    for tag in self.op.tags:
11563
      objects.TaggableObject.ValidateTag(tag)
11564

    
11565
  def Exec(self, feedback_fn):
11566
    """Sets the tag.
11567

11568
    """
11569
    try:
11570
      for tag in self.op.tags:
11571
        self.target.AddTag(tag)
11572
    except errors.TagError, err:
11573
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
11574
    self.cfg.Update(self.target, feedback_fn)
11575

    
11576

    
11577
class LUTagsDel(TagsLU):
11578
  """Delete a list of tags from a given object.
11579

11580
  """
11581
  REQ_BGL = False
11582

    
11583
  def CheckPrereq(self):
11584
    """Check prerequisites.
11585

11586
    This checks that we have the given tag.
11587

11588
    """
11589
    TagsLU.CheckPrereq(self)
11590
    for tag in self.op.tags:
11591
      objects.TaggableObject.ValidateTag(tag)
11592
    del_tags = frozenset(self.op.tags)
11593
    cur_tags = self.target.GetTags()
11594

    
11595
    diff_tags = del_tags - cur_tags
11596
    if diff_tags:
11597
      diff_names = ("'%s'" % i for i in sorted(diff_tags))
11598
      raise errors.OpPrereqError("Tag(s) %s not found" %
11599
                                 (utils.CommaJoin(diff_names), ),
11600
                                 errors.ECODE_NOENT)
11601

    
11602
  def Exec(self, feedback_fn):
11603
    """Remove the tag from the object.
11604

11605
    """
11606
    for tag in self.op.tags:
11607
      self.target.RemoveTag(tag)
11608
    self.cfg.Update(self.target, feedback_fn)
11609

    
11610

    
11611
class LUTestDelay(NoHooksLU):
11612
  """Sleep for a specified amount of time.
11613

11614
  This LU sleeps on the master and/or nodes for a specified amount of
11615
  time.
11616

11617
  """
11618
  REQ_BGL = False
11619

    
11620
  def ExpandNames(self):
11621
    """Expand names and set required locks.
11622

11623
    This expands the node list, if any.
11624

11625
    """
11626
    self.needed_locks = {}
11627
    if self.op.on_nodes:
11628
      # _GetWantedNodes can be used here, but is not always appropriate to use
11629
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
11630
      # more information.
11631
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
11632
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
11633

    
11634
  def _TestDelay(self):
11635
    """Do the actual sleep.
11636

11637
    """
11638
    if self.op.on_master:
11639
      if not utils.TestDelay(self.op.duration):
11640
        raise errors.OpExecError("Error during master delay test")
11641
    if self.op.on_nodes:
11642
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
11643
      for node, node_result in result.items():
11644
        node_result.Raise("Failure during rpc call to node %s" % node)
11645

    
11646
  def Exec(self, feedback_fn):
11647
    """Execute the test delay opcode, with the wanted repetitions.
11648

11649
    """
11650
    if self.op.repeat == 0:
11651
      self._TestDelay()
11652
    else:
11653
      top_value = self.op.repeat - 1
11654
      for i in range(self.op.repeat):
11655
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
11656
        self._TestDelay()
11657

    
11658

    
11659
class LUTestJqueue(NoHooksLU):
11660
  """Utility LU to test some aspects of the job queue.
11661

11662
  """
11663
  REQ_BGL = False
11664

    
11665
  # Must be lower than default timeout for WaitForJobChange to see whether it
11666
  # notices changed jobs
11667
  _CLIENT_CONNECT_TIMEOUT = 20.0
11668
  _CLIENT_CONFIRM_TIMEOUT = 60.0
11669

    
11670
  @classmethod
11671
  def _NotifyUsingSocket(cls, cb, errcls):
11672
    """Opens a Unix socket and waits for another program to connect.
11673

11674
    @type cb: callable
11675
    @param cb: Callback to send socket name to client
11676
    @type errcls: class
11677
    @param errcls: Exception class to use for errors
11678

11679
    """
11680
    # Using a temporary directory as there's no easy way to create temporary
11681
    # sockets without writing a custom loop around tempfile.mktemp and
11682
    # socket.bind
11683
    tmpdir = tempfile.mkdtemp()
11684
    try:
11685
      tmpsock = utils.PathJoin(tmpdir, "sock")
11686

    
11687
      logging.debug("Creating temporary socket at %s", tmpsock)
11688
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
11689
      try:
11690
        sock.bind(tmpsock)
11691
        sock.listen(1)
11692

    
11693
        # Send details to client
11694
        cb(tmpsock)
11695

    
11696
        # Wait for client to connect before continuing
11697
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
11698
        try:
11699
          (conn, _) = sock.accept()
11700
        except socket.error, err:
11701
          raise errcls("Client didn't connect in time (%s)" % err)
11702
      finally:
11703
        sock.close()
11704
    finally:
11705
      # Remove as soon as client is connected
11706
      shutil.rmtree(tmpdir)
11707

    
11708
    # Wait for client to close
11709
    try:
11710
      try:
11711
        # pylint: disable-msg=E1101
11712
        # Instance of '_socketobject' has no ... member
11713
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
11714
        conn.recv(1)
11715
      except socket.error, err:
11716
        raise errcls("Client failed to confirm notification (%s)" % err)
11717
    finally:
11718
      conn.close()
11719

    
11720
  def _SendNotification(self, test, arg, sockname):
11721
    """Sends a notification to the client.
11722

11723
    @type test: string
11724
    @param test: Test name
11725
    @param arg: Test argument (depends on test)
11726
    @type sockname: string
11727
    @param sockname: Socket path
11728

11729
    """
11730
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
11731

    
11732
  def _Notify(self, prereq, test, arg):
11733
    """Notifies the client of a test.
11734

11735
    @type prereq: bool
11736
    @param prereq: Whether this is a prereq-phase test
11737
    @type test: string
11738
    @param test: Test name
11739
    @param arg: Test argument (depends on test)
11740

11741
    """
11742
    if prereq:
11743
      errcls = errors.OpPrereqError
11744
    else:
11745
      errcls = errors.OpExecError
11746

    
11747
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
11748
                                                  test, arg),
11749
                                   errcls)
11750

    
11751
  def CheckArguments(self):
11752
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
11753
    self.expandnames_calls = 0
11754

    
11755
  def ExpandNames(self):
11756
    checkargs_calls = getattr(self, "checkargs_calls", 0)
11757
    if checkargs_calls < 1:
11758
      raise errors.ProgrammerError("CheckArguments was not called")
11759

    
11760
    self.expandnames_calls += 1
11761

    
11762
    if self.op.notify_waitlock:
11763
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
11764

    
11765
    self.LogInfo("Expanding names")
11766

    
11767
    # Get lock on master node (just to get a lock, not for a particular reason)
11768
    self.needed_locks = {
11769
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
11770
      }
11771

    
11772
  def Exec(self, feedback_fn):
11773
    if self.expandnames_calls < 1:
11774
      raise errors.ProgrammerError("ExpandNames was not called")
11775

    
11776
    if self.op.notify_exec:
11777
      self._Notify(False, constants.JQT_EXEC, None)
11778

    
11779
    self.LogInfo("Executing")
11780

    
11781
    if self.op.log_messages:
11782
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
11783
      for idx, msg in enumerate(self.op.log_messages):
11784
        self.LogInfo("Sending log message %s", idx + 1)
11785
        feedback_fn(constants.JQT_MSGPREFIX + msg)
11786
        # Report how many test messages have been sent
11787
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
11788

    
11789
    if self.op.fail:
11790
      raise errors.OpExecError("Opcode failure was requested")
11791

    
11792
    return True
11793

    
11794

    
11795
class IAllocator(object):
11796
  """IAllocator framework.
11797

11798
  An IAllocator instance has three sets of attributes:
11799
    - cfg that is needed to query the cluster
11800
    - input data (all members of the _KEYS class attribute are required)
11801
    - four buffer attributes (in|out_data|text), that represent the
11802
      input (to the external script) in text and data structure format,
11803
      and the output from it, again in two formats
11804
    - the result variables from the script (success, info, nodes) for
11805
      easy usage
11806

11807
  """
11808
  # pylint: disable-msg=R0902
11809
  # lots of instance attributes
11810

    
11811
  def __init__(self, cfg, rpc, mode, **kwargs):
11812
    self.cfg = cfg
11813
    self.rpc = rpc
11814
    # init buffer variables
11815
    self.in_text = self.out_text = self.in_data = self.out_data = None
11816
    # init all input fields so that pylint is happy
11817
    self.mode = mode
11818
    self.mem_size = self.disks = self.disk_template = None
11819
    self.os = self.tags = self.nics = self.vcpus = None
11820
    self.hypervisor = None
11821
    self.relocate_from = None
11822
    self.name = None
11823
    self.evac_nodes = None
11824
    self.instances = None
11825
    self.reloc_mode = None
11826
    self.target_groups = None
11827
    # computed fields
11828
    self.required_nodes = None
11829
    # init result fields
11830
    self.success = self.info = self.result = None
11831

    
11832
    try:
11833
      (fn, keyset, self._result_check) = self._MODE_DATA[self.mode]
11834
    except KeyError:
11835
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
11836
                                   " IAllocator" % self.mode)
11837

    
11838
    for key in kwargs:
11839
      if key not in keyset:
11840
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
11841
                                     " IAllocator" % key)
11842
      setattr(self, key, kwargs[key])
11843

    
11844
    for key in keyset:
11845
      if key not in kwargs:
11846
        raise errors.ProgrammerError("Missing input parameter '%s' to"
11847
                                     " IAllocator" % key)
11848
    self._BuildInputData(compat.partial(fn, self))
11849

    
11850
  def _ComputeClusterData(self):
11851
    """Compute the generic allocator input data.
11852

11853
    This is the data that is independent of the actual operation.
11854

11855
    """
11856
    cfg = self.cfg
11857
    cluster_info = cfg.GetClusterInfo()
11858
    # cluster data
11859
    data = {
11860
      "version": constants.IALLOCATOR_VERSION,
11861
      "cluster_name": cfg.GetClusterName(),
11862
      "cluster_tags": list(cluster_info.GetTags()),
11863
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
11864
      # we don't have job IDs
11865
      }
11866
    ninfo = cfg.GetAllNodesInfo()
11867
    iinfo = cfg.GetAllInstancesInfo().values()
11868
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
11869

    
11870
    # node data
11871
    node_list = [n.name for n in ninfo.values() if n.vm_capable]
11872

    
11873
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
11874
      hypervisor_name = self.hypervisor
11875
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
11876
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
11877
    elif self.mode in (constants.IALLOCATOR_MODE_MEVAC,
11878
                       constants.IALLOCATOR_MODE_MRELOC):
11879
      hypervisor_name = cluster_info.enabled_hypervisors[0]
11880

    
11881
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
11882
                                        hypervisor_name)
11883
    node_iinfo = \
11884
      self.rpc.call_all_instances_info(node_list,
11885
                                       cluster_info.enabled_hypervisors)
11886

    
11887
    data["nodegroups"] = self._ComputeNodeGroupData(cfg)
11888

    
11889
    config_ndata = self._ComputeBasicNodeData(ninfo)
11890
    data["nodes"] = self._ComputeDynamicNodeData(ninfo, node_data, node_iinfo,
11891
                                                 i_list, config_ndata)
11892
    assert len(data["nodes"]) == len(ninfo), \
11893
        "Incomplete node data computed"
11894

    
11895
    data["instances"] = self._ComputeInstanceData(cluster_info, i_list)
11896

    
11897
    self.in_data = data
11898

    
11899
  @staticmethod
11900
  def _ComputeNodeGroupData(cfg):
11901
    """Compute node groups data.
11902

11903
    """
11904
    ng = dict((guuid, {
11905
      "name": gdata.name,
11906
      "alloc_policy": gdata.alloc_policy,
11907
      })
11908
      for guuid, gdata in cfg.GetAllNodeGroupsInfo().items())
11909

    
11910
    return ng
11911

    
11912
  @staticmethod
11913
  def _ComputeBasicNodeData(node_cfg):
11914
    """Compute global node data.
11915

11916
    @rtype: dict
11917
    @returns: a dict of name: (node dict, node config)
11918

11919
    """
11920
    # fill in static (config-based) values
11921
    node_results = dict((ninfo.name, {
11922
      "tags": list(ninfo.GetTags()),
11923
      "primary_ip": ninfo.primary_ip,
11924
      "secondary_ip": ninfo.secondary_ip,
11925
      "offline": ninfo.offline,
11926
      "drained": ninfo.drained,
11927
      "master_candidate": ninfo.master_candidate,
11928
      "group": ninfo.group,
11929
      "master_capable": ninfo.master_capable,
11930
      "vm_capable": ninfo.vm_capable,
11931
      })
11932
      for ninfo in node_cfg.values())
11933

    
11934
    return node_results
11935

    
11936
  @staticmethod
11937
  def _ComputeDynamicNodeData(node_cfg, node_data, node_iinfo, i_list,
11938
                              node_results):
11939
    """Compute global node data.
11940

11941
    @param node_results: the basic node structures as filled from the config
11942

11943
    """
11944
    # make a copy of the current dict
11945
    node_results = dict(node_results)
11946
    for nname, nresult in node_data.items():
11947
      assert nname in node_results, "Missing basic data for node %s" % nname
11948
      ninfo = node_cfg[nname]
11949

    
11950
      if not (ninfo.offline or ninfo.drained):
11951
        nresult.Raise("Can't get data for node %s" % nname)
11952
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
11953
                                nname)
11954
        remote_info = nresult.payload
11955

    
11956
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
11957
                     'vg_size', 'vg_free', 'cpu_total']:
11958
          if attr not in remote_info:
11959
            raise errors.OpExecError("Node '%s' didn't return attribute"
11960
                                     " '%s'" % (nname, attr))
11961
          if not isinstance(remote_info[attr], int):
11962
            raise errors.OpExecError("Node '%s' returned invalid value"
11963
                                     " for '%s': %s" %
11964
                                     (nname, attr, remote_info[attr]))
11965
        # compute memory used by primary instances
11966
        i_p_mem = i_p_up_mem = 0
11967
        for iinfo, beinfo in i_list:
11968
          if iinfo.primary_node == nname:
11969
            i_p_mem += beinfo[constants.BE_MEMORY]
11970
            if iinfo.name not in node_iinfo[nname].payload:
11971
              i_used_mem = 0
11972
            else:
11973
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
11974
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
11975
            remote_info['memory_free'] -= max(0, i_mem_diff)
11976

    
11977
            if iinfo.admin_up:
11978
              i_p_up_mem += beinfo[constants.BE_MEMORY]
11979

    
11980
        # compute memory used by instances
11981
        pnr_dyn = {
11982
          "total_memory": remote_info['memory_total'],
11983
          "reserved_memory": remote_info['memory_dom0'],
11984
          "free_memory": remote_info['memory_free'],
11985
          "total_disk": remote_info['vg_size'],
11986
          "free_disk": remote_info['vg_free'],
11987
          "total_cpus": remote_info['cpu_total'],
11988
          "i_pri_memory": i_p_mem,
11989
          "i_pri_up_memory": i_p_up_mem,
11990
          }
11991
        pnr_dyn.update(node_results[nname])
11992
        node_results[nname] = pnr_dyn
11993

    
11994
    return node_results
11995

    
11996
  @staticmethod
11997
  def _ComputeInstanceData(cluster_info, i_list):
11998
    """Compute global instance data.
11999

12000
    """
12001
    instance_data = {}
12002
    for iinfo, beinfo in i_list:
12003
      nic_data = []
12004
      for nic in iinfo.nics:
12005
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
12006
        nic_dict = {
12007
          "mac": nic.mac,
12008
          "ip": nic.ip,
12009
          "mode": filled_params[constants.NIC_MODE],
12010
          "link": filled_params[constants.NIC_LINK],
12011
          }
12012
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
12013
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
12014
        nic_data.append(nic_dict)
12015
      pir = {
12016
        "tags": list(iinfo.GetTags()),
12017
        "admin_up": iinfo.admin_up,
12018
        "vcpus": beinfo[constants.BE_VCPUS],
12019
        "memory": beinfo[constants.BE_MEMORY],
12020
        "os": iinfo.os,
12021
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
12022
        "nics": nic_data,
12023
        "disks": [{constants.IDISK_SIZE: dsk.size,
12024
                   constants.IDISK_MODE: dsk.mode}
12025
                  for dsk in iinfo.disks],
12026
        "disk_template": iinfo.disk_template,
12027
        "hypervisor": iinfo.hypervisor,
12028
        }
12029
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
12030
                                                 pir["disks"])
12031
      instance_data[iinfo.name] = pir
12032

    
12033
    return instance_data
12034

    
12035
  def _AddNewInstance(self):
12036
    """Add new instance data to allocator structure.
12037

12038
    This in combination with _AllocatorGetClusterData will create the
12039
    correct structure needed as input for the allocator.
12040

12041
    The checks for the completeness of the opcode must have already been
12042
    done.
12043

12044
    """
12045
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
12046

    
12047
    if self.disk_template in constants.DTS_INT_MIRROR:
12048
      self.required_nodes = 2
12049
    else:
12050
      self.required_nodes = 1
12051

    
12052
    request = {
12053
      "name": self.name,
12054
      "disk_template": self.disk_template,
12055
      "tags": self.tags,
12056
      "os": self.os,
12057
      "vcpus": self.vcpus,
12058
      "memory": self.mem_size,
12059
      "disks": self.disks,
12060
      "disk_space_total": disk_space,
12061
      "nics": self.nics,
12062
      "required_nodes": self.required_nodes,
12063
      }
12064

    
12065
    return request
12066

    
12067
  def _AddRelocateInstance(self):
12068
    """Add relocate instance data to allocator structure.
12069

12070
    This in combination with _IAllocatorGetClusterData will create the
12071
    correct structure needed as input for the allocator.
12072

12073
    The checks for the completeness of the opcode must have already been
12074
    done.
12075

12076
    """
12077
    instance = self.cfg.GetInstanceInfo(self.name)
12078
    if instance is None:
12079
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
12080
                                   " IAllocator" % self.name)
12081

    
12082
    if instance.disk_template not in constants.DTS_MIRRORED:
12083
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
12084
                                 errors.ECODE_INVAL)
12085

    
12086
    if instance.disk_template in constants.DTS_INT_MIRROR and \
12087
        len(instance.secondary_nodes) != 1:
12088
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
12089
                                 errors.ECODE_STATE)
12090

    
12091
    self.required_nodes = 1
12092
    disk_sizes = [{constants.IDISK_SIZE: disk.size} for disk in instance.disks]
12093
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
12094

    
12095
    request = {
12096
      "name": self.name,
12097
      "disk_space_total": disk_space,
12098
      "required_nodes": self.required_nodes,
12099
      "relocate_from": self.relocate_from,
12100
      }
12101
    return request
12102

    
12103
  def _AddEvacuateNodes(self):
12104
    """Add evacuate nodes data to allocator structure.
12105

12106
    """
12107
    request = {
12108
      "evac_nodes": self.evac_nodes
12109
      }
12110
    return request
12111

    
12112
  def _AddMultiRelocate(self):
12113
    """Get data for multi-relocate requests.
12114

12115
    """
12116
    return {
12117
      "instances": self.instances,
12118
      "reloc_mode": self.reloc_mode,
12119
      "target_groups": self.target_groups,
12120
      }
12121

    
12122
  def _BuildInputData(self, fn):
12123
    """Build input data structures.
12124

12125
    """
12126
    self._ComputeClusterData()
12127

    
12128
    request = fn()
12129
    request["type"] = self.mode
12130
    self.in_data["request"] = request
12131

    
12132
    self.in_text = serializer.Dump(self.in_data)
12133

    
12134
  _MODE_DATA = {
12135
    constants.IALLOCATOR_MODE_ALLOC:
12136
      (_AddNewInstance,
12137
       ["name", "mem_size", "disks", "disk_template", "os", "tags", "nics",
12138
        "vcpus", "hypervisor"], ht.TList),
12139
    constants.IALLOCATOR_MODE_RELOC:
12140
      (_AddRelocateInstance, ["name", "relocate_from"], ht.TList),
12141
    constants.IALLOCATOR_MODE_MEVAC:
12142
      (_AddEvacuateNodes, ["evac_nodes"],
12143
       ht.TListOf(ht.TAnd(ht.TIsLength(2),
12144
                          ht.TListOf(ht.TString)))),
12145
    constants.IALLOCATOR_MODE_MRELOC:
12146
      (_AddMultiRelocate, ["instances", "reloc_mode", "target_groups"],
12147
       ht.TListOf(ht.TListOf(ht.TStrictDict(True, False, {
12148
         # pylint: disable-msg=E1101
12149
         # Class '...' has no 'OP_ID' member
12150
         "OP_ID": ht.TElemOf([opcodes.OpInstanceFailover.OP_ID,
12151
                              opcodes.OpInstanceMigrate.OP_ID,
12152
                              opcodes.OpInstanceReplaceDisks.OP_ID])
12153
         })))),
12154
    }
12155

    
12156
  def Run(self, name, validate=True, call_fn=None):
12157
    """Run an instance allocator and return the results.
12158

12159
    """
12160
    if call_fn is None:
12161
      call_fn = self.rpc.call_iallocator_runner
12162

    
12163
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
12164
    result.Raise("Failure while running the iallocator script")
12165

    
12166
    self.out_text = result.payload
12167
    if validate:
12168
      self._ValidateResult()
12169

    
12170
  def _ValidateResult(self):
12171
    """Process the allocator results.
12172

12173
    This will process and if successful save the result in
12174
    self.out_data and the other parameters.
12175

12176
    """
12177
    try:
12178
      rdict = serializer.Load(self.out_text)
12179
    except Exception, err:
12180
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
12181

    
12182
    if not isinstance(rdict, dict):
12183
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
12184

    
12185
    # TODO: remove backwards compatiblity in later versions
12186
    if "nodes" in rdict and "result" not in rdict:
12187
      rdict["result"] = rdict["nodes"]
12188
      del rdict["nodes"]
12189

    
12190
    for key in "success", "info", "result":
12191
      if key not in rdict:
12192
        raise errors.OpExecError("Can't parse iallocator results:"
12193
                                 " missing key '%s'" % key)
12194
      setattr(self, key, rdict[key])
12195

    
12196
    if not self._result_check(self.result):
12197
      raise errors.OpExecError("Iallocator returned invalid result,"
12198
                               " expected %s, got %s" %
12199
                               (self._result_check, self.result),
12200
                               errors.ECODE_INVAL)
12201

    
12202
    if self.mode in (constants.IALLOCATOR_MODE_RELOC,
12203
                     constants.IALLOCATOR_MODE_MEVAC):
12204
      node2group = dict((name, ndata["group"])
12205
                        for (name, ndata) in self.in_data["nodes"].items())
12206

    
12207
      fn = compat.partial(self._NodesToGroups, node2group,
12208
                          self.in_data["nodegroups"])
12209

    
12210
      if self.mode == constants.IALLOCATOR_MODE_RELOC:
12211
        assert self.relocate_from is not None
12212
        assert self.required_nodes == 1
12213

    
12214
        request_groups = fn(self.relocate_from)
12215
        result_groups = fn(rdict["result"])
12216

    
12217
        if result_groups != request_groups:
12218
          raise errors.OpExecError("Groups of nodes returned by iallocator (%s)"
12219
                                   " differ from original groups (%s)" %
12220
                                   (utils.CommaJoin(result_groups),
12221
                                    utils.CommaJoin(request_groups)))
12222
      elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
12223
        request_groups = fn(self.evac_nodes)
12224
        for (instance_name, secnode) in self.result:
12225
          result_groups = fn([secnode])
12226
          if result_groups != request_groups:
12227
            raise errors.OpExecError("Iallocator returned new secondary node"
12228
                                     " '%s' (group '%s') for instance '%s'"
12229
                                     " which is not in original group '%s'" %
12230
                                     (secnode, utils.CommaJoin(result_groups),
12231
                                      instance_name,
12232
                                      utils.CommaJoin(request_groups)))
12233
      else:
12234
        raise errors.ProgrammerError("Unhandled mode '%s'" % self.mode)
12235

    
12236
    self.out_data = rdict
12237

    
12238
  @staticmethod
12239
  def _NodesToGroups(node2group, groups, nodes):
12240
    """Returns a list of unique group names for a list of nodes.
12241

12242
    @type node2group: dict
12243
    @param node2group: Map from node name to group UUID
12244
    @type groups: dict
12245
    @param groups: Group information
12246
    @type nodes: list
12247
    @param nodes: Node names
12248

12249
    """
12250
    result = set()
12251

    
12252
    for node in nodes:
12253
      try:
12254
        group_uuid = node2group[node]
12255
      except KeyError:
12256
        # Ignore unknown node
12257
        pass
12258
      else:
12259
        try:
12260
          group = groups[group_uuid]
12261
        except KeyError:
12262
          # Can't find group, let's use UUID
12263
          group_name = group_uuid
12264
        else:
12265
          group_name = group["name"]
12266

    
12267
        result.add(group_name)
12268

    
12269
    return sorted(result)
12270

    
12271

    
12272
class LUTestAllocator(NoHooksLU):
12273
  """Run allocator tests.
12274

12275
  This LU runs the allocator tests
12276

12277
  """
12278
  def CheckPrereq(self):
12279
    """Check prerequisites.
12280

12281
    This checks the opcode parameters depending on the director and mode test.
12282

12283
    """
12284
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12285
      for attr in ["mem_size", "disks", "disk_template",
12286
                   "os", "tags", "nics", "vcpus"]:
12287
        if not hasattr(self.op, attr):
12288
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
12289
                                     attr, errors.ECODE_INVAL)
12290
      iname = self.cfg.ExpandInstanceName(self.op.name)
12291
      if iname is not None:
12292
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
12293
                                   iname, errors.ECODE_EXISTS)
12294
      if not isinstance(self.op.nics, list):
12295
        raise errors.OpPrereqError("Invalid parameter 'nics'",
12296
                                   errors.ECODE_INVAL)
12297
      if not isinstance(self.op.disks, list):
12298
        raise errors.OpPrereqError("Invalid parameter 'disks'",
12299
                                   errors.ECODE_INVAL)
12300
      for row in self.op.disks:
12301
        if (not isinstance(row, dict) or
12302
            "size" not in row or
12303
            not isinstance(row["size"], int) or
12304
            "mode" not in row or
12305
            row["mode"] not in ['r', 'w']):
12306
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
12307
                                     " parameter", errors.ECODE_INVAL)
12308
      if self.op.hypervisor is None:
12309
        self.op.hypervisor = self.cfg.GetHypervisorType()
12310
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12311
      fname = _ExpandInstanceName(self.cfg, self.op.name)
12312
      self.op.name = fname
12313
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
12314
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12315
      if not hasattr(self.op, "evac_nodes"):
12316
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
12317
                                   " opcode input", errors.ECODE_INVAL)
12318
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12319
      if self.op.instances:
12320
        self.op.instances = _GetWantedInstances(self, self.op.instances)
12321
      else:
12322
        raise errors.OpPrereqError("Missing instances to relocate",
12323
                                   errors.ECODE_INVAL)
12324
    else:
12325
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
12326
                                 self.op.mode, errors.ECODE_INVAL)
12327

    
12328
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
12329
      if self.op.allocator is None:
12330
        raise errors.OpPrereqError("Missing allocator name",
12331
                                   errors.ECODE_INVAL)
12332
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
12333
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
12334
                                 self.op.direction, errors.ECODE_INVAL)
12335

    
12336
  def Exec(self, feedback_fn):
12337
    """Run the allocator test.
12338

12339
    """
12340
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
12341
      ial = IAllocator(self.cfg, self.rpc,
12342
                       mode=self.op.mode,
12343
                       name=self.op.name,
12344
                       mem_size=self.op.mem_size,
12345
                       disks=self.op.disks,
12346
                       disk_template=self.op.disk_template,
12347
                       os=self.op.os,
12348
                       tags=self.op.tags,
12349
                       nics=self.op.nics,
12350
                       vcpus=self.op.vcpus,
12351
                       hypervisor=self.op.hypervisor,
12352
                       )
12353
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
12354
      ial = IAllocator(self.cfg, self.rpc,
12355
                       mode=self.op.mode,
12356
                       name=self.op.name,
12357
                       relocate_from=list(self.relocate_from),
12358
                       )
12359
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
12360
      ial = IAllocator(self.cfg, self.rpc,
12361
                       mode=self.op.mode,
12362
                       evac_nodes=self.op.evac_nodes)
12363
    elif self.op.mode == constants.IALLOCATOR_MODE_MRELOC:
12364
      ial = IAllocator(self.cfg, self.rpc,
12365
                       mode=self.op.mode,
12366
                       instances=self.op.instances,
12367
                       reloc_mode=self.op.reloc_mode,
12368
                       target_groups=self.op.target_groups)
12369
    else:
12370
      raise errors.ProgrammerError("Uncatched mode %s in"
12371
                                   " LUTestAllocator.Exec", self.op.mode)
12372

    
12373
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
12374
      result = ial.in_text
12375
    else:
12376
      ial.Run(self.op.allocator, validate=False)
12377
      result = ial.out_text
12378
    return result
12379

    
12380

    
12381
#: Query type implementations
12382
_QUERY_IMPL = {
12383
  constants.QR_INSTANCE: _InstanceQuery,
12384
  constants.QR_NODE: _NodeQuery,
12385
  constants.QR_GROUP: _GroupQuery,
12386
  constants.QR_OS: _OsQuery,
12387
  }
12388

    
12389
assert set(_QUERY_IMPL.keys()) == constants.QR_VIA_OP
12390

    
12391

    
12392
def _GetQueryImplementation(name):
12393
  """Returns the implemtnation for a query type.
12394

12395
  @param name: Query type, must be one of L{constants.QR_VIA_OP}
12396

12397
  """
12398
  try:
12399
    return _QUERY_IMPL[name]
12400
  except KeyError:
12401
    raise errors.OpPrereqError("Unknown query resource '%s'" % name,
12402
                               errors.ECODE_INVAL)