Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 51cb1581

History | View | Annotate | Download (354 kB)

1
#
2
#
3

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

    
21

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

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

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

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

    
31
import os
32
import os.path
33
import time
34
import re
35
import platform
36
import logging
37
import copy
38
import OpenSSL
39

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

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

    
55

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

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

62
  """
63
  return []
64

    
65

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

69
  """
70
  return {}
71

    
72

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

    
76

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

    
80

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

85
  """
86
  return val is not None
87

    
88

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

92
  """
93
  return val is None
94

    
95

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

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

    
102

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

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

    
109

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

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

    
116

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

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

    
123

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

127
  """
128
  return bool(val)
129

    
130

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

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

    
137

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

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

    
145

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

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

    
152

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

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

    
162

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

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

    
171

    
172
# Type aliases
173

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

    
177

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

    
181

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

    
185

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

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

    
192

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

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

    
200

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

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

    
210

    
211
# Common opcode attributes
212

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

    
216

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

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

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

    
227

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

    
231

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

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

245
  Note that all commands require root permissions.
246

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

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

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

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

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

    
290
    # Tasklets
291
    self.tasklets = None
292

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

    
320
    self.CheckArguments()
321

    
322
  def __GetSSH(self):
323
    """Returns the SshRunner object
324

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

    
330
  ssh = property(fget=__GetSSH)
331

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

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

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

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

347
    """
348
    pass
349

    
350
  def ExpandNames(self):
351
    """Expand names for this LU.
352

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

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

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

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

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

375
    Examples::
376

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

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

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

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

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

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

414
    """
415

    
416
  def CheckPrereq(self):
417
    """Check prerequisites for this LU.
418

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

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

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

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

    
439
  def Exec(self, feedback_fn):
440
    """Execute the LU.
441

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

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

    
454
  def BuildHooksEnv(self):
455
    """Build hooks environment for this LU.
456

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

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

468
    No nodes should be returned as an empty list (and not None).
469

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

473
    """
474
    raise NotImplementedError
475

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

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

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

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

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

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

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

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

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

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

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

533
    If should be called in DeclareLocks in a way similar to::
534

535
      if level == locking.LEVEL_NODE:
536
        self._LockInstancesNodes()
537

538
    @type primary_only: boolean
539
    @param primary_only: only lock primary nodes of locked instances
540

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

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

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

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

    
562
    del self.recalculate_locks[locking.LEVEL_NODE]
563

    
564

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

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

571
  """
572
  HPATH = None
573
  HTYPE = None
574

    
575
  def BuildHooksEnv(self):
576
    """Empty BuildHooksEnv for NoHooksLu.
577

578
    This just raises an error.
579

580
    """
581
    assert False, "BuildHooksEnv called for NoHooksLUs"
582

    
583

    
584
class Tasklet:
585
  """Tasklet base class.
586

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

591
  Subclasses must follow these rules:
592
    - Implement CheckPrereq
593
    - Implement Exec
594

595
  """
596
  def __init__(self, lu):
597
    self.lu = lu
598

    
599
    # Shortcuts
600
    self.cfg = lu.cfg
601
    self.rpc = lu.rpc
602

    
603
  def CheckPrereq(self):
604
    """Check prerequisites for this tasklets.
605

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

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

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

616
    """
617
    pass
618

    
619
  def Exec(self, feedback_fn):
620
    """Execute the tasklet.
621

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

626
    """
627
    raise NotImplementedError
628

    
629

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

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

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

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

    
649

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

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

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

    
669

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

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

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

    
702

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

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

711
  """
712
  f = utils.FieldSet()
713
  f.Extend(static)
714
  f.Extend(dynamic)
715

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

    
721

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

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

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

    
736

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

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

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

    
749

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

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

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

    
762

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

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

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

    
780

    
781
def _RequireFileStorage():
782
  """Checks that file storage is enabled.
783

784
  @raise errors.OpPrereqError: when file storage is disabled
785

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

    
791

    
792
def _CheckDiskTemplate(template):
793
  """Ensure a given disk template is valid.
794

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

    
804

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

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

    
816

    
817
def _GetClusterDomainSecret():
818
  """Reads the cluster domain secret.
819

820
  """
821
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
822
                               strict=True)
823

    
824

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

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

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

    
840

    
841
def _ExpandItemName(fn, name, kind):
842
  """Expand an item name.
843

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

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

    
857

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

    
862

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

    
867

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

873
  This builds the hook environment from individual variables.
874

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

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

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

    
937
  env["INSTANCE_NIC_COUNT"] = nic_count
938

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

    
947
  env["INSTANCE_DISK_COUNT"] = disk_count
948

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

    
953
  return env
954

    
955

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

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

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

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

    
979

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

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

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

    
1017

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

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

    
1033

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

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

    
1044

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

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

    
1058

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

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

    
1067

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

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

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

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

    
1088

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

    
1092

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

1096
  """
1097

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

    
1100

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

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

    
1108

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

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

    
1116

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

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

    
1126
  return []
1127

    
1128

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

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

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

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

    
1143
  return faulty
1144

    
1145

    
1146
class LUPostInitCluster(LogicalUnit):
1147
  """Logical unit for running hooks after cluster initialization.
1148

1149
  """
1150
  HPATH = "cluster-init"
1151
  HTYPE = constants.HTYPE_CLUSTER
1152

    
1153
  def BuildHooksEnv(self):
1154
    """Build hooks env.
1155

1156
    """
1157
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1158
    mn = self.cfg.GetMasterNode()
1159
    return env, [], [mn]
1160

    
1161
  def Exec(self, feedback_fn):
1162
    """Nothing to do.
1163

1164
    """
1165
    return True
1166

    
1167

    
1168
class LUDestroyCluster(LogicalUnit):
1169
  """Logical unit for destroying the cluster.
1170

1171
  """
1172
  HPATH = "cluster-destroy"
1173
  HTYPE = constants.HTYPE_CLUSTER
1174

    
1175
  def BuildHooksEnv(self):
1176
    """Build hooks env.
1177

1178
    """
1179
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1180
    return env, [], []
1181

    
1182
  def CheckPrereq(self):
1183
    """Check prerequisites.
1184

1185
    This checks whether the cluster is empty.
1186

1187
    Any errors are signaled by raising errors.OpPrereqError.
1188

1189
    """
1190
    master = self.cfg.GetMasterNode()
1191

    
1192
    nodelist = self.cfg.GetNodeList()
1193
    if len(nodelist) != 1 or nodelist[0] != master:
1194
      raise errors.OpPrereqError("There are still %d node(s) in"
1195
                                 " this cluster." % (len(nodelist) - 1),
1196
                                 errors.ECODE_INVAL)
1197
    instancelist = self.cfg.GetInstanceList()
1198
    if instancelist:
1199
      raise errors.OpPrereqError("There are still %d instance(s) in"
1200
                                 " this cluster." % len(instancelist),
1201
                                 errors.ECODE_INVAL)
1202

    
1203
  def Exec(self, feedback_fn):
1204
    """Destroys the cluster.
1205

1206
    """
1207
    master = self.cfg.GetMasterNode()
1208
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1209

    
1210
    # Run post hooks on master node before it's removed
1211
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1212
    try:
1213
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1214
    except:
1215
      # pylint: disable-msg=W0702
1216
      self.LogWarning("Errors occurred running hooks on %s" % master)
1217

    
1218
    result = self.rpc.call_node_stop_master(master, False)
1219
    result.Raise("Could not disable the master role")
1220

    
1221
    if modify_ssh_setup:
1222
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1223
      utils.CreateBackup(priv_key)
1224
      utils.CreateBackup(pub_key)
1225

    
1226
    return master
1227

    
1228

    
1229
def _VerifyCertificate(filename):
1230
  """Verifies a certificate for LUVerifyCluster.
1231

1232
  @type filename: string
1233
  @param filename: Path to PEM file
1234

1235
  """
1236
  try:
1237
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1238
                                           utils.ReadFile(filename))
1239
  except Exception, err: # pylint: disable-msg=W0703
1240
    return (LUVerifyCluster.ETYPE_ERROR,
1241
            "Failed to load X509 certificate %s: %s" % (filename, err))
1242

    
1243
  (errcode, msg) = \
1244
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1245
                                constants.SSL_CERT_EXPIRATION_ERROR)
1246

    
1247
  if msg:
1248
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1249
  else:
1250
    fnamemsg = None
1251

    
1252
  if errcode is None:
1253
    return (None, fnamemsg)
1254
  elif errcode == utils.CERT_WARNING:
1255
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1256
  elif errcode == utils.CERT_ERROR:
1257
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1258

    
1259
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1260

    
1261

    
1262
class LUVerifyCluster(LogicalUnit):
1263
  """Verifies the cluster status.
1264

1265
  """
1266
  HPATH = "cluster-verify"
1267
  HTYPE = constants.HTYPE_CLUSTER
1268
  _OP_PARAMS = [
1269
    ("skip_checks", _EmptyList,
1270
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1271
    ("verbose", False, _TBool),
1272
    ("error_codes", False, _TBool),
1273
    ("debug_simulate_errors", False, _TBool),
1274
    ]
1275
  REQ_BGL = False
1276

    
1277
  TCLUSTER = "cluster"
1278
  TNODE = "node"
1279
  TINSTANCE = "instance"
1280

    
1281
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1282
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1283
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1284
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1285
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1286
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1287
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1288
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1289
  ENODEDRBD = (TNODE, "ENODEDRBD")
1290
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1291
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1292
  ENODEHV = (TNODE, "ENODEHV")
1293
  ENODELVM = (TNODE, "ENODELVM")
1294
  ENODEN1 = (TNODE, "ENODEN1")
1295
  ENODENET = (TNODE, "ENODENET")
1296
  ENODEOS = (TNODE, "ENODEOS")
1297
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1298
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1299
  ENODERPC = (TNODE, "ENODERPC")
1300
  ENODESSH = (TNODE, "ENODESSH")
1301
  ENODEVERSION = (TNODE, "ENODEVERSION")
1302
  ENODESETUP = (TNODE, "ENODESETUP")
1303
  ENODETIME = (TNODE, "ENODETIME")
1304

    
1305
  ETYPE_FIELD = "code"
1306
  ETYPE_ERROR = "ERROR"
1307
  ETYPE_WARNING = "WARNING"
1308

    
1309
  class NodeImage(object):
1310
    """A class representing the logical and physical status of a node.
1311

1312
    @type name: string
1313
    @ivar name: the node name to which this object refers
1314
    @ivar volumes: a structure as returned from
1315
        L{ganeti.backend.GetVolumeList} (runtime)
1316
    @ivar instances: a list of running instances (runtime)
1317
    @ivar pinst: list of configured primary instances (config)
1318
    @ivar sinst: list of configured secondary instances (config)
1319
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1320
        of this node (config)
1321
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1322
    @ivar dfree: free disk, as reported by the node (runtime)
1323
    @ivar offline: the offline status (config)
1324
    @type rpc_fail: boolean
1325
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1326
        not whether the individual keys were correct) (runtime)
1327
    @type lvm_fail: boolean
1328
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1329
    @type hyp_fail: boolean
1330
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1331
    @type ghost: boolean
1332
    @ivar ghost: whether this is a known node or not (config)
1333
    @type os_fail: boolean
1334
    @ivar os_fail: whether the RPC call didn't return valid OS data
1335
    @type oslist: list
1336
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1337

1338
    """
1339
    def __init__(self, offline=False, name=None):
1340
      self.name = name
1341
      self.volumes = {}
1342
      self.instances = []
1343
      self.pinst = []
1344
      self.sinst = []
1345
      self.sbp = {}
1346
      self.mfree = 0
1347
      self.dfree = 0
1348
      self.offline = offline
1349
      self.rpc_fail = False
1350
      self.lvm_fail = False
1351
      self.hyp_fail = False
1352
      self.ghost = False
1353
      self.os_fail = False
1354
      self.oslist = {}
1355

    
1356
  def ExpandNames(self):
1357
    self.needed_locks = {
1358
      locking.LEVEL_NODE: locking.ALL_SET,
1359
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1360
    }
1361
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1362

    
1363
  def _Error(self, ecode, item, msg, *args, **kwargs):
1364
    """Format an error message.
1365

1366
    Based on the opcode's error_codes parameter, either format a
1367
    parseable error code, or a simpler error string.
1368

1369
    This must be called only from Exec and functions called from Exec.
1370

1371
    """
1372
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1373
    itype, etxt = ecode
1374
    # first complete the msg
1375
    if args:
1376
      msg = msg % args
1377
    # then format the whole message
1378
    if self.op.error_codes:
1379
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1380
    else:
1381
      if item:
1382
        item = " " + item
1383
      else:
1384
        item = ""
1385
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1386
    # and finally report it via the feedback_fn
1387
    self._feedback_fn("  - %s" % msg)
1388

    
1389
  def _ErrorIf(self, cond, *args, **kwargs):
1390
    """Log an error message if the passed condition is True.
1391

1392
    """
1393
    cond = bool(cond) or self.op.debug_simulate_errors
1394
    if cond:
1395
      self._Error(*args, **kwargs)
1396
    # do not mark the operation as failed for WARN cases only
1397
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1398
      self.bad = self.bad or cond
1399

    
1400
  def _VerifyNode(self, ninfo, nresult):
1401
    """Run multiple tests against a node.
1402

1403
    Test list:
1404

1405
      - compares ganeti version
1406
      - checks vg existence and size > 20G
1407
      - checks config file checksum
1408
      - checks ssh to other nodes
1409

1410
    @type ninfo: L{objects.Node}
1411
    @param ninfo: the node to check
1412
    @param nresult: the results from the node
1413
    @rtype: boolean
1414
    @return: whether overall this call was successful (and we can expect
1415
         reasonable values in the respose)
1416

1417
    """
1418
    node = ninfo.name
1419
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1420

    
1421
    # main result, nresult should be a non-empty dict
1422
    test = not nresult or not isinstance(nresult, dict)
1423
    _ErrorIf(test, self.ENODERPC, node,
1424
                  "unable to verify node: no data returned")
1425
    if test:
1426
      return False
1427

    
1428
    # compares ganeti version
1429
    local_version = constants.PROTOCOL_VERSION
1430
    remote_version = nresult.get("version", None)
1431
    test = not (remote_version and
1432
                isinstance(remote_version, (list, tuple)) and
1433
                len(remote_version) == 2)
1434
    _ErrorIf(test, self.ENODERPC, node,
1435
             "connection to node returned invalid data")
1436
    if test:
1437
      return False
1438

    
1439
    test = local_version != remote_version[0]
1440
    _ErrorIf(test, self.ENODEVERSION, node,
1441
             "incompatible protocol versions: master %s,"
1442
             " node %s", local_version, remote_version[0])
1443
    if test:
1444
      return False
1445

    
1446
    # node seems compatible, we can actually try to look into its results
1447

    
1448
    # full package version
1449
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1450
                  self.ENODEVERSION, node,
1451
                  "software version mismatch: master %s, node %s",
1452
                  constants.RELEASE_VERSION, remote_version[1],
1453
                  code=self.ETYPE_WARNING)
1454

    
1455
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1456
    if isinstance(hyp_result, dict):
1457
      for hv_name, hv_result in hyp_result.iteritems():
1458
        test = hv_result is not None
1459
        _ErrorIf(test, self.ENODEHV, node,
1460
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1461

    
1462

    
1463
    test = nresult.get(constants.NV_NODESETUP,
1464
                           ["Missing NODESETUP results"])
1465
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1466
             "; ".join(test))
1467

    
1468
    return True
1469

    
1470
  def _VerifyNodeTime(self, ninfo, nresult,
1471
                      nvinfo_starttime, nvinfo_endtime):
1472
    """Check the node time.
1473

1474
    @type ninfo: L{objects.Node}
1475
    @param ninfo: the node to check
1476
    @param nresult: the remote results for the node
1477
    @param nvinfo_starttime: the start time of the RPC call
1478
    @param nvinfo_endtime: the end time of the RPC call
1479

1480
    """
1481
    node = ninfo.name
1482
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1483

    
1484
    ntime = nresult.get(constants.NV_TIME, None)
1485
    try:
1486
      ntime_merged = utils.MergeTime(ntime)
1487
    except (ValueError, TypeError):
1488
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1489
      return
1490

    
1491
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1492
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1493
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1494
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1495
    else:
1496
      ntime_diff = None
1497

    
1498
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1499
             "Node time diverges by at least %s from master node time",
1500
             ntime_diff)
1501

    
1502
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1503
    """Check the node time.
1504

1505
    @type ninfo: L{objects.Node}
1506
    @param ninfo: the node to check
1507
    @param nresult: the remote results for the node
1508
    @param vg_name: the configured VG name
1509

1510
    """
1511
    if vg_name is None:
1512
      return
1513

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

    
1517
    # checks vg existence and size > 20G
1518
    vglist = nresult.get(constants.NV_VGLIST, None)
1519
    test = not vglist
1520
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1521
    if not test:
1522
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1523
                                            constants.MIN_VG_SIZE)
1524
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1525

    
1526
    # check pv names
1527
    pvlist = nresult.get(constants.NV_PVLIST, None)
1528
    test = pvlist is None
1529
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1530
    if not test:
1531
      # check that ':' is not present in PV names, since it's a
1532
      # special character for lvcreate (denotes the range of PEs to
1533
      # use on the PV)
1534
      for _, pvname, owner_vg in pvlist:
1535
        test = ":" in pvname
1536
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1537
                 " '%s' of VG '%s'", pvname, owner_vg)
1538

    
1539
  def _VerifyNodeNetwork(self, ninfo, nresult):
1540
    """Check the node time.
1541

1542
    @type ninfo: L{objects.Node}
1543
    @param ninfo: the node to check
1544
    @param nresult: the remote results for the node
1545

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

    
1550
    test = constants.NV_NODELIST not in nresult
1551
    _ErrorIf(test, self.ENODESSH, node,
1552
             "node hasn't returned node ssh connectivity data")
1553
    if not test:
1554
      if nresult[constants.NV_NODELIST]:
1555
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1556
          _ErrorIf(True, self.ENODESSH, node,
1557
                   "ssh communication with node '%s': %s", a_node, a_msg)
1558

    
1559
    test = constants.NV_NODENETTEST not in nresult
1560
    _ErrorIf(test, self.ENODENET, node,
1561
             "node hasn't returned node tcp connectivity data")
1562
    if not test:
1563
      if nresult[constants.NV_NODENETTEST]:
1564
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1565
        for anode in nlist:
1566
          _ErrorIf(True, self.ENODENET, node,
1567
                   "tcp communication with node '%s': %s",
1568
                   anode, nresult[constants.NV_NODENETTEST][anode])
1569

    
1570
    test = constants.NV_MASTERIP not in nresult
1571
    _ErrorIf(test, self.ENODENET, node,
1572
             "node hasn't returned node master IP reachability data")
1573
    if not test:
1574
      if not nresult[constants.NV_MASTERIP]:
1575
        if node == self.master_node:
1576
          msg = "the master node cannot reach the master IP (not configured?)"
1577
        else:
1578
          msg = "cannot reach the master IP"
1579
        _ErrorIf(True, self.ENODENET, node, msg)
1580

    
1581

    
1582
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1583
    """Verify an instance.
1584

1585
    This function checks to see if the required block devices are
1586
    available on the instance's node.
1587

1588
    """
1589
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1590
    node_current = instanceconfig.primary_node
1591

    
1592
    node_vol_should = {}
1593
    instanceconfig.MapLVsByNode(node_vol_should)
1594

    
1595
    for node in node_vol_should:
1596
      n_img = node_image[node]
1597
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1598
        # ignore missing volumes on offline or broken nodes
1599
        continue
1600
      for volume in node_vol_should[node]:
1601
        test = volume not in n_img.volumes
1602
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1603
                 "volume %s missing on node %s", volume, node)
1604

    
1605
    if instanceconfig.admin_up:
1606
      pri_img = node_image[node_current]
1607
      test = instance not in pri_img.instances and not pri_img.offline
1608
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1609
               "instance not running on its primary node %s",
1610
               node_current)
1611

    
1612
    for node, n_img in node_image.items():
1613
      if (not node == node_current):
1614
        test = instance in n_img.instances
1615
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1616
                 "instance should not run on node %s", node)
1617

    
1618
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1619
    """Verify if there are any unknown volumes in the cluster.
1620

1621
    The .os, .swap and backup volumes are ignored. All other volumes are
1622
    reported as unknown.
1623

1624
    """
1625
    for node, n_img in node_image.items():
1626
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1627
        # skip non-healthy nodes
1628
        continue
1629
      for volume in n_img.volumes:
1630
        test = (node not in node_vol_should or
1631
                volume not in node_vol_should[node])
1632
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1633
                      "volume %s is unknown", volume)
1634

    
1635
  def _VerifyOrphanInstances(self, instancelist, node_image):
1636
    """Verify the list of running instances.
1637

1638
    This checks what instances are running but unknown to the cluster.
1639

1640
    """
1641
    for node, n_img in node_image.items():
1642
      for o_inst in n_img.instances:
1643
        test = o_inst not in instancelist
1644
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1645
                      "instance %s on node %s should not exist", o_inst, node)
1646

    
1647
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1648
    """Verify N+1 Memory Resilience.
1649

1650
    Check that if one single node dies we can still start all the
1651
    instances it was primary for.
1652

1653
    """
1654
    for node, n_img in node_image.items():
1655
      # This code checks that every node which is now listed as
1656
      # secondary has enough memory to host all instances it is
1657
      # supposed to should a single other node in the cluster fail.
1658
      # FIXME: not ready for failover to an arbitrary node
1659
      # FIXME: does not support file-backed instances
1660
      # WARNING: we currently take into account down instances as well
1661
      # as up ones, considering that even if they're down someone
1662
      # might want to start them even in the event of a node failure.
1663
      for prinode, instances in n_img.sbp.items():
1664
        needed_mem = 0
1665
        for instance in instances:
1666
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1667
          if bep[constants.BE_AUTO_BALANCE]:
1668
            needed_mem += bep[constants.BE_MEMORY]
1669
        test = n_img.mfree < needed_mem
1670
        self._ErrorIf(test, self.ENODEN1, node,
1671
                      "not enough memory on to accommodate"
1672
                      " failovers should peer node %s fail", prinode)
1673

    
1674
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1675
                       master_files):
1676
    """Verifies and computes the node required file checksums.
1677

1678
    @type ninfo: L{objects.Node}
1679
    @param ninfo: the node to check
1680
    @param nresult: the remote results for the node
1681
    @param file_list: required list of files
1682
    @param local_cksum: dictionary of local files and their checksums
1683
    @param master_files: list of files that only masters should have
1684

1685
    """
1686
    node = ninfo.name
1687
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1688

    
1689
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1690
    test = not isinstance(remote_cksum, dict)
1691
    _ErrorIf(test, self.ENODEFILECHECK, node,
1692
             "node hasn't returned file checksum data")
1693
    if test:
1694
      return
1695

    
1696
    for file_name in file_list:
1697
      node_is_mc = ninfo.master_candidate
1698
      must_have = (file_name not in master_files) or node_is_mc
1699
      # missing
1700
      test1 = file_name not in remote_cksum
1701
      # invalid checksum
1702
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1703
      # existing and good
1704
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1705
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1706
               "file '%s' missing", file_name)
1707
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1708
               "file '%s' has wrong checksum", file_name)
1709
      # not candidate and this is not a must-have file
1710
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1711
               "file '%s' should not exist on non master"
1712
               " candidates (and the file is outdated)", file_name)
1713
      # all good, except non-master/non-must have combination
1714
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1715
               "file '%s' should not exist"
1716
               " on non master candidates", file_name)
1717

    
1718
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1719
    """Verifies and the node DRBD status.
1720

1721
    @type ninfo: L{objects.Node}
1722
    @param ninfo: the node to check
1723
    @param nresult: the remote results for the node
1724
    @param instanceinfo: the dict of instances
1725
    @param drbd_map: the DRBD map as returned by
1726
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1727

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

    
1732
    # compute the DRBD minors
1733
    node_drbd = {}
1734
    for minor, instance in drbd_map[node].items():
1735
      test = instance not in instanceinfo
1736
      _ErrorIf(test, self.ECLUSTERCFG, None,
1737
               "ghost instance '%s' in temporary DRBD map", instance)
1738
        # ghost instance should not be running, but otherwise we
1739
        # don't give double warnings (both ghost instance and
1740
        # unallocated minor in use)
1741
      if test:
1742
        node_drbd[minor] = (instance, False)
1743
      else:
1744
        instance = instanceinfo[instance]
1745
        node_drbd[minor] = (instance.name, instance.admin_up)
1746

    
1747
    # and now check them
1748
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1749
    test = not isinstance(used_minors, (tuple, list))
1750
    _ErrorIf(test, self.ENODEDRBD, node,
1751
             "cannot parse drbd status file: %s", str(used_minors))
1752
    if test:
1753
      # we cannot check drbd status
1754
      return
1755

    
1756
    for minor, (iname, must_exist) in node_drbd.items():
1757
      test = minor not in used_minors and must_exist
1758
      _ErrorIf(test, self.ENODEDRBD, node,
1759
               "drbd minor %d of instance %s is not active", minor, iname)
1760
    for minor in used_minors:
1761
      test = minor not in node_drbd
1762
      _ErrorIf(test, self.ENODEDRBD, node,
1763
               "unallocated drbd minor %d is in use", minor)
1764

    
1765
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1766
    """Builds the node OS structures.
1767

1768
    @type ninfo: L{objects.Node}
1769
    @param ninfo: the node to check
1770
    @param nresult: the remote results for the node
1771
    @param nimg: the node image object
1772

1773
    """
1774
    node = ninfo.name
1775
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1776

    
1777
    remote_os = nresult.get(constants.NV_OSLIST, None)
1778
    test = (not isinstance(remote_os, list) or
1779
            not compat.all(isinstance(v, list) and len(v) == 7
1780
                           for v in remote_os))
1781

    
1782
    _ErrorIf(test, self.ENODEOS, node,
1783
             "node hasn't returned valid OS data")
1784

    
1785
    nimg.os_fail = test
1786

    
1787
    if test:
1788
      return
1789

    
1790
    os_dict = {}
1791

    
1792
    for (name, os_path, status, diagnose,
1793
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1794

    
1795
      if name not in os_dict:
1796
        os_dict[name] = []
1797

    
1798
      # parameters is a list of lists instead of list of tuples due to
1799
      # JSON lacking a real tuple type, fix it:
1800
      parameters = [tuple(v) for v in parameters]
1801
      os_dict[name].append((os_path, status, diagnose,
1802
                            set(variants), set(parameters), set(api_ver)))
1803

    
1804
    nimg.oslist = os_dict
1805

    
1806
  def _VerifyNodeOS(self, ninfo, nimg, base):
1807
    """Verifies the node OS list.
1808

1809
    @type ninfo: L{objects.Node}
1810
    @param ninfo: the node to check
1811
    @param nimg: the node image object
1812
    @param base: the 'template' node we match against (e.g. from the master)
1813

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

    
1818
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1819

    
1820
    for os_name, os_data in nimg.oslist.items():
1821
      assert os_data, "Empty OS status for OS %s?!" % os_name
1822
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1823
      _ErrorIf(not f_status, self.ENODEOS, node,
1824
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1825
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1826
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1827
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1828
      # this will catched in backend too
1829
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1830
               and not f_var, self.ENODEOS, node,
1831
               "OS %s with API at least %d does not declare any variant",
1832
               os_name, constants.OS_API_V15)
1833
      # comparisons with the 'base' image
1834
      test = os_name not in base.oslist
1835
      _ErrorIf(test, self.ENODEOS, node,
1836
               "Extra OS %s not present on reference node (%s)",
1837
               os_name, base.name)
1838
      if test:
1839
        continue
1840
      assert base.oslist[os_name], "Base node has empty OS status?"
1841
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1842
      if not b_status:
1843
        # base OS is invalid, skipping
1844
        continue
1845
      for kind, a, b in [("API version", f_api, b_api),
1846
                         ("variants list", f_var, b_var),
1847
                         ("parameters", f_param, b_param)]:
1848
        _ErrorIf(a != b, self.ENODEOS, node,
1849
                 "OS %s %s differs from reference node %s: %s vs. %s",
1850
                 kind, os_name, base.name,
1851
                 utils.CommaJoin(a), utils.CommaJoin(b))
1852

    
1853
    # check any missing OSes
1854
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1855
    _ErrorIf(missing, self.ENODEOS, node,
1856
             "OSes present on reference node %s but missing on this node: %s",
1857
             base.name, utils.CommaJoin(missing))
1858

    
1859
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1860
    """Verifies and updates the node volume data.
1861

1862
    This function will update a L{NodeImage}'s internal structures
1863
    with data from the remote call.
1864

1865
    @type ninfo: L{objects.Node}
1866
    @param ninfo: the node to check
1867
    @param nresult: the remote results for the node
1868
    @param nimg: the node image object
1869
    @param vg_name: the configured VG name
1870

1871
    """
1872
    node = ninfo.name
1873
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1874

    
1875
    nimg.lvm_fail = True
1876
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1877
    if vg_name is None:
1878
      pass
1879
    elif isinstance(lvdata, basestring):
1880
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1881
               utils.SafeEncode(lvdata))
1882
    elif not isinstance(lvdata, dict):
1883
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1884
    else:
1885
      nimg.volumes = lvdata
1886
      nimg.lvm_fail = False
1887

    
1888
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1889
    """Verifies and updates the node instance list.
1890

1891
    If the listing was successful, then updates this node's instance
1892
    list. Otherwise, it marks the RPC call as failed for the instance
1893
    list key.
1894

1895
    @type ninfo: L{objects.Node}
1896
    @param ninfo: the node to check
1897
    @param nresult: the remote results for the node
1898
    @param nimg: the node image object
1899

1900
    """
1901
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1902
    test = not isinstance(idata, list)
1903
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1904
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1905
    if test:
1906
      nimg.hyp_fail = True
1907
    else:
1908
      nimg.instances = idata
1909

    
1910
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1911
    """Verifies and computes a node information map
1912

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

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

    
1923
    # try to read free memory (from the hypervisor)
1924
    hv_info = nresult.get(constants.NV_HVINFO, None)
1925
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1926
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1927
    if not test:
1928
      try:
1929
        nimg.mfree = int(hv_info["memory_free"])
1930
      except (ValueError, TypeError):
1931
        _ErrorIf(True, self.ENODERPC, node,
1932
                 "node returned invalid nodeinfo, check hypervisor")
1933

    
1934
    # FIXME: devise a free space model for file based instances as well
1935
    if vg_name is not None:
1936
      test = (constants.NV_VGLIST not in nresult or
1937
              vg_name not in nresult[constants.NV_VGLIST])
1938
      _ErrorIf(test, self.ENODELVM, node,
1939
               "node didn't return data for the volume group '%s'"
1940
               " - it is either missing or broken", vg_name)
1941
      if not test:
1942
        try:
1943
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1944
        except (ValueError, TypeError):
1945
          _ErrorIf(True, self.ENODERPC, node,
1946
                   "node returned invalid LVM info, check LVM status")
1947

    
1948
  def BuildHooksEnv(self):
1949
    """Build hooks env.
1950

1951
    Cluster-Verify hooks just ran in the post phase and their failure makes
1952
    the output be logged in the verify output and the verification to fail.
1953

1954
    """
1955
    all_nodes = self.cfg.GetNodeList()
1956
    env = {
1957
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1958
      }
1959
    for node in self.cfg.GetAllNodesInfo().values():
1960
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1961

    
1962
    return env, [], all_nodes
1963

    
1964
  def Exec(self, feedback_fn):
1965
    """Verify integrity of cluster, performing various test on nodes.
1966

1967
    """
1968
    self.bad = False
1969
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1970
    verbose = self.op.verbose
1971
    self._feedback_fn = feedback_fn
1972
    feedback_fn("* Verifying global settings")
1973
    for msg in self.cfg.VerifyConfig():
1974
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1975

    
1976
    # Check the cluster certificates
1977
    for cert_filename in constants.ALL_CERT_FILES:
1978
      (errcode, msg) = _VerifyCertificate(cert_filename)
1979
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1980

    
1981
    vg_name = self.cfg.GetVGName()
1982
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1983
    cluster = self.cfg.GetClusterInfo()
1984
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1985
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1986
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1987
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1988
                        for iname in instancelist)
1989
    i_non_redundant = [] # Non redundant instances
1990
    i_non_a_balanced = [] # Non auto-balanced instances
1991
    n_offline = 0 # Count of offline nodes
1992
    n_drained = 0 # Count of nodes being drained
1993
    node_vol_should = {}
1994

    
1995
    # FIXME: verify OS list
1996
    # do local checksums
1997
    master_files = [constants.CLUSTER_CONF_FILE]
1998
    master_node = self.master_node = self.cfg.GetMasterNode()
1999
    master_ip = self.cfg.GetMasterIP()
2000

    
2001
    file_names = ssconf.SimpleStore().GetFileList()
2002
    file_names.extend(constants.ALL_CERT_FILES)
2003
    file_names.extend(master_files)
2004
    if cluster.modify_etc_hosts:
2005
      file_names.append(constants.ETC_HOSTS)
2006

    
2007
    local_checksums = utils.FingerprintFiles(file_names)
2008

    
2009
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2010
    node_verify_param = {
2011
      constants.NV_FILELIST: file_names,
2012
      constants.NV_NODELIST: [node.name for node in nodeinfo
2013
                              if not node.offline],
2014
      constants.NV_HYPERVISOR: hypervisors,
2015
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2016
                                  node.secondary_ip) for node in nodeinfo
2017
                                 if not node.offline],
2018
      constants.NV_INSTANCELIST: hypervisors,
2019
      constants.NV_VERSION: None,
2020
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2021
      constants.NV_NODESETUP: None,
2022
      constants.NV_TIME: None,
2023
      constants.NV_MASTERIP: (master_node, master_ip),
2024
      constants.NV_OSLIST: None,
2025
      }
2026

    
2027
    if vg_name is not None:
2028
      node_verify_param[constants.NV_VGLIST] = None
2029
      node_verify_param[constants.NV_LVLIST] = vg_name
2030
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2031
      node_verify_param[constants.NV_DRBDLIST] = None
2032

    
2033
    # Build our expected cluster state
2034
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2035
                                                 name=node.name))
2036
                      for node in nodeinfo)
2037

    
2038
    for instance in instancelist:
2039
      inst_config = instanceinfo[instance]
2040

    
2041
      for nname in inst_config.all_nodes:
2042
        if nname not in node_image:
2043
          # ghost node
2044
          gnode = self.NodeImage(name=nname)
2045
          gnode.ghost = True
2046
          node_image[nname] = gnode
2047

    
2048
      inst_config.MapLVsByNode(node_vol_should)
2049

    
2050
      pnode = inst_config.primary_node
2051
      node_image[pnode].pinst.append(instance)
2052

    
2053
      for snode in inst_config.secondary_nodes:
2054
        nimg = node_image[snode]
2055
        nimg.sinst.append(instance)
2056
        if pnode not in nimg.sbp:
2057
          nimg.sbp[pnode] = []
2058
        nimg.sbp[pnode].append(instance)
2059

    
2060
    # At this point, we have the in-memory data structures complete,
2061
    # except for the runtime information, which we'll gather next
2062

    
2063
    # Due to the way our RPC system works, exact response times cannot be
2064
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2065
    # time before and after executing the request, we can at least have a time
2066
    # window.
2067
    nvinfo_starttime = time.time()
2068
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2069
                                           self.cfg.GetClusterName())
2070
    nvinfo_endtime = time.time()
2071

    
2072
    all_drbd_map = self.cfg.ComputeDRBDMap()
2073

    
2074
    feedback_fn("* Verifying node status")
2075

    
2076
    refos_img = None
2077

    
2078
    for node_i in nodeinfo:
2079
      node = node_i.name
2080
      nimg = node_image[node]
2081

    
2082
      if node_i.offline:
2083
        if verbose:
2084
          feedback_fn("* Skipping offline node %s" % (node,))
2085
        n_offline += 1
2086
        continue
2087

    
2088
      if node == master_node:
2089
        ntype = "master"
2090
      elif node_i.master_candidate:
2091
        ntype = "master candidate"
2092
      elif node_i.drained:
2093
        ntype = "drained"
2094
        n_drained += 1
2095
      else:
2096
        ntype = "regular"
2097
      if verbose:
2098
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2099

    
2100
      msg = all_nvinfo[node].fail_msg
2101
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2102
      if msg:
2103
        nimg.rpc_fail = True
2104
        continue
2105

    
2106
      nresult = all_nvinfo[node].payload
2107

    
2108
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2109
      self._VerifyNodeNetwork(node_i, nresult)
2110
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2111
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2112
                            master_files)
2113
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
2114
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2115

    
2116
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2117
      self._UpdateNodeInstances(node_i, nresult, nimg)
2118
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2119
      self._UpdateNodeOS(node_i, nresult, nimg)
2120
      if not nimg.os_fail:
2121
        if refos_img is None:
2122
          refos_img = nimg
2123
        self._VerifyNodeOS(node_i, nimg, refos_img)
2124

    
2125
    feedback_fn("* Verifying instance status")
2126
    for instance in instancelist:
2127
      if verbose:
2128
        feedback_fn("* Verifying instance %s" % instance)
2129
      inst_config = instanceinfo[instance]
2130
      self._VerifyInstance(instance, inst_config, node_image)
2131
      inst_nodes_offline = []
2132

    
2133
      pnode = inst_config.primary_node
2134
      pnode_img = node_image[pnode]
2135
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2136
               self.ENODERPC, pnode, "instance %s, connection to"
2137
               " primary node failed", instance)
2138

    
2139
      if pnode_img.offline:
2140
        inst_nodes_offline.append(pnode)
2141

    
2142
      # If the instance is non-redundant we cannot survive losing its primary
2143
      # node, so we are not N+1 compliant. On the other hand we have no disk
2144
      # templates with more than one secondary so that situation is not well
2145
      # supported either.
2146
      # FIXME: does not support file-backed instances
2147
      if not inst_config.secondary_nodes:
2148
        i_non_redundant.append(instance)
2149
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2150
               instance, "instance has multiple secondary nodes: %s",
2151
               utils.CommaJoin(inst_config.secondary_nodes),
2152
               code=self.ETYPE_WARNING)
2153

    
2154
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2155
        i_non_a_balanced.append(instance)
2156

    
2157
      for snode in inst_config.secondary_nodes:
2158
        s_img = node_image[snode]
2159
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2160
                 "instance %s, connection to secondary node failed", instance)
2161

    
2162
        if s_img.offline:
2163
          inst_nodes_offline.append(snode)
2164

    
2165
      # warn that the instance lives on offline nodes
2166
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2167
               "instance lives on offline node(s) %s",
2168
               utils.CommaJoin(inst_nodes_offline))
2169
      # ... or ghost nodes
2170
      for node in inst_config.all_nodes:
2171
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2172
                 "instance lives on ghost node %s", node)
2173

    
2174
    feedback_fn("* Verifying orphan volumes")
2175
    self._VerifyOrphanVolumes(node_vol_should, node_image)
2176

    
2177
    feedback_fn("* Verifying orphan instances")
2178
    self._VerifyOrphanInstances(instancelist, node_image)
2179

    
2180
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2181
      feedback_fn("* Verifying N+1 Memory redundancy")
2182
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2183

    
2184
    feedback_fn("* Other Notes")
2185
    if i_non_redundant:
2186
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2187
                  % len(i_non_redundant))
2188

    
2189
    if i_non_a_balanced:
2190
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2191
                  % len(i_non_a_balanced))
2192

    
2193
    if n_offline:
2194
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2195

    
2196
    if n_drained:
2197
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2198

    
2199
    return not self.bad
2200

    
2201
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2202
    """Analyze the post-hooks' result
2203

2204
    This method analyses the hook result, handles it, and sends some
2205
    nicely-formatted feedback back to the user.
2206

2207
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2208
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2209
    @param hooks_results: the results of the multi-node hooks rpc call
2210
    @param feedback_fn: function used send feedback back to the caller
2211
    @param lu_result: previous Exec result
2212
    @return: the new Exec result, based on the previous result
2213
        and hook results
2214

2215
    """
2216
    # We only really run POST phase hooks, and are only interested in
2217
    # their results
2218
    if phase == constants.HOOKS_PHASE_POST:
2219
      # Used to change hooks' output to proper indentation
2220
      indent_re = re.compile('^', re.M)
2221
      feedback_fn("* Hooks Results")
2222
      assert hooks_results, "invalid result from hooks"
2223

    
2224
      for node_name in hooks_results:
2225
        res = hooks_results[node_name]
2226
        msg = res.fail_msg
2227
        test = msg and not res.offline
2228
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2229
                      "Communication failure in hooks execution: %s", msg)
2230
        if res.offline or msg:
2231
          # No need to investigate payload if node is offline or gave an error.
2232
          # override manually lu_result here as _ErrorIf only
2233
          # overrides self.bad
2234
          lu_result = 1
2235
          continue
2236
        for script, hkr, output in res.payload:
2237
          test = hkr == constants.HKR_FAIL
2238
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2239
                        "Script %s failed, output:", script)
2240
          if test:
2241
            output = indent_re.sub('      ', output)
2242
            feedback_fn("%s" % output)
2243
            lu_result = 0
2244

    
2245
      return lu_result
2246

    
2247

    
2248
class LUVerifyDisks(NoHooksLU):
2249
  """Verifies the cluster disks status.
2250

2251
  """
2252
  REQ_BGL = False
2253

    
2254
  def ExpandNames(self):
2255
    self.needed_locks = {
2256
      locking.LEVEL_NODE: locking.ALL_SET,
2257
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2258
    }
2259
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2260

    
2261
  def Exec(self, feedback_fn):
2262
    """Verify integrity of cluster disks.
2263

2264
    @rtype: tuple of three items
2265
    @return: a tuple of (dict of node-to-node_error, list of instances
2266
        which need activate-disks, dict of instance: (node, volume) for
2267
        missing volumes
2268

2269
    """
2270
    result = res_nodes, res_instances, res_missing = {}, [], {}
2271

    
2272
    vg_name = self.cfg.GetVGName()
2273
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2274
    instances = [self.cfg.GetInstanceInfo(name)
2275
                 for name in self.cfg.GetInstanceList()]
2276

    
2277
    nv_dict = {}
2278
    for inst in instances:
2279
      inst_lvs = {}
2280
      if (not inst.admin_up or
2281
          inst.disk_template not in constants.DTS_NET_MIRROR):
2282
        continue
2283
      inst.MapLVsByNode(inst_lvs)
2284
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2285
      for node, vol_list in inst_lvs.iteritems():
2286
        for vol in vol_list:
2287
          nv_dict[(node, vol)] = inst
2288

    
2289
    if not nv_dict:
2290
      return result
2291

    
2292
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2293

    
2294
    for node in nodes:
2295
      # node_volume
2296
      node_res = node_lvs[node]
2297
      if node_res.offline:
2298
        continue
2299
      msg = node_res.fail_msg
2300
      if msg:
2301
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2302
        res_nodes[node] = msg
2303
        continue
2304

    
2305
      lvs = node_res.payload
2306
      for lv_name, (_, _, lv_online) in lvs.items():
2307
        inst = nv_dict.pop((node, lv_name), None)
2308
        if (not lv_online and inst is not None
2309
            and inst.name not in res_instances):
2310
          res_instances.append(inst.name)
2311

    
2312
    # any leftover items in nv_dict are missing LVs, let's arrange the
2313
    # data better
2314
    for key, inst in nv_dict.iteritems():
2315
      if inst.name not in res_missing:
2316
        res_missing[inst.name] = []
2317
      res_missing[inst.name].append(key)
2318

    
2319
    return result
2320

    
2321

    
2322
class LURepairDiskSizes(NoHooksLU):
2323
  """Verifies the cluster disks sizes.
2324

2325
  """
2326
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2327
  REQ_BGL = False
2328

    
2329
  def ExpandNames(self):
2330
    if self.op.instances:
2331
      self.wanted_names = []
2332
      for name in self.op.instances:
2333
        full_name = _ExpandInstanceName(self.cfg, name)
2334
        self.wanted_names.append(full_name)
2335
      self.needed_locks = {
2336
        locking.LEVEL_NODE: [],
2337
        locking.LEVEL_INSTANCE: self.wanted_names,
2338
        }
2339
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2340
    else:
2341
      self.wanted_names = None
2342
      self.needed_locks = {
2343
        locking.LEVEL_NODE: locking.ALL_SET,
2344
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2345
        }
2346
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2347

    
2348
  def DeclareLocks(self, level):
2349
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2350
      self._LockInstancesNodes(primary_only=True)
2351

    
2352
  def CheckPrereq(self):
2353
    """Check prerequisites.
2354

2355
    This only checks the optional instance list against the existing names.
2356

2357
    """
2358
    if self.wanted_names is None:
2359
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2360

    
2361
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2362
                             in self.wanted_names]
2363

    
2364
  def _EnsureChildSizes(self, disk):
2365
    """Ensure children of the disk have the needed disk size.
2366

2367
    This is valid mainly for DRBD8 and fixes an issue where the
2368
    children have smaller disk size.
2369

2370
    @param disk: an L{ganeti.objects.Disk} object
2371

2372
    """
2373
    if disk.dev_type == constants.LD_DRBD8:
2374
      assert disk.children, "Empty children for DRBD8?"
2375
      fchild = disk.children[0]
2376
      mismatch = fchild.size < disk.size
2377
      if mismatch:
2378
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2379
                     fchild.size, disk.size)
2380
        fchild.size = disk.size
2381

    
2382
      # and we recurse on this child only, not on the metadev
2383
      return self._EnsureChildSizes(fchild) or mismatch
2384
    else:
2385
      return False
2386

    
2387
  def Exec(self, feedback_fn):
2388
    """Verify the size of cluster disks.
2389

2390
    """
2391
    # TODO: check child disks too
2392
    # TODO: check differences in size between primary/secondary nodes
2393
    per_node_disks = {}
2394
    for instance in self.wanted_instances:
2395
      pnode = instance.primary_node
2396
      if pnode not in per_node_disks:
2397
        per_node_disks[pnode] = []
2398
      for idx, disk in enumerate(instance.disks):
2399
        per_node_disks[pnode].append((instance, idx, disk))
2400

    
2401
    changed = []
2402
    for node, dskl in per_node_disks.items():
2403
      newl = [v[2].Copy() for v in dskl]
2404
      for dsk in newl:
2405
        self.cfg.SetDiskID(dsk, node)
2406
      result = self.rpc.call_blockdev_getsizes(node, newl)
2407
      if result.fail_msg:
2408
        self.LogWarning("Failure in blockdev_getsizes call to node"
2409
                        " %s, ignoring", node)
2410
        continue
2411
      if len(result.data) != len(dskl):
2412
        self.LogWarning("Invalid result from node %s, ignoring node results",
2413
                        node)
2414
        continue
2415
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2416
        if size is None:
2417
          self.LogWarning("Disk %d of instance %s did not return size"
2418
                          " information, ignoring", idx, instance.name)
2419
          continue
2420
        if not isinstance(size, (int, long)):
2421
          self.LogWarning("Disk %d of instance %s did not return valid"
2422
                          " size information, ignoring", idx, instance.name)
2423
          continue
2424
        size = size >> 20
2425
        if size != disk.size:
2426
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2427
                       " correcting: recorded %d, actual %d", idx,
2428
                       instance.name, disk.size, size)
2429
          disk.size = size
2430
          self.cfg.Update(instance, feedback_fn)
2431
          changed.append((instance.name, idx, size))
2432
        if self._EnsureChildSizes(disk):
2433
          self.cfg.Update(instance, feedback_fn)
2434
          changed.append((instance.name, idx, disk.size))
2435
    return changed
2436

    
2437

    
2438
class LURenameCluster(LogicalUnit):
2439
  """Rename the cluster.
2440

2441
  """
2442
  HPATH = "cluster-rename"
2443
  HTYPE = constants.HTYPE_CLUSTER
2444
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2445

    
2446
  def BuildHooksEnv(self):
2447
    """Build hooks env.
2448

2449
    """
2450
    env = {
2451
      "OP_TARGET": self.cfg.GetClusterName(),
2452
      "NEW_NAME": self.op.name,
2453
      }
2454
    mn = self.cfg.GetMasterNode()
2455
    all_nodes = self.cfg.GetNodeList()
2456
    return env, [mn], all_nodes
2457

    
2458
  def CheckPrereq(self):
2459
    """Verify that the passed name is a valid one.
2460

2461
    """
2462
    hostname = utils.GetHostInfo(self.op.name)
2463

    
2464
    new_name = hostname.name
2465
    self.ip = new_ip = hostname.ip
2466
    old_name = self.cfg.GetClusterName()
2467
    old_ip = self.cfg.GetMasterIP()
2468
    if new_name == old_name and new_ip == old_ip:
2469
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2470
                                 " cluster has changed",
2471
                                 errors.ECODE_INVAL)
2472
    if new_ip != old_ip:
2473
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2474
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2475
                                   " reachable on the network. Aborting." %
2476
                                   new_ip, errors.ECODE_NOTUNIQUE)
2477

    
2478
    self.op.name = new_name
2479

    
2480
  def Exec(self, feedback_fn):
2481
    """Rename the cluster.
2482

2483
    """
2484
    clustername = self.op.name
2485
    ip = self.ip
2486

    
2487
    # shutdown the master IP
2488
    master = self.cfg.GetMasterNode()
2489
    result = self.rpc.call_node_stop_master(master, False)
2490
    result.Raise("Could not disable the master role")
2491

    
2492
    try:
2493
      cluster = self.cfg.GetClusterInfo()
2494
      cluster.cluster_name = clustername
2495
      cluster.master_ip = ip
2496
      self.cfg.Update(cluster, feedback_fn)
2497

    
2498
      # update the known hosts file
2499
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2500
      node_list = self.cfg.GetNodeList()
2501
      try:
2502
        node_list.remove(master)
2503
      except ValueError:
2504
        pass
2505
      result = self.rpc.call_upload_file(node_list,
2506
                                         constants.SSH_KNOWN_HOSTS_FILE)
2507
      for to_node, to_result in result.iteritems():
2508
        msg = to_result.fail_msg
2509
        if msg:
2510
          msg = ("Copy of file %s to node %s failed: %s" %
2511
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2512
          self.proc.LogWarning(msg)
2513

    
2514
    finally:
2515
      result = self.rpc.call_node_start_master(master, False, False)
2516
      msg = result.fail_msg
2517
      if msg:
2518
        self.LogWarning("Could not re-enable the master role on"
2519
                        " the master, please restart manually: %s", msg)
2520

    
2521

    
2522
class LUSetClusterParams(LogicalUnit):
2523
  """Change the parameters of the cluster.
2524

2525
  """
2526
  HPATH = "cluster-modify"
2527
  HTYPE = constants.HTYPE_CLUSTER
2528
  _OP_PARAMS = [
2529
    ("vg_name", None, _TMaybeString),
2530
    ("enabled_hypervisors", None,
2531
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2532
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2533
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2534
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2535
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2536
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2537
    ("uid_pool", None, _NoType),
2538
    ("add_uids", None, _NoType),
2539
    ("remove_uids", None, _NoType),
2540
    ("maintain_node_health", None, _TMaybeBool),
2541
    ("nicparams", None, _TOr(_TDict, _TNone)),
2542
    ]
2543
  REQ_BGL = False
2544

    
2545
  def CheckArguments(self):
2546
    """Check parameters
2547

2548
    """
2549
    if self.op.uid_pool:
2550
      uidpool.CheckUidPool(self.op.uid_pool)
2551

    
2552
    if self.op.add_uids:
2553
      uidpool.CheckUidPool(self.op.add_uids)
2554

    
2555
    if self.op.remove_uids:
2556
      uidpool.CheckUidPool(self.op.remove_uids)
2557

    
2558
  def ExpandNames(self):
2559
    # FIXME: in the future maybe other cluster params won't require checking on
2560
    # all nodes to be modified.
2561
    self.needed_locks = {
2562
      locking.LEVEL_NODE: locking.ALL_SET,
2563
    }
2564
    self.share_locks[locking.LEVEL_NODE] = 1
2565

    
2566
  def BuildHooksEnv(self):
2567
    """Build hooks env.
2568

2569
    """
2570
    env = {
2571
      "OP_TARGET": self.cfg.GetClusterName(),
2572
      "NEW_VG_NAME": self.op.vg_name,
2573
      }
2574
    mn = self.cfg.GetMasterNode()
2575
    return env, [mn], [mn]
2576

    
2577
  def CheckPrereq(self):
2578
    """Check prerequisites.
2579

2580
    This checks whether the given params don't conflict and
2581
    if the given volume group is valid.
2582

2583
    """
2584
    if self.op.vg_name is not None and not self.op.vg_name:
2585
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2586
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2587
                                   " instances exist", errors.ECODE_INVAL)
2588

    
2589
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2590

    
2591
    # if vg_name not None, checks given volume group on all nodes
2592
    if self.op.vg_name:
2593
      vglist = self.rpc.call_vg_list(node_list)
2594
      for node in node_list:
2595
        msg = vglist[node].fail_msg
2596
        if msg:
2597
          # ignoring down node
2598
          self.LogWarning("Error while gathering data on node %s"
2599
                          " (ignoring node): %s", node, msg)
2600
          continue
2601
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2602
                                              self.op.vg_name,
2603
                                              constants.MIN_VG_SIZE)
2604
        if vgstatus:
2605
          raise errors.OpPrereqError("Error on node '%s': %s" %
2606
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2607

    
2608
    self.cluster = cluster = self.cfg.GetClusterInfo()
2609
    # validate params changes
2610
    if self.op.beparams:
2611
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2612
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2613

    
2614
    if self.op.nicparams:
2615
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2616
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2617
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2618
      nic_errors = []
2619

    
2620
      # check all instances for consistency
2621
      for instance in self.cfg.GetAllInstancesInfo().values():
2622
        for nic_idx, nic in enumerate(instance.nics):
2623
          params_copy = copy.deepcopy(nic.nicparams)
2624
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2625

    
2626
          # check parameter syntax
2627
          try:
2628
            objects.NIC.CheckParameterSyntax(params_filled)
2629
          except errors.ConfigurationError, err:
2630
            nic_errors.append("Instance %s, nic/%d: %s" %
2631
                              (instance.name, nic_idx, err))
2632

    
2633
          # if we're moving instances to routed, check that they have an ip
2634
          target_mode = params_filled[constants.NIC_MODE]
2635
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2636
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2637
                              (instance.name, nic_idx))
2638
      if nic_errors:
2639
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2640
                                   "\n".join(nic_errors))
2641

    
2642
    # hypervisor list/parameters
2643
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2644
    if self.op.hvparams:
2645
      for hv_name, hv_dict in self.op.hvparams.items():
2646
        if hv_name not in self.new_hvparams:
2647
          self.new_hvparams[hv_name] = hv_dict
2648
        else:
2649
          self.new_hvparams[hv_name].update(hv_dict)
2650

    
2651
    # os hypervisor parameters
2652
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2653
    if self.op.os_hvp:
2654
      for os_name, hvs in self.op.os_hvp.items():
2655
        if os_name not in self.new_os_hvp:
2656
          self.new_os_hvp[os_name] = hvs
2657
        else:
2658
          for hv_name, hv_dict in hvs.items():
2659
            if hv_name not in self.new_os_hvp[os_name]:
2660
              self.new_os_hvp[os_name][hv_name] = hv_dict
2661
            else:
2662
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2663

    
2664
    # os parameters
2665
    self.new_osp = objects.FillDict(cluster.osparams, {})
2666
    if self.op.osparams:
2667
      for os_name, osp in self.op.osparams.items():
2668
        if os_name not in self.new_osp:
2669
          self.new_osp[os_name] = {}
2670

    
2671
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2672
                                                  use_none=True)
2673

    
2674
        if not self.new_osp[os_name]:
2675
          # we removed all parameters
2676
          del self.new_osp[os_name]
2677
        else:
2678
          # check the parameter validity (remote check)
2679
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2680
                         os_name, self.new_osp[os_name])
2681

    
2682
    # changes to the hypervisor list
2683
    if self.op.enabled_hypervisors is not None:
2684
      self.hv_list = self.op.enabled_hypervisors
2685
      for hv in self.hv_list:
2686
        # if the hypervisor doesn't already exist in the cluster
2687
        # hvparams, we initialize it to empty, and then (in both
2688
        # cases) we make sure to fill the defaults, as we might not
2689
        # have a complete defaults list if the hypervisor wasn't
2690
        # enabled before
2691
        if hv not in new_hvp:
2692
          new_hvp[hv] = {}
2693
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2694
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2695
    else:
2696
      self.hv_list = cluster.enabled_hypervisors
2697

    
2698
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2699
      # either the enabled list has changed, or the parameters have, validate
2700
      for hv_name, hv_params in self.new_hvparams.items():
2701
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2702
            (self.op.enabled_hypervisors and
2703
             hv_name in self.op.enabled_hypervisors)):
2704
          # either this is a new hypervisor, or its parameters have changed
2705
          hv_class = hypervisor.GetHypervisor(hv_name)
2706
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2707
          hv_class.CheckParameterSyntax(hv_params)
2708
          _CheckHVParams(self, node_list, hv_name, hv_params)
2709

    
2710
    if self.op.os_hvp:
2711
      # no need to check any newly-enabled hypervisors, since the
2712
      # defaults have already been checked in the above code-block
2713
      for os_name, os_hvp in self.new_os_hvp.items():
2714
        for hv_name, hv_params in os_hvp.items():
2715
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2716
          # we need to fill in the new os_hvp on top of the actual hv_p
2717
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2718
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2719
          hv_class = hypervisor.GetHypervisor(hv_name)
2720
          hv_class.CheckParameterSyntax(new_osp)
2721
          _CheckHVParams(self, node_list, hv_name, new_osp)
2722

    
2723

    
2724
  def Exec(self, feedback_fn):
2725
    """Change the parameters of the cluster.
2726

2727
    """
2728
    if self.op.vg_name is not None:
2729
      new_volume = self.op.vg_name
2730
      if not new_volume:
2731
        new_volume = None
2732
      if new_volume != self.cfg.GetVGName():
2733
        self.cfg.SetVGName(new_volume)
2734
      else:
2735
        feedback_fn("Cluster LVM configuration already in desired"
2736
                    " state, not changing")
2737
    if self.op.hvparams:
2738
      self.cluster.hvparams = self.new_hvparams
2739
    if self.op.os_hvp:
2740
      self.cluster.os_hvp = self.new_os_hvp
2741
    if self.op.enabled_hypervisors is not None:
2742
      self.cluster.hvparams = self.new_hvparams
2743
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2744
    if self.op.beparams:
2745
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2746
    if self.op.nicparams:
2747
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2748
    if self.op.osparams:
2749
      self.cluster.osparams = self.new_osp
2750

    
2751
    if self.op.candidate_pool_size is not None:
2752
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2753
      # we need to update the pool size here, otherwise the save will fail
2754
      _AdjustCandidatePool(self, [])
2755

    
2756
    if self.op.maintain_node_health is not None:
2757
      self.cluster.maintain_node_health = self.op.maintain_node_health
2758

    
2759
    if self.op.add_uids is not None:
2760
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2761

    
2762
    if self.op.remove_uids is not None:
2763
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2764

    
2765
    if self.op.uid_pool is not None:
2766
      self.cluster.uid_pool = self.op.uid_pool
2767

    
2768
    self.cfg.Update(self.cluster, feedback_fn)
2769

    
2770

    
2771
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2772
  """Distribute additional files which are part of the cluster configuration.
2773

2774
  ConfigWriter takes care of distributing the config and ssconf files, but
2775
  there are more files which should be distributed to all nodes. This function
2776
  makes sure those are copied.
2777

2778
  @param lu: calling logical unit
2779
  @param additional_nodes: list of nodes not in the config to distribute to
2780

2781
  """
2782
  # 1. Gather target nodes
2783
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2784
  dist_nodes = lu.cfg.GetOnlineNodeList()
2785
  if additional_nodes is not None:
2786
    dist_nodes.extend(additional_nodes)
2787
  if myself.name in dist_nodes:
2788
    dist_nodes.remove(myself.name)
2789

    
2790
  # 2. Gather files to distribute
2791
  dist_files = set([constants.ETC_HOSTS,
2792
                    constants.SSH_KNOWN_HOSTS_FILE,
2793
                    constants.RAPI_CERT_FILE,
2794
                    constants.RAPI_USERS_FILE,
2795
                    constants.CONFD_HMAC_KEY,
2796
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2797
                   ])
2798

    
2799
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2800
  for hv_name in enabled_hypervisors:
2801
    hv_class = hypervisor.GetHypervisor(hv_name)
2802
    dist_files.update(hv_class.GetAncillaryFiles())
2803

    
2804
  # 3. Perform the files upload
2805
  for fname in dist_files:
2806
    if os.path.exists(fname):
2807
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2808
      for to_node, to_result in result.items():
2809
        msg = to_result.fail_msg
2810
        if msg:
2811
          msg = ("Copy of file %s to node %s failed: %s" %
2812
                 (fname, to_node, msg))
2813
          lu.proc.LogWarning(msg)
2814

    
2815

    
2816
class LURedistributeConfig(NoHooksLU):
2817
  """Force the redistribution of cluster configuration.
2818

2819
  This is a very simple LU.
2820

2821
  """
2822
  REQ_BGL = False
2823

    
2824
  def ExpandNames(self):
2825
    self.needed_locks = {
2826
      locking.LEVEL_NODE: locking.ALL_SET,
2827
    }
2828
    self.share_locks[locking.LEVEL_NODE] = 1
2829

    
2830
  def Exec(self, feedback_fn):
2831
    """Redistribute the configuration.
2832

2833
    """
2834
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2835
    _RedistributeAncillaryFiles(self)
2836

    
2837

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

2841
  """
2842
  if not instance.disks or disks is not None and not disks:
2843
    return True
2844

    
2845
  disks = _ExpandCheckDisks(instance, disks)
2846

    
2847
  if not oneshot:
2848
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2849

    
2850
  node = instance.primary_node
2851

    
2852
  for dev in disks:
2853
    lu.cfg.SetDiskID(dev, node)
2854

    
2855
  # TODO: Convert to utils.Retry
2856

    
2857
  retries = 0
2858
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2859
  while True:
2860
    max_time = 0
2861
    done = True
2862
    cumul_degraded = False
2863
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2864
    msg = rstats.fail_msg
2865
    if msg:
2866
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2867
      retries += 1
2868
      if retries >= 10:
2869
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2870
                                 " aborting." % node)
2871
      time.sleep(6)
2872
      continue
2873
    rstats = rstats.payload
2874
    retries = 0
2875
    for i, mstat in enumerate(rstats):
2876
      if mstat is None:
2877
        lu.LogWarning("Can't compute data for node %s/%s",
2878
                           node, disks[i].iv_name)
2879
        continue
2880

    
2881
      cumul_degraded = (cumul_degraded or
2882
                        (mstat.is_degraded and mstat.sync_percent is None))
2883
      if mstat.sync_percent is not None:
2884
        done = False
2885
        if mstat.estimated_time is not None:
2886
          rem_time = ("%s remaining (estimated)" %
2887
                      utils.FormatSeconds(mstat.estimated_time))
2888
          max_time = mstat.estimated_time
2889
        else:
2890
          rem_time = "no time estimate"
2891
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2892
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2893

    
2894
    # if we're done but degraded, let's do a few small retries, to
2895
    # make sure we see a stable and not transient situation; therefore
2896
    # we force restart of the loop
2897
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2898
      logging.info("Degraded disks found, %d retries left", degr_retries)
2899
      degr_retries -= 1
2900
      time.sleep(1)
2901
      continue
2902

    
2903
    if done or oneshot:
2904
      break
2905

    
2906
    time.sleep(min(60, max_time))
2907

    
2908
  if done:
2909
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2910
  return not cumul_degraded
2911

    
2912

    
2913
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2914
  """Check that mirrors are not degraded.
2915

2916
  The ldisk parameter, if True, will change the test from the
2917
  is_degraded attribute (which represents overall non-ok status for
2918
  the device(s)) to the ldisk (representing the local storage status).
2919

2920
  """
2921
  lu.cfg.SetDiskID(dev, node)
2922

    
2923
  result = True
2924

    
2925
  if on_primary or dev.AssembleOnSecondary():
2926
    rstats = lu.rpc.call_blockdev_find(node, dev)
2927
    msg = rstats.fail_msg
2928
    if msg:
2929
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2930
      result = False
2931
    elif not rstats.payload:
2932
      lu.LogWarning("Can't find disk on node %s", node)
2933
      result = False
2934
    else:
2935
      if ldisk:
2936
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2937
      else:
2938
        result = result and not rstats.payload.is_degraded
2939

    
2940
  if dev.children:
2941
    for child in dev.children:
2942
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2943

    
2944
  return result
2945

    
2946

    
2947
class LUDiagnoseOS(NoHooksLU):
2948
  """Logical unit for OS diagnose/query.
2949

2950
  """
2951
  _OP_PARAMS = [
2952
    _POutputFields,
2953
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
2954
    ]
2955
  REQ_BGL = False
2956
  _FIELDS_STATIC = utils.FieldSet()
2957
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
2958
                                   "parameters", "api_versions")
2959

    
2960
  def CheckArguments(self):
2961
    if self.op.names:
2962
      raise errors.OpPrereqError("Selective OS query not supported",
2963
                                 errors.ECODE_INVAL)
2964

    
2965
    _CheckOutputFields(static=self._FIELDS_STATIC,
2966
                       dynamic=self._FIELDS_DYNAMIC,
2967
                       selected=self.op.output_fields)
2968

    
2969
  def ExpandNames(self):
2970
    # Lock all nodes, in shared mode
2971
    # Temporary removal of locks, should be reverted later
2972
    # TODO: reintroduce locks when they are lighter-weight
2973
    self.needed_locks = {}
2974
    #self.share_locks[locking.LEVEL_NODE] = 1
2975
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
2976

    
2977
  @staticmethod
2978
  def _DiagnoseByOS(rlist):
2979
    """Remaps a per-node return list into an a per-os per-node dictionary
2980

2981
    @param rlist: a map with node names as keys and OS objects as values
2982

2983
    @rtype: dict
2984
    @return: a dictionary with osnames as keys and as value another
2985
        map, with nodes as keys and tuples of (path, status, diagnose,
2986
        variants, parameters, api_versions) as values, eg::
2987

2988
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
2989
                                     (/srv/..., False, "invalid api")],
2990
                           "node2": [(/srv/..., True, "", [], [])]}
2991
          }
2992

2993
    """
2994
    all_os = {}
2995
    # we build here the list of nodes that didn't fail the RPC (at RPC
2996
    # level), so that nodes with a non-responding node daemon don't
2997
    # make all OSes invalid
2998
    good_nodes = [node_name for node_name in rlist
2999
                  if not rlist[node_name].fail_msg]
3000
    for node_name, nr in rlist.items():
3001
      if nr.fail_msg or not nr.payload:
3002
        continue
3003
      for (name, path, status, diagnose, variants,
3004
           params, api_versions) in nr.payload:
3005
        if name not in all_os:
3006
          # build a list of nodes for this os containing empty lists
3007
          # for each node in node_list
3008
          all_os[name] = {}
3009
          for nname in good_nodes:
3010
            all_os[name][nname] = []
3011
        # convert params from [name, help] to (name, help)
3012
        params = [tuple(v) for v in params]
3013
        all_os[name][node_name].append((path, status, diagnose,
3014
                                        variants, params, api_versions))
3015
    return all_os
3016

    
3017
  def Exec(self, feedback_fn):
3018
    """Compute the list of OSes.
3019

3020
    """
3021
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3022
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3023
    pol = self._DiagnoseByOS(node_data)
3024
    output = []
3025

    
3026
    for os_name, os_data in pol.items():
3027
      row = []
3028
      valid = True
3029
      (variants, params, api_versions) = null_state = (set(), set(), set())
3030
      for idx, osl in enumerate(os_data.values()):
3031
        valid = bool(valid and osl and osl[0][1])
3032
        if not valid:
3033
          (variants, params, api_versions) = null_state
3034
          break
3035
        node_variants, node_params, node_api = osl[0][3:6]
3036
        if idx == 0: # first entry
3037
          variants = set(node_variants)
3038
          params = set(node_params)
3039
          api_versions = set(node_api)
3040
        else: # keep consistency
3041
          variants.intersection_update(node_variants)
3042
          params.intersection_update(node_params)
3043
          api_versions.intersection_update(node_api)
3044

    
3045
      for field in self.op.output_fields:
3046
        if field == "name":
3047
          val = os_name
3048
        elif field == "valid":
3049
          val = valid
3050
        elif field == "node_status":
3051
          # this is just a copy of the dict
3052
          val = {}
3053
          for node_name, nos_list in os_data.items():
3054
            val[node_name] = nos_list
3055
        elif field == "variants":
3056
          val = list(variants)
3057
        elif field == "parameters":
3058
          val = list(params)
3059
        elif field == "api_versions":
3060
          val = list(api_versions)
3061
        else:
3062
          raise errors.ParameterError(field)
3063
        row.append(val)
3064
      output.append(row)
3065

    
3066
    return output
3067

    
3068

    
3069
class LURemoveNode(LogicalUnit):
3070
  """Logical unit for removing a node.
3071

3072
  """
3073
  HPATH = "node-remove"
3074
  HTYPE = constants.HTYPE_NODE
3075
  _OP_PARAMS = [
3076
    _PNodeName,
3077
    ]
3078

    
3079
  def BuildHooksEnv(self):
3080
    """Build hooks env.
3081

3082
    This doesn't run on the target node in the pre phase as a failed
3083
    node would then be impossible to remove.
3084

3085
    """
3086
    env = {
3087
      "OP_TARGET": self.op.node_name,
3088
      "NODE_NAME": self.op.node_name,
3089
      }
3090
    all_nodes = self.cfg.GetNodeList()
3091
    try:
3092
      all_nodes.remove(self.op.node_name)
3093
    except ValueError:
3094
      logging.warning("Node %s which is about to be removed not found"
3095
                      " in the all nodes list", self.op.node_name)
3096
    return env, all_nodes, all_nodes
3097

    
3098
  def CheckPrereq(self):
3099
    """Check prerequisites.
3100

3101
    This checks:
3102
     - the node exists in the configuration
3103
     - it does not have primary or secondary instances
3104
     - it's not the master
3105

3106
    Any errors are signaled by raising errors.OpPrereqError.
3107

3108
    """
3109
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3110
    node = self.cfg.GetNodeInfo(self.op.node_name)
3111
    assert node is not None
3112

    
3113
    instance_list = self.cfg.GetInstanceList()
3114

    
3115
    masternode = self.cfg.GetMasterNode()
3116
    if node.name == masternode:
3117
      raise errors.OpPrereqError("Node is the master node,"
3118
                                 " you need to failover first.",
3119
                                 errors.ECODE_INVAL)
3120

    
3121
    for instance_name in instance_list:
3122
      instance = self.cfg.GetInstanceInfo(instance_name)
3123
      if node.name in instance.all_nodes:
3124
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3125
                                   " please remove first." % instance_name,
3126
                                   errors.ECODE_INVAL)
3127
    self.op.node_name = node.name
3128
    self.node = node
3129

    
3130
  def Exec(self, feedback_fn):
3131
    """Removes the node from the cluster.
3132

3133
    """
3134
    node = self.node
3135
    logging.info("Stopping the node daemon and removing configs from node %s",
3136
                 node.name)
3137

    
3138
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3139

    
3140
    # Promote nodes to master candidate as needed
3141
    _AdjustCandidatePool(self, exceptions=[node.name])
3142
    self.context.RemoveNode(node.name)
3143

    
3144
    # Run post hooks on the node before it's removed
3145
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3146
    try:
3147
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3148
    except:
3149
      # pylint: disable-msg=W0702
3150
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3151

    
3152
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3153
    msg = result.fail_msg
3154
    if msg:
3155
      self.LogWarning("Errors encountered on the remote node while leaving"
3156
                      " the cluster: %s", msg)
3157

    
3158
    # Remove node from our /etc/hosts
3159
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3160
      # FIXME: this should be done via an rpc call to node daemon
3161
      utils.RemoveHostFromEtcHosts(node.name)
3162
      _RedistributeAncillaryFiles(self)
3163

    
3164

    
3165
class LUQueryNodes(NoHooksLU):
3166
  """Logical unit for querying nodes.
3167

3168
  """
3169
  # pylint: disable-msg=W0142
3170
  _OP_PARAMS = [
3171
    _POutputFields,
3172
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3173
    ("use_locking", False, _TBool),
3174
    ]
3175
  REQ_BGL = False
3176

    
3177
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3178
                    "master_candidate", "offline", "drained"]
3179

    
3180
  _FIELDS_DYNAMIC = utils.FieldSet(
3181
    "dtotal", "dfree",
3182
    "mtotal", "mnode", "mfree",
3183
    "bootid",
3184
    "ctotal", "cnodes", "csockets",
3185
    )
3186

    
3187
  _FIELDS_STATIC = utils.FieldSet(*[
3188
    "pinst_cnt", "sinst_cnt",
3189
    "pinst_list", "sinst_list",
3190
    "pip", "sip", "tags",
3191
    "master",
3192
    "role"] + _SIMPLE_FIELDS
3193
    )
3194

    
3195
  def CheckArguments(self):
3196
    _CheckOutputFields(static=self._FIELDS_STATIC,
3197
                       dynamic=self._FIELDS_DYNAMIC,
3198
                       selected=self.op.output_fields)
3199

    
3200
  def ExpandNames(self):
3201
    self.needed_locks = {}
3202
    self.share_locks[locking.LEVEL_NODE] = 1
3203

    
3204
    if self.op.names:
3205
      self.wanted = _GetWantedNodes(self, self.op.names)
3206
    else:
3207
      self.wanted = locking.ALL_SET
3208

    
3209
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3210
    self.do_locking = self.do_node_query and self.op.use_locking
3211
    if self.do_locking:
3212
      # if we don't request only static fields, we need to lock the nodes
3213
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3214

    
3215
  def Exec(self, feedback_fn):
3216
    """Computes the list of nodes and their attributes.
3217

3218
    """
3219
    all_info = self.cfg.GetAllNodesInfo()
3220
    if self.do_locking:
3221
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3222
    elif self.wanted != locking.ALL_SET:
3223
      nodenames = self.wanted
3224
      missing = set(nodenames).difference(all_info.keys())
3225
      if missing:
3226
        raise errors.OpExecError(
3227
          "Some nodes were removed before retrieving their data: %s" % missing)
3228
    else:
3229
      nodenames = all_info.keys()
3230

    
3231
    nodenames = utils.NiceSort(nodenames)
3232
    nodelist = [all_info[name] for name in nodenames]
3233

    
3234
    # begin data gathering
3235

    
3236
    if self.do_node_query:
3237
      live_data = {}
3238
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3239
                                          self.cfg.GetHypervisorType())
3240
      for name in nodenames:
3241
        nodeinfo = node_data[name]
3242
        if not nodeinfo.fail_msg and nodeinfo.payload:
3243
          nodeinfo = nodeinfo.payload
3244
          fn = utils.TryConvert
3245
          live_data[name] = {
3246
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3247
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3248
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3249
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3250
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3251
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3252
            "bootid": nodeinfo.get('bootid', None),
3253
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3254
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3255
            }
3256
        else:
3257
          live_data[name] = {}
3258
    else:
3259
      live_data = dict.fromkeys(nodenames, {})
3260

    
3261
    node_to_primary = dict([(name, set()) for name in nodenames])
3262
    node_to_secondary = dict([(name, set()) for name in nodenames])
3263

    
3264
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3265
                             "sinst_cnt", "sinst_list"))
3266
    if inst_fields & frozenset(self.op.output_fields):
3267
      inst_data = self.cfg.GetAllInstancesInfo()
3268

    
3269
      for inst in inst_data.values():
3270
        if inst.primary_node in node_to_primary:
3271
          node_to_primary[inst.primary_node].add(inst.name)
3272
        for secnode in inst.secondary_nodes:
3273
          if secnode in node_to_secondary:
3274
            node_to_secondary[secnode].add(inst.name)
3275

    
3276
    master_node = self.cfg.GetMasterNode()
3277

    
3278
    # end data gathering
3279

    
3280
    output = []
3281
    for node in nodelist:
3282
      node_output = []
3283
      for field in self.op.output_fields:
3284
        if field in self._SIMPLE_FIELDS:
3285
          val = getattr(node, field)
3286
        elif field == "pinst_list":
3287
          val = list(node_to_primary[node.name])
3288
        elif field == "sinst_list":
3289
          val = list(node_to_secondary[node.name])
3290
        elif field == "pinst_cnt":
3291
          val = len(node_to_primary[node.name])
3292
        elif field == "sinst_cnt":
3293
          val = len(node_to_secondary[node.name])
3294
        elif field == "pip":
3295
          val = node.primary_ip
3296
        elif field == "sip":
3297
          val = node.secondary_ip
3298
        elif field == "tags":
3299
          val = list(node.GetTags())
3300
        elif field == "master":
3301
          val = node.name == master_node
3302
        elif self._FIELDS_DYNAMIC.Matches(field):
3303
          val = live_data[node.name].get(field, None)
3304
        elif field == "role":
3305
          if node.name == master_node:
3306
            val = "M"
3307
          elif node.master_candidate:
3308
            val = "C"
3309
          elif node.drained:
3310
            val = "D"
3311
          elif node.offline:
3312
            val = "O"
3313
          else:
3314
            val = "R"
3315
        else:
3316
          raise errors.ParameterError(field)
3317
        node_output.append(val)
3318
      output.append(node_output)
3319

    
3320
    return output
3321

    
3322

    
3323
class LUQueryNodeVolumes(NoHooksLU):
3324
  """Logical unit for getting volumes on node(s).
3325

3326
  """
3327
  _OP_PARAMS = [
3328
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3329
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3330
    ]
3331
  REQ_BGL = False
3332
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3333
  _FIELDS_STATIC = utils.FieldSet("node")
3334

    
3335
  def CheckArguments(self):
3336
    _CheckOutputFields(static=self._FIELDS_STATIC,
3337
                       dynamic=self._FIELDS_DYNAMIC,
3338
                       selected=self.op.output_fields)
3339

    
3340
  def ExpandNames(self):
3341
    self.needed_locks = {}
3342
    self.share_locks[locking.LEVEL_NODE] = 1
3343
    if not self.op.nodes:
3344
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3345
    else:
3346
      self.needed_locks[locking.LEVEL_NODE] = \
3347
        _GetWantedNodes(self, self.op.nodes)
3348

    
3349
  def Exec(self, feedback_fn):
3350
    """Computes the list of nodes and their attributes.
3351

3352
    """
3353
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3354
    volumes = self.rpc.call_node_volumes(nodenames)
3355

    
3356
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3357
             in self.cfg.GetInstanceList()]
3358

    
3359
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3360

    
3361
    output = []
3362
    for node in nodenames:
3363
      nresult = volumes[node]
3364
      if nresult.offline:
3365
        continue
3366
      msg = nresult.fail_msg
3367
      if msg:
3368
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3369
        continue
3370

    
3371
      node_vols = nresult.payload[:]
3372
      node_vols.sort(key=lambda vol: vol['dev'])
3373

    
3374
      for vol in node_vols:
3375
        node_output = []
3376
        for field in self.op.output_fields:
3377
          if field == "node":
3378
            val = node
3379
          elif field == "phys":
3380
            val = vol['dev']
3381
          elif field == "vg":
3382
            val = vol['vg']
3383
          elif field == "name":
3384
            val = vol['name']
3385
          elif field == "size":
3386
            val = int(float(vol['size']))
3387
          elif field == "instance":
3388
            for inst in ilist:
3389
              if node not in lv_by_node[inst]:
3390
                continue
3391
              if vol['name'] in lv_by_node[inst][node]:
3392
                val = inst.name
3393
                break
3394
            else:
3395
              val = '-'
3396
          else:
3397
            raise errors.ParameterError(field)
3398
          node_output.append(str(val))
3399

    
3400
        output.append(node_output)
3401

    
3402
    return output
3403

    
3404

    
3405
class LUQueryNodeStorage(NoHooksLU):
3406
  """Logical unit for getting information on storage units on node(s).
3407

3408
  """
3409
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3410
  _OP_PARAMS = [
3411
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3412
    ("storage_type", _NoDefault, _CheckStorageType),
3413
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3414
    ("name", None, _TMaybeString),
3415
    ]
3416
  REQ_BGL = False
3417

    
3418
  def CheckArguments(self):
3419
    _CheckOutputFields(static=self._FIELDS_STATIC,
3420
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3421
                       selected=self.op.output_fields)
3422

    
3423
  def ExpandNames(self):
3424
    self.needed_locks = {}
3425
    self.share_locks[locking.LEVEL_NODE] = 1
3426

    
3427
    if self.op.nodes:
3428
      self.needed_locks[locking.LEVEL_NODE] = \
3429
        _GetWantedNodes(self, self.op.nodes)
3430
    else:
3431
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3432

    
3433
  def Exec(self, feedback_fn):
3434
    """Computes the list of nodes and their attributes.
3435

3436
    """
3437
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3438

    
3439
    # Always get name to sort by
3440
    if constants.SF_NAME in self.op.output_fields:
3441
      fields = self.op.output_fields[:]
3442
    else:
3443
      fields = [constants.SF_NAME] + self.op.output_fields
3444

    
3445
    # Never ask for node or type as it's only known to the LU
3446
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3447
      while extra in fields:
3448
        fields.remove(extra)
3449

    
3450
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3451
    name_idx = field_idx[constants.SF_NAME]
3452

    
3453
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3454
    data = self.rpc.call_storage_list(self.nodes,
3455
                                      self.op.storage_type, st_args,
3456
                                      self.op.name, fields)
3457

    
3458
    result = []
3459

    
3460
    for node in utils.NiceSort(self.nodes):
3461
      nresult = data[node]
3462
      if nresult.offline:
3463
        continue
3464

    
3465
      msg = nresult.fail_msg
3466
      if msg:
3467
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3468
        continue
3469

    
3470
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3471

    
3472
      for name in utils.NiceSort(rows.keys()):
3473
        row = rows[name]
3474

    
3475
        out = []
3476

    
3477
        for field in self.op.output_fields:
3478
          if field == constants.SF_NODE:
3479
            val = node
3480
          elif field == constants.SF_TYPE:
3481
            val = self.op.storage_type
3482
          elif field in field_idx:
3483
            val = row[field_idx[field]]
3484
          else:
3485
            raise errors.ParameterError(field)
3486

    
3487
          out.append(val)
3488

    
3489
        result.append(out)
3490

    
3491
    return result
3492

    
3493

    
3494
class LUModifyNodeStorage(NoHooksLU):
3495
  """Logical unit for modifying a storage volume on a node.
3496

3497
  """
3498
  _OP_PARAMS = [
3499
    _PNodeName,
3500
    ("storage_type", _NoDefault, _CheckStorageType),
3501
    ("name", _NoDefault, _TNonEmptyString),
3502
    ("changes", _NoDefault, _TDict),
3503
    ]
3504
  REQ_BGL = False
3505

    
3506
  def CheckArguments(self):
3507
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3508

    
3509
    storage_type = self.op.storage_type
3510

    
3511
    try:
3512
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3513
    except KeyError:
3514
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3515
                                 " modified" % storage_type,
3516
                                 errors.ECODE_INVAL)
3517

    
3518
    diff = set(self.op.changes.keys()) - modifiable
3519
    if diff:
3520
      raise errors.OpPrereqError("The following fields can not be modified for"
3521
                                 " storage units of type '%s': %r" %
3522
                                 (storage_type, list(diff)),
3523
                                 errors.ECODE_INVAL)
3524

    
3525
  def ExpandNames(self):
3526
    self.needed_locks = {
3527
      locking.LEVEL_NODE: self.op.node_name,
3528
      }
3529

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

3533
    """
3534
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3535
    result = self.rpc.call_storage_modify(self.op.node_name,
3536
                                          self.op.storage_type, st_args,
3537
                                          self.op.name, self.op.changes)
3538
    result.Raise("Failed to modify storage unit '%s' on %s" %
3539
                 (self.op.name, self.op.node_name))
3540

    
3541

    
3542
class LUAddNode(LogicalUnit):
3543
  """Logical unit for adding node to the cluster.
3544

3545
  """
3546
  HPATH = "node-add"
3547
  HTYPE = constants.HTYPE_NODE
3548
  _OP_PARAMS = [
3549
    _PNodeName,
3550
    ("primary_ip", None, _NoType),
3551
    ("secondary_ip", None, _TMaybeString),
3552
    ("readd", False, _TBool),
3553
    ]
3554

    
3555
  def CheckArguments(self):
3556
    # validate/normalize the node name
3557
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3558

    
3559
  def BuildHooksEnv(self):
3560
    """Build hooks env.
3561

3562
    This will run on all nodes before, and on all nodes + the new node after.
3563

3564
    """
3565
    env = {
3566
      "OP_TARGET": self.op.node_name,
3567
      "NODE_NAME": self.op.node_name,
3568
      "NODE_PIP": self.op.primary_ip,
3569
      "NODE_SIP": self.op.secondary_ip,
3570
      }
3571
    nodes_0 = self.cfg.GetNodeList()
3572
    nodes_1 = nodes_0 + [self.op.node_name, ]
3573
    return env, nodes_0, nodes_1
3574

    
3575
  def CheckPrereq(self):
3576
    """Check prerequisites.
3577

3578
    This checks:
3579
     - the new node is not already in the config
3580
     - it is resolvable
3581
     - its parameters (single/dual homed) matches the cluster
3582

3583
    Any errors are signaled by raising errors.OpPrereqError.
3584

3585
    """
3586
    node_name = self.op.node_name
3587
    cfg = self.cfg
3588

    
3589
    dns_data = utils.GetHostInfo(node_name)
3590

    
3591
    node = dns_data.name
3592
    primary_ip = self.op.primary_ip = dns_data.ip
3593
    if self.op.secondary_ip is None:
3594
      self.op.secondary_ip = primary_ip
3595
    if not utils.IsValidIP4(self.op.secondary_ip):
3596
      raise errors.OpPrereqError("Invalid secondary IP given",
3597
                                 errors.ECODE_INVAL)
3598
    secondary_ip = self.op.secondary_ip
3599

    
3600
    node_list = cfg.GetNodeList()
3601
    if not self.op.readd and node in node_list:
3602
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3603
                                 node, errors.ECODE_EXISTS)
3604
    elif self.op.readd and node not in node_list:
3605
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3606
                                 errors.ECODE_NOENT)
3607

    
3608
    self.changed_primary_ip = False
3609

    
3610
    for existing_node_name in node_list:
3611
      existing_node = cfg.GetNodeInfo(existing_node_name)
3612

    
3613
      if self.op.readd and node == existing_node_name:
3614
        if existing_node.secondary_ip != secondary_ip:
3615
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3616
                                     " address configuration as before",
3617
                                     errors.ECODE_INVAL)
3618
        if existing_node.primary_ip != primary_ip:
3619
          self.changed_primary_ip = True
3620

    
3621
        continue
3622

    
3623
      if (existing_node.primary_ip == primary_ip or
3624
          existing_node.secondary_ip == primary_ip or
3625
          existing_node.primary_ip == secondary_ip or
3626
          existing_node.secondary_ip == secondary_ip):
3627
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3628
                                   " existing node %s" % existing_node.name,
3629
                                   errors.ECODE_NOTUNIQUE)
3630

    
3631
    # check that the type of the node (single versus dual homed) is the
3632
    # same as for the master
3633
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3634
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3635
    newbie_singlehomed = secondary_ip == primary_ip
3636
    if master_singlehomed != newbie_singlehomed:
3637
      if master_singlehomed:
3638
        raise errors.OpPrereqError("The master has no private ip but the"
3639
                                   " new node has one",
3640
                                   errors.ECODE_INVAL)
3641
      else:
3642
        raise errors.OpPrereqError("The master has a private ip but the"
3643
                                   " new node doesn't have one",
3644
                                   errors.ECODE_INVAL)
3645

    
3646
    # checks reachability
3647
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3648
      raise errors.OpPrereqError("Node not reachable by ping",
3649
                                 errors.ECODE_ENVIRON)
3650

    
3651
    if not newbie_singlehomed:
3652
      # check reachability from my secondary ip to newbie's secondary ip
3653
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3654
                           source=myself.secondary_ip):
3655
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3656
                                   " based ping to noded port",
3657
                                   errors.ECODE_ENVIRON)
3658

    
3659
    if self.op.readd:
3660
      exceptions = [node]
3661
    else:
3662
      exceptions = []
3663

    
3664
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3665

    
3666
    if self.op.readd:
3667
      self.new_node = self.cfg.GetNodeInfo(node)
3668
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3669
    else:
3670
      self.new_node = objects.Node(name=node,
3671
                                   primary_ip=primary_ip,
3672
                                   secondary_ip=secondary_ip,
3673
                                   master_candidate=self.master_candidate,
3674
                                   offline=False, drained=False)
3675

    
3676
  def Exec(self, feedback_fn):
3677
    """Adds the new node to the cluster.
3678

3679
    """
3680
    new_node = self.new_node
3681
    node = new_node.name
3682

    
3683
    # for re-adds, reset the offline/drained/master-candidate flags;
3684
    # we need to reset here, otherwise offline would prevent RPC calls
3685
    # later in the procedure; this also means that if the re-add
3686
    # fails, we are left with a non-offlined, broken node
3687
    if self.op.readd:
3688
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3689
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3690
      # if we demote the node, we do cleanup later in the procedure
3691
      new_node.master_candidate = self.master_candidate
3692
      if self.changed_primary_ip:
3693
        new_node.primary_ip = self.op.primary_ip
3694

    
3695
    # notify the user about any possible mc promotion
3696
    if new_node.master_candidate:
3697
      self.LogInfo("Node will be a master candidate")
3698

    
3699
    # check connectivity
3700
    result = self.rpc.call_version([node])[node]
3701
    result.Raise("Can't get version information from node %s" % node)
3702
    if constants.PROTOCOL_VERSION == result.payload:
3703
      logging.info("Communication to node %s fine, sw version %s match",
3704
                   node, result.payload)
3705
    else:
3706
      raise errors.OpExecError("Version mismatch master version %s,"
3707
                               " node version %s" %
3708
                               (constants.PROTOCOL_VERSION, result.payload))
3709

    
3710
    # setup ssh on node
3711
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3712
      logging.info("Copy ssh key to node %s", node)
3713
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3714
      keyarray = []
3715
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3716
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3717
                  priv_key, pub_key]
3718

    
3719
      for i in keyfiles:
3720
        keyarray.append(utils.ReadFile(i))
3721

    
3722
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3723
                                      keyarray[2], keyarray[3], keyarray[4],
3724
                                      keyarray[5])
3725
      result.Raise("Cannot transfer ssh keys to the new node")
3726

    
3727
    # Add node to our /etc/hosts, and add key to known_hosts
3728
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3729
      # FIXME: this should be done via an rpc call to node daemon
3730
      utils.AddHostToEtcHosts(new_node.name)
3731

    
3732
    if new_node.secondary_ip != new_node.primary_ip:
3733
      result = self.rpc.call_node_has_ip_address(new_node.name,
3734
                                                 new_node.secondary_ip)
3735
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3736
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3737
      if not result.payload:
3738
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3739
                                 " you gave (%s). Please fix and re-run this"
3740
                                 " command." % new_node.secondary_ip)
3741

    
3742
    node_verify_list = [self.cfg.GetMasterNode()]
3743
    node_verify_param = {
3744
      constants.NV_NODELIST: [node],
3745
      # TODO: do a node-net-test as well?
3746
    }
3747

    
3748
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3749
                                       self.cfg.GetClusterName())
3750
    for verifier in node_verify_list:
3751
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3752
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3753
      if nl_payload:
3754
        for failed in nl_payload:
3755
          feedback_fn("ssh/hostname verification failed"
3756
                      " (checking from %s): %s" %
3757
                      (verifier, nl_payload[failed]))
3758
        raise errors.OpExecError("ssh/hostname verification failed.")
3759

    
3760
    if self.op.readd:
3761
      _RedistributeAncillaryFiles(self)
3762
      self.context.ReaddNode(new_node)
3763
      # make sure we redistribute the config
3764
      self.cfg.Update(new_node, feedback_fn)
3765
      # and make sure the new node will not have old files around
3766
      if not new_node.master_candidate:
3767
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3768
        msg = result.fail_msg
3769
        if msg:
3770
          self.LogWarning("Node failed to demote itself from master"
3771
                          " candidate status: %s" % msg)
3772
    else:
3773
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3774
      self.context.AddNode(new_node, self.proc.GetECId())
3775

    
3776

    
3777
class LUSetNodeParams(LogicalUnit):
3778
  """Modifies the parameters of a node.
3779

3780
  """
3781
  HPATH = "node-modify"
3782
  HTYPE = constants.HTYPE_NODE
3783
  _OP_PARAMS = [
3784
    _PNodeName,
3785
    ("master_candidate", None, _TMaybeBool),
3786
    ("offline", None, _TMaybeBool),
3787
    ("drained", None, _TMaybeBool),
3788
    ("auto_promote", False, _TBool),
3789
    _PForce,
3790
    ]
3791
  REQ_BGL = False
3792

    
3793
  def CheckArguments(self):
3794
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3795
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3796
    if all_mods.count(None) == 3:
3797
      raise errors.OpPrereqError("Please pass at least one modification",
3798
                                 errors.ECODE_INVAL)
3799
    if all_mods.count(True) > 1:
3800
      raise errors.OpPrereqError("Can't set the node into more than one"
3801
                                 " state at the same time",
3802
                                 errors.ECODE_INVAL)
3803

    
3804
    # Boolean value that tells us whether we're offlining or draining the node
3805
    self.offline_or_drain = (self.op.offline == True or
3806
                             self.op.drained == True)
3807
    self.deoffline_or_drain = (self.op.offline == False or
3808
                               self.op.drained == False)
3809
    self.might_demote = (self.op.master_candidate == False or
3810
                         self.offline_or_drain)
3811

    
3812
    self.lock_all = self.op.auto_promote and self.might_demote
3813

    
3814

    
3815
  def ExpandNames(self):
3816
    if self.lock_all:
3817
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3818
    else:
3819
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3820

    
3821
  def BuildHooksEnv(self):
3822
    """Build hooks env.
3823

3824
    This runs on the master node.
3825

3826
    """
3827
    env = {
3828
      "OP_TARGET": self.op.node_name,
3829
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3830
      "OFFLINE": str(self.op.offline),
3831
      "DRAINED": str(self.op.drained),
3832
      }
3833
    nl = [self.cfg.GetMasterNode(),
3834
          self.op.node_name]
3835
    return env, nl, nl
3836

    
3837
  def CheckPrereq(self):
3838
    """Check prerequisites.
3839

3840
    This only checks the instance list against the existing names.
3841

3842
    """
3843
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3844

    
3845
    if (self.op.master_candidate is not None or
3846
        self.op.drained is not None or
3847
        self.op.offline is not None):
3848
      # we can't change the master's node flags
3849
      if self.op.node_name == self.cfg.GetMasterNode():
3850
        raise errors.OpPrereqError("The master role can be changed"
3851
                                   " only via masterfailover",
3852
                                   errors.ECODE_INVAL)
3853

    
3854

    
3855
    if node.master_candidate and self.might_demote and not self.lock_all:
3856
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3857
      # check if after removing the current node, we're missing master
3858
      # candidates
3859
      (mc_remaining, mc_should, _) = \
3860
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3861
      if mc_remaining < mc_should:
3862
        raise errors.OpPrereqError("Not enough master candidates, please"
3863
                                   " pass auto_promote to allow promotion",
3864
                                   errors.ECODE_INVAL)
3865

    
3866
    if (self.op.master_candidate == True and
3867
        ((node.offline and not self.op.offline == False) or
3868
         (node.drained and not self.op.drained == False))):
3869
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3870
                                 " to master_candidate" % node.name,
3871
                                 errors.ECODE_INVAL)
3872

    
3873
    # If we're being deofflined/drained, we'll MC ourself if needed
3874
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3875
        self.op.master_candidate == True and not node.master_candidate):
3876
      self.op.master_candidate = _DecideSelfPromotion(self)
3877
      if self.op.master_candidate:
3878
        self.LogInfo("Autopromoting node to master candidate")
3879

    
3880
    return
3881

    
3882
  def Exec(self, feedback_fn):
3883
    """Modifies a node.
3884

3885
    """
3886
    node = self.node
3887

    
3888
    result = []
3889
    changed_mc = False
3890

    
3891
    if self.op.offline is not None:
3892
      node.offline = self.op.offline
3893
      result.append(("offline", str(self.op.offline)))
3894
      if self.op.offline == True:
3895
        if node.master_candidate:
3896
          node.master_candidate = False
3897
          changed_mc = True
3898
          result.append(("master_candidate", "auto-demotion due to offline"))
3899
        if node.drained:
3900
          node.drained = False
3901
          result.append(("drained", "clear drained status due to offline"))
3902

    
3903
    if self.op.master_candidate is not None:
3904
      node.master_candidate = self.op.master_candidate
3905
      changed_mc = True
3906
      result.append(("master_candidate", str(self.op.master_candidate)))
3907
      if self.op.master_candidate == False:
3908
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3909
        msg = rrc.fail_msg
3910
        if msg:
3911
          self.LogWarning("Node failed to demote itself: %s" % msg)
3912

    
3913
    if self.op.drained is not None:
3914
      node.drained = self.op.drained
3915
      result.append(("drained", str(self.op.drained)))
3916
      if self.op.drained == True:
3917
        if node.master_candidate:
3918
          node.master_candidate = False
3919
          changed_mc = True
3920
          result.append(("master_candidate", "auto-demotion due to drain"))
3921
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3922
          msg = rrc.fail_msg
3923
          if msg:
3924
            self.LogWarning("Node failed to demote itself: %s" % msg)
3925
        if node.offline:
3926
          node.offline = False
3927
          result.append(("offline", "clear offline status due to drain"))
3928

    
3929
    # we locked all nodes, we adjust the CP before updating this node
3930
    if self.lock_all:
3931
      _AdjustCandidatePool(self, [node.name])
3932

    
3933
    # this will trigger configuration file update, if needed
3934
    self.cfg.Update(node, feedback_fn)
3935

    
3936
    # this will trigger job queue propagation or cleanup
3937
    if changed_mc:
3938
      self.context.ReaddNode(node)
3939

    
3940
    return result
3941

    
3942

    
3943
class LUPowercycleNode(NoHooksLU):
3944
  """Powercycles a node.
3945

3946
  """
3947
  _OP_PARAMS = [
3948
    _PNodeName,
3949
    _PForce,
3950
    ]
3951
  REQ_BGL = False
3952

    
3953
  def CheckArguments(self):
3954
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3955
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3956
      raise errors.OpPrereqError("The node is the master and the force"
3957
                                 " parameter was not set",
3958
                                 errors.ECODE_INVAL)
3959

    
3960
  def ExpandNames(self):
3961
    """Locking for PowercycleNode.
3962

3963
    This is a last-resort option and shouldn't block on other
3964
    jobs. Therefore, we grab no locks.
3965

3966
    """
3967
    self.needed_locks = {}
3968

    
3969
  def Exec(self, feedback_fn):
3970
    """Reboots a node.
3971

3972
    """
3973
    result = self.rpc.call_node_powercycle(self.op.node_name,
3974
                                           self.cfg.GetHypervisorType())
3975
    result.Raise("Failed to schedule the reboot")
3976
    return result.payload
3977

    
3978

    
3979
class LUQueryClusterInfo(NoHooksLU):
3980
  """Query cluster configuration.
3981

3982
  """
3983
  REQ_BGL = False
3984

    
3985
  def ExpandNames(self):
3986
    self.needed_locks = {}
3987

    
3988
  def Exec(self, feedback_fn):
3989
    """Return cluster config.
3990

3991
    """
3992
    cluster = self.cfg.GetClusterInfo()
3993
    os_hvp = {}
3994

    
3995
    # Filter just for enabled hypervisors
3996
    for os_name, hv_dict in cluster.os_hvp.items():
3997
      os_hvp[os_name] = {}
3998
      for hv_name, hv_params in hv_dict.items():
3999
        if hv_name in cluster.enabled_hypervisors:
4000
          os_hvp[os_name][hv_name] = hv_params
4001

    
4002
    result = {
4003
      "software_version": constants.RELEASE_VERSION,
4004
      "protocol_version": constants.PROTOCOL_VERSION,
4005
      "config_version": constants.CONFIG_VERSION,
4006
      "os_api_version": max(constants.OS_API_VERSIONS),
4007
      "export_version": constants.EXPORT_VERSION,
4008
      "architecture": (platform.architecture()[0], platform.machine()),
4009
      "name": cluster.cluster_name,
4010
      "master": cluster.master_node,
4011
      "default_hypervisor": cluster.enabled_hypervisors[0],
4012
      "enabled_hypervisors": cluster.enabled_hypervisors,
4013
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4014
                        for hypervisor_name in cluster.enabled_hypervisors]),
4015
      "os_hvp": os_hvp,
4016
      "beparams": cluster.beparams,
4017
      "osparams": cluster.osparams,
4018
      "nicparams": cluster.nicparams,
4019
      "candidate_pool_size": cluster.candidate_pool_size,
4020
      "master_netdev": cluster.master_netdev,
4021
      "volume_group_name": cluster.volume_group_name,
4022
      "file_storage_dir": cluster.file_storage_dir,
4023
      "maintain_node_health": cluster.maintain_node_health,
4024
      "ctime": cluster.ctime,
4025
      "mtime": cluster.mtime,
4026
      "uuid": cluster.uuid,
4027
      "tags": list(cluster.GetTags()),
4028
      "uid_pool": cluster.uid_pool,
4029
      }
4030

    
4031
    return result
4032

    
4033

    
4034
class LUQueryConfigValues(NoHooksLU):
4035
  """Return configuration values.
4036

4037
  """
4038
  _OP_PARAMS = [_POutputFields]
4039
  REQ_BGL = False
4040
  _FIELDS_DYNAMIC = utils.FieldSet()
4041
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4042
                                  "watcher_pause")
4043

    
4044
  def CheckArguments(self):
4045
    _CheckOutputFields(static=self._FIELDS_STATIC,
4046
                       dynamic=self._FIELDS_DYNAMIC,
4047
                       selected=self.op.output_fields)
4048

    
4049
  def ExpandNames(self):
4050
    self.needed_locks = {}
4051

    
4052
  def Exec(self, feedback_fn):
4053
    """Dump a representation of the cluster config to the standard output.
4054

4055
    """
4056
    values = []
4057
    for field in self.op.output_fields:
4058
      if field == "cluster_name":
4059
        entry = self.cfg.GetClusterName()
4060
      elif field == "master_node":
4061
        entry = self.cfg.GetMasterNode()
4062
      elif field == "drain_flag":
4063
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4064
      elif field == "watcher_pause":
4065
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4066
      else:
4067
        raise errors.ParameterError(field)
4068
      values.append(entry)
4069
    return values
4070

    
4071

    
4072
class LUActivateInstanceDisks(NoHooksLU):
4073
  """Bring up an instance's disks.
4074

4075
  """
4076
  _OP_PARAMS = [
4077
    _PInstanceName,
4078
    ("ignore_size", False, _TBool),
4079
    ]
4080
  REQ_BGL = False
4081

    
4082
  def ExpandNames(self):
4083
    self._ExpandAndLockInstance()
4084
    self.needed_locks[locking.LEVEL_NODE] = []
4085
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4086

    
4087
  def DeclareLocks(self, level):
4088
    if level == locking.LEVEL_NODE:
4089
      self._LockInstancesNodes()
4090

    
4091
  def CheckPrereq(self):
4092
    """Check prerequisites.
4093

4094
    This checks that the instance is in the cluster.
4095

4096
    """
4097
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4098
    assert self.instance is not None, \
4099
      "Cannot retrieve locked instance %s" % self.op.instance_name
4100
    _CheckNodeOnline(self, self.instance.primary_node)
4101

    
4102
  def Exec(self, feedback_fn):
4103
    """Activate the disks.
4104

4105
    """
4106
    disks_ok, disks_info = \
4107
              _AssembleInstanceDisks(self, self.instance,
4108
                                     ignore_size=self.op.ignore_size)
4109
    if not disks_ok:
4110
      raise errors.OpExecError("Cannot activate block devices")
4111

    
4112
    return disks_info
4113

    
4114

    
4115
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4116
                           ignore_size=False):
4117
  """Prepare the block devices for an instance.
4118

4119
  This sets up the block devices on all nodes.
4120

4121
  @type lu: L{LogicalUnit}
4122
  @param lu: the logical unit on whose behalf we execute
4123
  @type instance: L{objects.Instance}
4124
  @param instance: the instance for whose disks we assemble
4125
  @type disks: list of L{objects.Disk} or None
4126
  @param disks: which disks to assemble (or all, if None)
4127
  @type ignore_secondaries: boolean
4128
  @param ignore_secondaries: if true, errors on secondary nodes
4129
      won't result in an error return from the function
4130
  @type ignore_size: boolean
4131
  @param ignore_size: if true, the current known size of the disk
4132
      will not be used during the disk activation, useful for cases
4133
      when the size is wrong
4134
  @return: False if the operation failed, otherwise a list of
4135
      (host, instance_visible_name, node_visible_name)
4136
      with the mapping from node devices to instance devices
4137

4138
  """
4139
  device_info = []
4140
  disks_ok = True
4141
  iname = instance.name
4142
  disks = _ExpandCheckDisks(instance, disks)
4143

    
4144
  # With the two passes mechanism we try to reduce the window of
4145
  # opportunity for the race condition of switching DRBD to primary
4146
  # before handshaking occured, but we do not eliminate it
4147

    
4148
  # The proper fix would be to wait (with some limits) until the
4149
  # connection has been made and drbd transitions from WFConnection
4150
  # into any other network-connected state (Connected, SyncTarget,
4151
  # SyncSource, etc.)
4152

    
4153
  # 1st pass, assemble on all nodes in secondary mode
4154
  for inst_disk in disks:
4155
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4156
      if ignore_size:
4157
        node_disk = node_disk.Copy()
4158
        node_disk.UnsetSize()
4159
      lu.cfg.SetDiskID(node_disk, node)
4160
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4161
      msg = result.fail_msg
4162
      if msg:
4163
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4164
                           " (is_primary=False, pass=1): %s",
4165
                           inst_disk.iv_name, node, msg)
4166
        if not ignore_secondaries:
4167
          disks_ok = False
4168

    
4169
  # FIXME: race condition on drbd migration to primary
4170

    
4171
  # 2nd pass, do only the primary node
4172
  for inst_disk in disks:
4173
    dev_path = None
4174

    
4175
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4176
      if node != instance.primary_node:
4177
        continue
4178
      if ignore_size:
4179
        node_disk = node_disk.Copy()
4180
        node_disk.UnsetSize()
4181
      lu.cfg.SetDiskID(node_disk, node)
4182
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4183
      msg = result.fail_msg
4184
      if msg:
4185
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4186
                           " (is_primary=True, pass=2): %s",
4187
                           inst_disk.iv_name, node, msg)
4188
        disks_ok = False
4189
      else:
4190
        dev_path = result.payload
4191

    
4192
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4193

    
4194
  # leave the disks configured for the primary node
4195
  # this is a workaround that would be fixed better by
4196
  # improving the logical/physical id handling
4197
  for disk in disks:
4198
    lu.cfg.SetDiskID(disk, instance.primary_node)
4199

    
4200
  return disks_ok, device_info
4201

    
4202

    
4203
def _StartInstanceDisks(lu, instance, force):
4204
  """Start the disks of an instance.
4205

4206
  """
4207
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4208
                                           ignore_secondaries=force)
4209
  if not disks_ok:
4210
    _ShutdownInstanceDisks(lu, instance)
4211
    if force is not None and not force:
4212
      lu.proc.LogWarning("", hint="If the message above refers to a"
4213
                         " secondary node,"
4214
                         " you can retry the operation using '--force'.")
4215
    raise errors.OpExecError("Disk consistency error")
4216

    
4217

    
4218
class LUDeactivateInstanceDisks(NoHooksLU):
4219
  """Shutdown an instance's disks.
4220

4221
  """
4222
  _OP_PARAMS = [
4223
    _PInstanceName,
4224
    ]
4225
  REQ_BGL = False
4226

    
4227
  def ExpandNames(self):
4228
    self._ExpandAndLockInstance()
4229
    self.needed_locks[locking.LEVEL_NODE] = []
4230
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4231

    
4232
  def DeclareLocks(self, level):
4233
    if level == locking.LEVEL_NODE:
4234
      self._LockInstancesNodes()
4235

    
4236
  def CheckPrereq(self):
4237
    """Check prerequisites.
4238

4239
    This checks that the instance is in the cluster.
4240

4241
    """
4242
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4243
    assert self.instance is not None, \
4244
      "Cannot retrieve locked instance %s" % self.op.instance_name
4245

    
4246
  def Exec(self, feedback_fn):
4247
    """Deactivate the disks
4248

4249
    """
4250
    instance = self.instance
4251
    _SafeShutdownInstanceDisks(self, instance)
4252

    
4253

    
4254
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4255
  """Shutdown block devices of an instance.
4256

4257
  This function checks if an instance is running, before calling
4258
  _ShutdownInstanceDisks.
4259

4260
  """
4261
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4262
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4263

    
4264

    
4265
def _ExpandCheckDisks(instance, disks):
4266
  """Return the instance disks selected by the disks list
4267

4268
  @type disks: list of L{objects.Disk} or None
4269
  @param disks: selected disks
4270
  @rtype: list of L{objects.Disk}
4271
  @return: selected instance disks to act on
4272

4273
  """
4274
  if disks is None:
4275
    return instance.disks
4276
  else:
4277
    if not set(disks).issubset(instance.disks):
4278
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4279
                                   " target instance")
4280
    return disks
4281

    
4282

    
4283
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4284
  """Shutdown block devices of an instance.
4285

4286
  This does the shutdown on all nodes of the instance.
4287

4288
  If the ignore_primary is false, errors on the primary node are
4289
  ignored.
4290

4291
  """
4292
  all_result = True
4293
  disks = _ExpandCheckDisks(instance, disks)
4294

    
4295
  for disk in disks:
4296
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4297
      lu.cfg.SetDiskID(top_disk, node)
4298
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4299
      msg = result.fail_msg
4300
      if msg:
4301
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4302
                      disk.iv_name, node, msg)
4303
        if not ignore_primary or node != instance.primary_node:
4304
          all_result = False
4305
  return all_result
4306

    
4307

    
4308
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4309
  """Checks if a node has enough free memory.
4310

4311
  This function check if a given node has the needed amount of free
4312
  memory. In case the node has less memory or we cannot get the
4313
  information from the node, this function raise an OpPrereqError
4314
  exception.
4315

4316
  @type lu: C{LogicalUnit}
4317
  @param lu: a logical unit from which we get configuration data
4318
  @type node: C{str}
4319
  @param node: the node to check
4320
  @type reason: C{str}
4321
  @param reason: string to use in the error message
4322
  @type requested: C{int}
4323
  @param requested: the amount of memory in MiB to check for
4324
  @type hypervisor_name: C{str}
4325
  @param hypervisor_name: the hypervisor to ask for memory stats
4326
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4327
      we cannot check the node
4328

4329
  """
4330
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4331
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4332
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4333
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4334
  if not isinstance(free_mem, int):
4335
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4336
                               " was '%s'" % (node, free_mem),
4337
                               errors.ECODE_ENVIRON)
4338
  if requested > free_mem:
4339
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4340
                               " needed %s MiB, available %s MiB" %
4341
                               (node, reason, requested, free_mem),
4342
                               errors.ECODE_NORES)
4343

    
4344

    
4345
def _CheckNodesFreeDisk(lu, nodenames, requested):
4346
  """Checks if nodes have enough free disk space in the default VG.
4347

4348
  This function check if all given nodes have the needed amount of
4349
  free disk. In case any node has less disk or we cannot get the
4350
  information from the node, this function raise an OpPrereqError
4351
  exception.
4352

4353
  @type lu: C{LogicalUnit}
4354
  @param lu: a logical unit from which we get configuration data
4355
  @type nodenames: C{list}
4356
  @param nodenames: the list of node names to check
4357
  @type requested: C{int}
4358
  @param requested: the amount of disk in MiB to check for
4359
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4360
      we cannot check the node
4361

4362
  """
4363
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4364
                                   lu.cfg.GetHypervisorType())
4365
  for node in nodenames:
4366
    info = nodeinfo[node]
4367
    info.Raise("Cannot get current information from node %s" % node,
4368
               prereq=True, ecode=errors.ECODE_ENVIRON)
4369
    vg_free = info.payload.get("vg_free", None)
4370
    if not isinstance(vg_free, int):
4371
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4372
                                 " result was '%s'" % (node, vg_free),
4373
                                 errors.ECODE_ENVIRON)
4374
    if requested > vg_free:
4375
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4376
                                 " required %d MiB, available %d MiB" %
4377
                                 (node, requested, vg_free),
4378
                                 errors.ECODE_NORES)
4379

    
4380

    
4381
class LUStartupInstance(LogicalUnit):
4382
  """Starts an instance.
4383

4384
  """
4385
  HPATH = "instance-start"
4386
  HTYPE = constants.HTYPE_INSTANCE
4387
  _OP_PARAMS = [
4388
    _PInstanceName,
4389
    _PForce,
4390
    ("hvparams", _EmptyDict, _TDict),
4391
    ("beparams", _EmptyDict, _TDict),
4392
    ]
4393
  REQ_BGL = False
4394

    
4395
  def CheckArguments(self):
4396
    # extra beparams
4397
    if self.op.beparams:
4398
      # fill the beparams dict
4399
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4400

    
4401
  def ExpandNames(self):
4402
    self._ExpandAndLockInstance()
4403

    
4404
  def BuildHooksEnv(self):
4405
    """Build hooks env.
4406

4407
    This runs on master, primary and secondary nodes of the instance.
4408

4409
    """
4410
    env = {
4411
      "FORCE": self.op.force,
4412
      }
4413
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4414
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4415
    return env, nl, nl
4416

    
4417
  def CheckPrereq(self):
4418
    """Check prerequisites.
4419

4420
    This checks that the instance is in the cluster.
4421

4422
    """
4423
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4424
    assert self.instance is not None, \
4425
      "Cannot retrieve locked instance %s" % self.op.instance_name
4426

    
4427
    # extra hvparams
4428
    if self.op.hvparams:
4429
      # check hypervisor parameter syntax (locally)
4430
      cluster = self.cfg.GetClusterInfo()
4431
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4432
      filled_hvp = cluster.FillHV(instance)
4433
      filled_hvp.update(self.op.hvparams)
4434
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4435
      hv_type.CheckParameterSyntax(filled_hvp)
4436
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4437

    
4438
    _CheckNodeOnline(self, instance.primary_node)
4439

    
4440
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4441
    # check bridges existence
4442
    _CheckInstanceBridgesExist(self, instance)
4443

    
4444
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4445
                                              instance.name,
4446
                                              instance.hypervisor)
4447
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4448
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4449
    if not remote_info.payload: # not running already
4450
      _CheckNodeFreeMemory(self, instance.primary_node,
4451
                           "starting instance %s" % instance.name,
4452
                           bep[constants.BE_MEMORY], instance.hypervisor)
4453

    
4454
  def Exec(self, feedback_fn):
4455
    """Start the instance.
4456

4457
    """
4458
    instance = self.instance
4459
    force = self.op.force
4460

    
4461
    self.cfg.MarkInstanceUp(instance.name)
4462

    
4463
    node_current = instance.primary_node
4464

    
4465
    _StartInstanceDisks(self, instance, force)
4466

    
4467
    result = self.rpc.call_instance_start(node_current, instance,
4468
                                          self.op.hvparams, self.op.beparams)
4469
    msg = result.fail_msg
4470
    if msg:
4471
      _ShutdownInstanceDisks(self, instance)
4472
      raise errors.OpExecError("Could not start instance: %s" % msg)
4473

    
4474

    
4475
class LURebootInstance(LogicalUnit):
4476
  """Reboot an instance.
4477

4478
  """
4479
  HPATH = "instance-reboot"
4480
  HTYPE = constants.HTYPE_INSTANCE
4481
  _OP_PARAMS = [
4482
    _PInstanceName,
4483
    ("ignore_secondaries", False, _TBool),
4484
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4485
    _PShutdownTimeout,
4486
    ]
4487
  REQ_BGL = False
4488

    
4489
  def ExpandNames(self):
4490
    self._ExpandAndLockInstance()
4491

    
4492
  def BuildHooksEnv(self):
4493
    """Build hooks env.
4494

4495
    This runs on master, primary and secondary nodes of the instance.
4496

4497
    """
4498
    env = {
4499
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4500
      "REBOOT_TYPE": self.op.reboot_type,
4501
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4502
      }
4503
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4504
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4505
    return env, nl, nl
4506

    
4507
  def CheckPrereq(self):
4508
    """Check prerequisites.
4509

4510
    This checks that the instance is in the cluster.
4511

4512
    """
4513
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4514
    assert self.instance is not None, \
4515
      "Cannot retrieve locked instance %s" % self.op.instance_name
4516

    
4517
    _CheckNodeOnline(self, instance.primary_node)
4518

    
4519
    # check bridges existence
4520
    _CheckInstanceBridgesExist(self, instance)
4521

    
4522
  def Exec(self, feedback_fn):
4523
    """Reboot the instance.
4524

4525
    """
4526
    instance = self.instance
4527
    ignore_secondaries = self.op.ignore_secondaries
4528
    reboot_type = self.op.reboot_type
4529

    
4530
    node_current = instance.primary_node
4531

    
4532
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4533
                       constants.INSTANCE_REBOOT_HARD]:
4534
      for disk in instance.disks:
4535
        self.cfg.SetDiskID(disk, node_current)
4536
      result = self.rpc.call_instance_reboot(node_current, instance,
4537
                                             reboot_type,
4538
                                             self.op.shutdown_timeout)
4539
      result.Raise("Could not reboot instance")
4540
    else:
4541
      result = self.rpc.call_instance_shutdown(node_current, instance,
4542
                                               self.op.shutdown_timeout)
4543
      result.Raise("Could not shutdown instance for full reboot")
4544
      _ShutdownInstanceDisks(self, instance)
4545
      _StartInstanceDisks(self, instance, ignore_secondaries)
4546
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4547
      msg = result.fail_msg
4548
      if msg:
4549
        _ShutdownInstanceDisks(self, instance)
4550
        raise errors.OpExecError("Could not start instance for"
4551
                                 " full reboot: %s" % msg)
4552

    
4553
    self.cfg.MarkInstanceUp(instance.name)
4554

    
4555

    
4556
class LUShutdownInstance(LogicalUnit):
4557
  """Shutdown an instance.
4558

4559
  """
4560
  HPATH = "instance-stop"
4561
  HTYPE = constants.HTYPE_INSTANCE
4562
  _OP_PARAMS = [
4563
    _PInstanceName,
4564
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4565
    ]
4566
  REQ_BGL = False
4567

    
4568
  def ExpandNames(self):
4569
    self._ExpandAndLockInstance()
4570

    
4571
  def BuildHooksEnv(self):
4572
    """Build hooks env.
4573

4574
    This runs on master, primary and secondary nodes of the instance.
4575

4576
    """
4577
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4578
    env["TIMEOUT"] = self.op.timeout
4579
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4580
    return env, nl, nl
4581

    
4582
  def CheckPrereq(self):
4583
    """Check prerequisites.
4584

4585
    This checks that the instance is in the cluster.
4586

4587
    """
4588
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4589
    assert self.instance is not None, \
4590
      "Cannot retrieve locked instance %s" % self.op.instance_name
4591
    _CheckNodeOnline(self, self.instance.primary_node)
4592

    
4593
  def Exec(self, feedback_fn):
4594
    """Shutdown the instance.
4595

4596
    """
4597
    instance = self.instance
4598
    node_current = instance.primary_node
4599
    timeout = self.op.timeout
4600
    self.cfg.MarkInstanceDown(instance.name)
4601
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4602
    msg = result.fail_msg
4603
    if msg:
4604
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4605

    
4606
    _ShutdownInstanceDisks(self, instance)
4607

    
4608

    
4609
class LUReinstallInstance(LogicalUnit):
4610
  """Reinstall an instance.
4611

4612
  """
4613
  HPATH = "instance-reinstall"
4614
  HTYPE = constants.HTYPE_INSTANCE
4615
  _OP_PARAMS = [
4616
    _PInstanceName,
4617
    ("os_type", None, _TMaybeString),
4618
    ("force_variant", False, _TBool),
4619
    ]
4620
  REQ_BGL = False
4621

    
4622
  def ExpandNames(self):
4623
    self._ExpandAndLockInstance()
4624

    
4625
  def BuildHooksEnv(self):
4626
    """Build hooks env.
4627

4628
    This runs on master, primary and secondary nodes of the instance.
4629

4630
    """
4631
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4632
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4633
    return env, nl, nl
4634

    
4635
  def CheckPrereq(self):
4636
    """Check prerequisites.
4637

4638
    This checks that the instance is in the cluster and is not running.
4639

4640
    """
4641
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4642
    assert instance is not None, \
4643
      "Cannot retrieve locked instance %s" % self.op.instance_name
4644
    _CheckNodeOnline(self, instance.primary_node)
4645

    
4646
    if instance.disk_template == constants.DT_DISKLESS:
4647
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4648
                                 self.op.instance_name,
4649
                                 errors.ECODE_INVAL)
4650
    _CheckInstanceDown(self, instance, "cannot reinstall")
4651

    
4652
    if self.op.os_type is not None:
4653
      # OS verification
4654
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4655
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4656

    
4657
    self.instance = instance
4658

    
4659
  def Exec(self, feedback_fn):
4660
    """Reinstall the instance.
4661

4662
    """
4663
    inst = self.instance
4664

    
4665
    if self.op.os_type is not None:
4666
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4667
      inst.os = self.op.os_type
4668
      self.cfg.Update(inst, feedback_fn)
4669

    
4670
    _StartInstanceDisks(self, inst, None)
4671
    try:
4672
      feedback_fn("Running the instance OS create scripts...")
4673
      # FIXME: pass debug option from opcode to backend
4674
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4675
                                             self.op.debug_level)
4676
      result.Raise("Could not install OS for instance %s on node %s" %
4677
                   (inst.name, inst.primary_node))
4678
    finally:
4679
      _ShutdownInstanceDisks(self, inst)
4680

    
4681

    
4682
class LURecreateInstanceDisks(LogicalUnit):
4683
  """Recreate an instance's missing disks.
4684

4685
  """
4686
  HPATH = "instance-recreate-disks"
4687
  HTYPE = constants.HTYPE_INSTANCE
4688
  _OP_PARAMS = [
4689
    _PInstanceName,
4690
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4691
    ]
4692
  REQ_BGL = False
4693

    
4694
  def ExpandNames(self):
4695
    self._ExpandAndLockInstance()
4696

    
4697
  def BuildHooksEnv(self):
4698
    """Build hooks env.
4699

4700
    This runs on master, primary and secondary nodes of the instance.
4701

4702
    """
4703
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4704
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4705
    return env, nl, nl
4706

    
4707
  def CheckPrereq(self):
4708
    """Check prerequisites.
4709

4710
    This checks that the instance is in the cluster and is not running.
4711

4712
    """
4713
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4714
    assert instance is not None, \
4715
      "Cannot retrieve locked instance %s" % self.op.instance_name
4716
    _CheckNodeOnline(self, instance.primary_node)
4717

    
4718
    if instance.disk_template == constants.DT_DISKLESS:
4719
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4720
                                 self.op.instance_name, errors.ECODE_INVAL)
4721
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4722

    
4723
    if not self.op.disks:
4724
      self.op.disks = range(len(instance.disks))
4725
    else:
4726
      for idx in self.op.disks:
4727
        if idx >= len(instance.disks):
4728
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4729
                                     errors.ECODE_INVAL)
4730

    
4731
    self.instance = instance
4732

    
4733
  def Exec(self, feedback_fn):
4734
    """Recreate the disks.
4735

4736
    """
4737
    to_skip = []
4738
    for idx, _ in enumerate(self.instance.disks):
4739
      if idx not in self.op.disks: # disk idx has not been passed in
4740
        to_skip.append(idx)
4741
        continue
4742

    
4743
    _CreateDisks(self, self.instance, to_skip=to_skip)
4744

    
4745

    
4746
class LURenameInstance(LogicalUnit):
4747
  """Rename an instance.
4748

4749
  """
4750
  HPATH = "instance-rename"
4751
  HTYPE = constants.HTYPE_INSTANCE
4752
  _OP_PARAMS = [
4753
    _PInstanceName,
4754
    ("new_name", _NoDefault, _TNonEmptyString),
4755
    ("ignore_ip", False, _TBool),
4756
    ("check_name", True, _TBool),
4757
    ]
4758

    
4759
  def BuildHooksEnv(self):
4760
    """Build hooks env.
4761

4762
    This runs on master, primary and secondary nodes of the instance.
4763

4764
    """
4765
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4766
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4767
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4768
    return env, nl, nl
4769

    
4770
  def CheckPrereq(self):
4771
    """Check prerequisites.
4772

4773
    This checks that the instance is in the cluster and is not running.
4774

4775
    """
4776
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4777
                                                self.op.instance_name)
4778
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4779
    assert instance is not None
4780
    _CheckNodeOnline(self, instance.primary_node)
4781
    _CheckInstanceDown(self, instance, "cannot rename")
4782
    self.instance = instance
4783

    
4784
    # new name verification
4785
    if self.op.check_name:
4786
      name_info = utils.GetHostInfo(self.op.new_name)
4787
      self.op.new_name = name_info.name
4788

    
4789
    new_name = self.op.new_name
4790

    
4791
    instance_list = self.cfg.GetInstanceList()
4792
    if new_name in instance_list:
4793
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4794
                                 new_name, errors.ECODE_EXISTS)
4795

    
4796
    if not self.op.ignore_ip:
4797
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4798
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4799
                                   (name_info.ip, new_name),
4800
                                   errors.ECODE_NOTUNIQUE)
4801

    
4802
  def Exec(self, feedback_fn):
4803
    """Reinstall the instance.
4804

4805
    """
4806
    inst = self.instance
4807
    old_name = inst.name
4808

    
4809
    if inst.disk_template == constants.DT_FILE:
4810
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4811

    
4812
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4813
    # Change the instance lock. This is definitely safe while we hold the BGL
4814
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4815
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4816

    
4817
    # re-read the instance from the configuration after rename
4818
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4819

    
4820
    if inst.disk_template == constants.DT_FILE:
4821
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4822
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4823
                                                     old_file_storage_dir,
4824
                                                     new_file_storage_dir)
4825
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4826
                   " (but the instance has been renamed in Ganeti)" %
4827
                   (inst.primary_node, old_file_storage_dir,
4828
                    new_file_storage_dir))
4829

    
4830
    _StartInstanceDisks(self, inst, None)
4831
    try:
4832
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4833
                                                 old_name, self.op.debug_level)
4834
      msg = result.fail_msg
4835
      if msg:
4836
        msg = ("Could not run OS rename script for instance %s on node %s"
4837
               " (but the instance has been renamed in Ganeti): %s" %
4838
               (inst.name, inst.primary_node, msg))
4839
        self.proc.LogWarning(msg)
4840
    finally:
4841
      _ShutdownInstanceDisks(self, inst)
4842

    
4843

    
4844
class LURemoveInstance(LogicalUnit):
4845
  """Remove an instance.
4846

4847
  """
4848
  HPATH = "instance-remove"
4849
  HTYPE = constants.HTYPE_INSTANCE
4850
  _OP_PARAMS = [
4851
    _PInstanceName,
4852
    ("ignore_failures", False, _TBool),
4853
    _PShutdownTimeout,
4854
    ]
4855
  REQ_BGL = False
4856

    
4857
  def ExpandNames(self):
4858
    self._ExpandAndLockInstance()
4859
    self.needed_locks[locking.LEVEL_NODE] = []
4860
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4861

    
4862
  def DeclareLocks(self, level):
4863
    if level == locking.LEVEL_NODE:
4864
      self._LockInstancesNodes()
4865

    
4866
  def BuildHooksEnv(self):
4867
    """Build hooks env.
4868

4869
    This runs on master, primary and secondary nodes of the instance.
4870

4871
    """
4872
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4873
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4874
    nl = [self.cfg.GetMasterNode()]
4875
    nl_post = list(self.instance.all_nodes) + nl
4876
    return env, nl, nl_post
4877

    
4878
  def CheckPrereq(self):
4879
    """Check prerequisites.
4880

4881
    This checks that the instance is in the cluster.
4882

4883
    """
4884
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4885
    assert self.instance is not None, \
4886
      "Cannot retrieve locked instance %s" % self.op.instance_name
4887

    
4888
  def Exec(self, feedback_fn):
4889
    """Remove the instance.
4890

4891
    """
4892
    instance = self.instance
4893
    logging.info("Shutting down instance %s on node %s",
4894
                 instance.name, instance.primary_node)
4895

    
4896
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4897
                                             self.op.shutdown_timeout)
4898
    msg = result.fail_msg
4899
    if msg:
4900
      if self.op.ignore_failures:
4901
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4902
      else:
4903
        raise errors.OpExecError("Could not shutdown instance %s on"
4904
                                 " node %s: %s" %
4905
                                 (instance.name, instance.primary_node, msg))
4906

    
4907
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4908

    
4909

    
4910
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4911
  """Utility function to remove an instance.
4912

4913
  """
4914
  logging.info("Removing block devices for instance %s", instance.name)
4915

    
4916
  if not _RemoveDisks(lu, instance):
4917
    if not ignore_failures:
4918
      raise errors.OpExecError("Can't remove instance's disks")
4919
    feedback_fn("Warning: can't remove instance's disks")
4920

    
4921
  logging.info("Removing instance %s out of cluster config", instance.name)
4922

    
4923
  lu.cfg.RemoveInstance(instance.name)
4924

    
4925
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4926
    "Instance lock removal conflict"
4927

    
4928
  # Remove lock for the instance
4929
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4930

    
4931

    
4932
class LUQueryInstances(NoHooksLU):
4933
  """Logical unit for querying instances.
4934

4935
  """
4936
  # pylint: disable-msg=W0142
4937
  _OP_PARAMS = [
4938
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
4939
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
4940
    ("use_locking", False, _TBool),
4941
    ]
4942
  REQ_BGL = False
4943
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4944
                    "serial_no", "ctime", "mtime", "uuid"]
4945
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4946
                                    "admin_state",
4947
                                    "disk_template", "ip", "mac", "bridge",
4948
                                    "nic_mode", "nic_link",
4949
                                    "sda_size", "sdb_size", "vcpus", "tags",
4950
                                    "network_port", "beparams",
4951
                                    r"(disk)\.(size)/([0-9]+)",
4952
                                    r"(disk)\.(sizes)", "disk_usage",
4953
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4954
                                    r"(nic)\.(bridge)/([0-9]+)",
4955
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4956
                                    r"(disk|nic)\.(count)",
4957
                                    "hvparams",
4958
                                    ] + _SIMPLE_FIELDS +
4959
                                  ["hv/%s" % name
4960
                                   for name in constants.HVS_PARAMETERS
4961
                                   if name not in constants.HVC_GLOBALS] +
4962
                                  ["be/%s" % name
4963
                                   for name in constants.BES_PARAMETERS])
4964
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
4965

    
4966

    
4967
  def CheckArguments(self):
4968
    _CheckOutputFields(static=self._FIELDS_STATIC,
4969
                       dynamic=self._FIELDS_DYNAMIC,
4970
                       selected=self.op.output_fields)
4971

    
4972
  def ExpandNames(self):
4973
    self.needed_locks = {}
4974
    self.share_locks[locking.LEVEL_INSTANCE] = 1
4975
    self.share_locks[locking.LEVEL_NODE] = 1
4976

    
4977
    if self.op.names:
4978
      self.wanted = _GetWantedInstances(self, self.op.names)
4979
    else:
4980
      self.wanted = locking.ALL_SET
4981

    
4982
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
4983
    self.do_locking = self.do_node_query and self.op.use_locking
4984
    if self.do_locking:
4985
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
4986
      self.needed_locks[locking.LEVEL_NODE] = []
4987
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4988

    
4989
  def DeclareLocks(self, level):
4990
    if level == locking.LEVEL_NODE and self.do_locking:
4991
      self._LockInstancesNodes()
4992

    
4993
  def Exec(self, feedback_fn):
4994
    """Computes the list of nodes and their attributes.
4995

4996
    """
4997
    # pylint: disable-msg=R0912
4998
    # way too many branches here
4999
    all_info = self.cfg.GetAllInstancesInfo()
5000
    if self.wanted == locking.ALL_SET:
5001
      # caller didn't specify instance names, so ordering is not important
5002
      if self.do_locking:
5003
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5004
      else:
5005
        instance_names = all_info.keys()
5006
      instance_names = utils.NiceSort(instance_names)
5007
    else:
5008
      # caller did specify names, so we must keep the ordering
5009
      if self.do_locking:
5010
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5011
      else:
5012
        tgt_set = all_info.keys()
5013
      missing = set(self.wanted).difference(tgt_set)
5014
      if missing:
5015
        raise errors.OpExecError("Some instances were removed before"
5016
                                 " retrieving their data: %s" % missing)
5017
      instance_names = self.wanted
5018

    
5019
    instance_list = [all_info[iname] for iname in instance_names]
5020

    
5021
    # begin data gathering
5022

    
5023
    nodes = frozenset([inst.primary_node for inst in instance_list])
5024
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5025

    
5026
    bad_nodes = []
5027
    off_nodes = []
5028
    if self.do_node_query:
5029
      live_data = {}
5030
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5031
      for name in nodes:
5032
        result = node_data[name]
5033
        if result.offline:
5034
          # offline nodes will be in both lists
5035
          off_nodes.append(name)
5036
        if result.fail_msg:
5037
          bad_nodes.append(name)
5038
        else:
5039
          if result.payload:
5040
            live_data.update(result.payload)
5041
          # else no instance is alive
5042
    else:
5043
      live_data = dict([(name, {}) for name in instance_names])
5044

    
5045
    # end data gathering
5046

    
5047
    HVPREFIX = "hv/"
5048
    BEPREFIX = "be/"
5049
    output = []
5050
    cluster = self.cfg.GetClusterInfo()
5051
    for instance in instance_list:
5052
      iout = []
5053
      i_hv = cluster.FillHV(instance, skip_globals=True)
5054
      i_be = cluster.FillBE(instance)
5055
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5056
      for field in self.op.output_fields:
5057
        st_match = self._FIELDS_STATIC.Matches(field)
5058
        if field in self._SIMPLE_FIELDS:
5059
          val = getattr(instance, field)
5060
        elif field == "pnode":
5061
          val = instance.primary_node
5062
        elif field == "snodes":
5063
          val = list(instance.secondary_nodes)
5064
        elif field == "admin_state":
5065
          val = instance.admin_up
5066
        elif field == "oper_state":
5067
          if instance.primary_node in bad_nodes:
5068
            val = None
5069
          else:
5070
            val = bool(live_data.get(instance.name))
5071
        elif field == "status":
5072
          if instance.primary_node in off_nodes:
5073
            val = "ERROR_nodeoffline"
5074
          elif instance.primary_node in bad_nodes:
5075
            val = "ERROR_nodedown"
5076
          else:
5077
            running = bool(live_data.get(instance.name))
5078
            if running:
5079
              if instance.admin_up:
5080
                val = "running"
5081
              else:
5082
                val = "ERROR_up"
5083
            else:
5084
              if instance.admin_up:
5085
                val = "ERROR_down"
5086
              else:
5087
                val = "ADMIN_down"
5088
        elif field == "oper_ram":
5089
          if instance.primary_node in bad_nodes:
5090
            val = None
5091
          elif instance.name in live_data:
5092
            val = live_data[instance.name].get("memory", "?")
5093
          else:
5094
            val = "-"
5095
        elif field == "vcpus":
5096
          val = i_be[constants.BE_VCPUS]
5097
        elif field == "disk_template":
5098
          val = instance.disk_template
5099
        elif field == "ip":
5100
          if instance.nics:
5101
            val = instance.nics[0].ip
5102
          else:
5103
            val = None
5104
        elif field == "nic_mode":
5105
          if instance.nics:
5106
            val = i_nicp[0][constants.NIC_MODE]
5107
          else:
5108
            val = None
5109
        elif field == "nic_link":
5110
          if instance.nics:
5111
            val = i_nicp[0][constants.NIC_LINK]
5112
          else:
5113
            val = None
5114
        elif field == "bridge":
5115
          if (instance.nics and
5116
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5117
            val = i_nicp[0][constants.NIC_LINK]
5118
          else:
5119
            val = None
5120
        elif field == "mac":
5121
          if instance.nics:
5122
            val = instance.nics[0].mac
5123
          else:
5124
            val = None
5125
        elif field == "sda_size" or field == "sdb_size":
5126
          idx = ord(field[2]) - ord('a')
5127
          try:
5128
            val = instance.FindDisk(idx).size
5129
          except errors.OpPrereqError:
5130
            val = None
5131
        elif field == "disk_usage": # total disk usage per node
5132
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5133
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5134
        elif field == "tags":
5135
          val = list(instance.GetTags())
5136
        elif field == "hvparams":
5137
          val = i_hv
5138
        elif (field.startswith(HVPREFIX) and
5139
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5140
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5141
          val = i_hv.get(field[len(HVPREFIX):], None)
5142
        elif field == "beparams":
5143
          val = i_be
5144
        elif (field.startswith(BEPREFIX) and
5145
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5146
          val = i_be.get(field[len(BEPREFIX):], None)
5147
        elif st_match and st_match.groups():
5148
          # matches a variable list
5149
          st_groups = st_match.groups()
5150
          if st_groups and st_groups[0] == "disk":
5151
            if st_groups[1] == "count":
5152
              val = len(instance.disks)
5153
            elif st_groups[1] == "sizes":
5154
              val = [disk.size for disk in instance.disks]
5155
            elif st_groups[1] == "size":
5156
              try:
5157
                val = instance.FindDisk(st_groups[2]).size
5158
              except errors.OpPrereqError:
5159
                val = None
5160
            else:
5161
              assert False, "Unhandled disk parameter"
5162
          elif st_groups[0] == "nic":
5163
            if st_groups[1] == "count":
5164
              val = len(instance.nics)
5165
            elif st_groups[1] == "macs":
5166
              val = [nic.mac for nic in instance.nics]
5167
            elif st_groups[1] == "ips":
5168
              val = [nic.ip for nic in instance.nics]
5169
            elif st_groups[1] == "modes":
5170
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5171
            elif st_groups[1] == "links":
5172
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5173
            elif st_groups[1] == "bridges":
5174
              val = []
5175
              for nicp in i_nicp:
5176
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5177
                  val.append(nicp[constants.NIC_LINK])
5178
                else:
5179
                  val.append(None)
5180
            else:
5181
              # index-based item
5182
              nic_idx = int(st_groups[2])
5183
              if nic_idx >= len(instance.nics):
5184
                val = None
5185
              else:
5186
                if st_groups[1] == "mac":
5187
                  val = instance.nics[nic_idx].mac
5188
                elif st_groups[1] == "ip":
5189
                  val = instance.nics[nic_idx].ip
5190
                elif st_groups[1] == "mode":
5191
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5192
                elif st_groups[1] == "link":
5193
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5194
                elif st_groups[1] == "bridge":
5195
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5196
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5197
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5198
                  else:
5199
                    val = None
5200
                else:
5201
                  assert False, "Unhandled NIC parameter"
5202
          else:
5203
            assert False, ("Declared but unhandled variable parameter '%s'" %
5204
                           field)
5205
        else:
5206
          assert False, "Declared but unhandled parameter '%s'" % field
5207
        iout.append(val)
5208
      output.append(iout)
5209

    
5210
    return output
5211

    
5212

    
5213
class LUFailoverInstance(LogicalUnit):
5214
  """Failover an instance.
5215

5216
  """
5217
  HPATH = "instance-failover"
5218
  HTYPE = constants.HTYPE_INSTANCE
5219
  _OP_PARAMS = [
5220
    _PInstanceName,
5221
    ("ignore_consistency", False, _TBool),
5222
    _PShutdownTimeout,
5223
    ]
5224
  REQ_BGL = False
5225

    
5226
  def ExpandNames(self):
5227
    self._ExpandAndLockInstance()
5228
    self.needed_locks[locking.LEVEL_NODE] = []
5229
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5230

    
5231
  def DeclareLocks(self, level):
5232
    if level == locking.LEVEL_NODE:
5233
      self._LockInstancesNodes()
5234

    
5235
  def BuildHooksEnv(self):
5236
    """Build hooks env.
5237

5238
    This runs on master, primary and secondary nodes of the instance.
5239

5240
    """
5241
    instance = self.instance
5242
    source_node = instance.primary_node
5243
    target_node = instance.secondary_nodes[0]
5244
    env = {
5245
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5246
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5247
      "OLD_PRIMARY": source_node,
5248
      "OLD_SECONDARY": target_node,
5249
      "NEW_PRIMARY": target_node,
5250
      "NEW_SECONDARY": source_node,
5251
      }
5252
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5253
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5254
    nl_post = list(nl)
5255
    nl_post.append(source_node)
5256
    return env, nl, nl_post
5257

    
5258
  def CheckPrereq(self):
5259
    """Check prerequisites.
5260

5261
    This checks that the instance is in the cluster.
5262

5263
    """
5264
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5265
    assert self.instance is not None, \
5266
      "Cannot retrieve locked instance %s" % self.op.instance_name
5267

    
5268
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5269
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5270
      raise errors.OpPrereqError("Instance's disk layout is not"
5271
                                 " network mirrored, cannot failover.",
5272
                                 errors.ECODE_STATE)
5273

    
5274
    secondary_nodes = instance.secondary_nodes
5275
    if not secondary_nodes:
5276
      raise errors.ProgrammerError("no secondary node but using "
5277
                                   "a mirrored disk template")
5278

    
5279
    target_node = secondary_nodes[0]
5280
    _CheckNodeOnline(self, target_node)
5281
    _CheckNodeNotDrained(self, target_node)
5282
    if instance.admin_up:
5283
      # check memory requirements on the secondary node
5284
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5285
                           instance.name, bep[constants.BE_MEMORY],
5286
                           instance.hypervisor)
5287
    else:
5288
      self.LogInfo("Not checking memory on the secondary node as"
5289
                   " instance will not be started")
5290

    
5291
    # check bridge existance
5292
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5293

    
5294
  def Exec(self, feedback_fn):
5295
    """Failover an instance.
5296

5297
    The failover is done by shutting it down on its present node and
5298
    starting it on the secondary.
5299

5300
    """
5301
    instance = self.instance
5302

    
5303
    source_node = instance.primary_node
5304
    target_node = instance.secondary_nodes[0]
5305

    
5306
    if instance.admin_up:
5307
      feedback_fn("* checking disk consistency between source and target")
5308
      for dev in instance.disks:
5309
        # for drbd, these are drbd over lvm
5310
        if not _CheckDiskConsistency(self, dev, target_node, False):
5311
          if not self.op.ignore_consistency:
5312
            raise errors.OpExecError("Disk %s is degraded on target node,"
5313
                                     " aborting failover." % dev.iv_name)
5314
    else:
5315
      feedback_fn("* not checking disk consistency as instance is not running")
5316

    
5317
    feedback_fn("* shutting down instance on source node")
5318
    logging.info("Shutting down instance %s on node %s",
5319
                 instance.name, source_node)
5320

    
5321
    result = self.rpc.call_instance_shutdown(source_node, instance,
5322
                                             self.op.shutdown_timeout)
5323
    msg = result.fail_msg
5324
    if msg:
5325
      if self.op.ignore_consistency:
5326
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5327
                             " Proceeding anyway. Please make sure node"
5328
                             " %s is down. Error details: %s",
5329
                             instance.name, source_node, source_node, msg)
5330
      else:
5331
        raise errors.OpExecError("Could not shutdown instance %s on"
5332
                                 " node %s: %s" %
5333
                                 (instance.name, source_node, msg))
5334

    
5335
    feedback_fn("* deactivating the instance's disks on source node")
5336
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5337
      raise errors.OpExecError("Can't shut down the instance's disks.")
5338

    
5339
    instance.primary_node = target_node
5340
    # distribute new instance config to the other nodes
5341
    self.cfg.Update(instance, feedback_fn)
5342

    
5343
    # Only start the instance if it's marked as up
5344
    if instance.admin_up:
5345
      feedback_fn("* activating the instance's disks on target node")
5346
      logging.info("Starting instance %s on node %s",
5347
                   instance.name, target_node)
5348

    
5349
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5350
                                           ignore_secondaries=True)
5351
      if not disks_ok:
5352
        _ShutdownInstanceDisks(self, instance)
5353
        raise errors.OpExecError("Can't activate the instance's disks")
5354

    
5355
      feedback_fn("* starting the instance on the target node")
5356
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5357
      msg = result.fail_msg
5358
      if msg:
5359
        _ShutdownInstanceDisks(self, instance)
5360
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5361
                                 (instance.name, target_node, msg))
5362

    
5363

    
5364
class LUMigrateInstance(LogicalUnit):
5365
  """Migrate an instance.
5366

5367
  This is migration without shutting down, compared to the failover,
5368
  which is done with shutdown.
5369

5370
  """
5371
  HPATH = "instance-migrate"
5372
  HTYPE = constants.HTYPE_INSTANCE
5373
  _OP_PARAMS = [
5374
    _PInstanceName,
5375
    ("live", True, _TBool),
5376
    ("cleanup", False, _TBool),
5377
    ]
5378

    
5379
  REQ_BGL = False
5380

    
5381
  def ExpandNames(self):
5382
    self._ExpandAndLockInstance()
5383

    
5384
    self.needed_locks[locking.LEVEL_NODE] = []
5385
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5386

    
5387
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5388
                                       self.op.live, self.op.cleanup)
5389
    self.tasklets = [self._migrater]
5390

    
5391
  def DeclareLocks(self, level):
5392
    if level == locking.LEVEL_NODE:
5393
      self._LockInstancesNodes()
5394

    
5395
  def BuildHooksEnv(self):
5396
    """Build hooks env.
5397

5398
    This runs on master, primary and secondary nodes of the instance.
5399

5400
    """
5401
    instance = self._migrater.instance
5402
    source_node = instance.primary_node
5403
    target_node = instance.secondary_nodes[0]
5404
    env = _BuildInstanceHookEnvByObject(self, instance)
5405
    env["MIGRATE_LIVE"] = self.op.live
5406
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5407
    env.update({
5408
        "OLD_PRIMARY": source_node,
5409
        "OLD_SECONDARY": target_node,
5410
        "NEW_PRIMARY": target_node,
5411
        "NEW_SECONDARY": source_node,
5412
        })
5413
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5414
    nl_post = list(nl)
5415
    nl_post.append(source_node)
5416
    return env, nl, nl_post
5417

    
5418

    
5419
class LUMoveInstance(LogicalUnit):
5420
  """Move an instance by data-copying.
5421

5422
  """
5423
  HPATH = "instance-move"
5424
  HTYPE = constants.HTYPE_INSTANCE
5425
  _OP_PARAMS = [
5426
    _PInstanceName,
5427
    ("target_node", _NoDefault, _TNonEmptyString),
5428
    _PShutdownTimeout,
5429
    ]
5430
  REQ_BGL = False
5431

    
5432
  def ExpandNames(self):
5433
    self._ExpandAndLockInstance()
5434
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5435
    self.op.target_node = target_node
5436
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5437
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5438

    
5439
  def DeclareLocks(self, level):
5440
    if level == locking.LEVEL_NODE:
5441
      self._LockInstancesNodes(primary_only=True)
5442

    
5443
  def BuildHooksEnv(self):
5444
    """Build hooks env.
5445

5446
    This runs on master, primary and secondary nodes of the instance.
5447

5448
    """
5449
    env = {
5450
      "TARGET_NODE": self.op.target_node,
5451
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5452
      }
5453
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5454
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5455
                                       self.op.target_node]
5456
    return env, nl, nl
5457

    
5458
  def CheckPrereq(self):
5459
    """Check prerequisites.
5460

5461
    This checks that the instance is in the cluster.
5462

5463
    """
5464
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5465
    assert self.instance is not None, \
5466
      "Cannot retrieve locked instance %s" % self.op.instance_name
5467

    
5468
    node = self.cfg.GetNodeInfo(self.op.target_node)
5469
    assert node is not None, \
5470
      "Cannot retrieve locked node %s" % self.op.target_node
5471

    
5472
    self.target_node = target_node = node.name
5473

    
5474
    if target_node == instance.primary_node:
5475
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5476
                                 (instance.name, target_node),
5477
                                 errors.ECODE_STATE)
5478

    
5479
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5480

    
5481
    for idx, dsk in enumerate(instance.disks):
5482
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5483
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5484
                                   " cannot copy" % idx, errors.ECODE_STATE)
5485

    
5486
    _CheckNodeOnline(self, target_node)
5487
    _CheckNodeNotDrained(self, target_node)
5488

    
5489
    if instance.admin_up:
5490
      # check memory requirements on the secondary node
5491
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5492
                           instance.name, bep[constants.BE_MEMORY],
5493
                           instance.hypervisor)
5494
    else:
5495
      self.LogInfo("Not checking memory on the secondary node as"
5496
                   " instance will not be started")
5497

    
5498
    # check bridge existance
5499
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5500

    
5501
  def Exec(self, feedback_fn):
5502
    """Move an instance.
5503

5504
    The move is done by shutting it down on its present node, copying
5505
    the data over (slow) and starting it on the new node.
5506

5507
    """
5508
    instance = self.instance
5509

    
5510
    source_node = instance.primary_node
5511
    target_node = self.target_node
5512

    
5513
    self.LogInfo("Shutting down instance %s on source node %s",
5514
                 instance.name, source_node)
5515

    
5516
    result = self.rpc.call_instance_shutdown(source_node, instance,
5517
                                             self.op.shutdown_timeout)
5518
    msg = result.fail_msg
5519
    if msg:
5520
      if self.op.ignore_consistency:
5521
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5522
                             " Proceeding anyway. Please make sure node"
5523
                             " %s is down. Error details: %s",
5524
                             instance.name, source_node, source_node, msg)
5525
      else:
5526
        raise errors.OpExecError("Could not shutdown instance %s on"
5527
                                 " node %s: %s" %
5528
                                 (instance.name, source_node, msg))
5529

    
5530
    # create the target disks
5531
    try:
5532
      _CreateDisks(self, instance, target_node=target_node)
5533
    except errors.OpExecError:
5534
      self.LogWarning("Device creation failed, reverting...")
5535
      try:
5536
        _RemoveDisks(self, instance, target_node=target_node)
5537
      finally:
5538
        self.cfg.ReleaseDRBDMinors(instance.name)
5539
        raise
5540

    
5541
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5542

    
5543
    errs = []
5544
    # activate, get path, copy the data over
5545
    for idx, disk in enumerate(instance.disks):
5546
      self.LogInfo("Copying data for disk %d", idx)
5547
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5548
                                               instance.name, True)
5549
      if result.fail_msg:
5550
        self.LogWarning("Can't assemble newly created disk %d: %s",
5551
                        idx, result.fail_msg)
5552
        errs.append(result.fail_msg)
5553
        break
5554
      dev_path = result.payload
5555
      result = self.rpc.call_blockdev_export(source_node, disk,
5556
                                             target_node, dev_path,
5557
                                             cluster_name)
5558
      if result.fail_msg:
5559
        self.LogWarning("Can't copy data over for disk %d: %s",
5560
                        idx, result.fail_msg)
5561
        errs.append(result.fail_msg)
5562
        break
5563

    
5564
    if errs:
5565
      self.LogWarning("Some disks failed to copy, aborting")
5566
      try:
5567
        _RemoveDisks(self, instance, target_node=target_node)
5568
      finally:
5569
        self.cfg.ReleaseDRBDMinors(instance.name)
5570
        raise errors.OpExecError("Errors during disk copy: %s" %
5571
                                 (",".join(errs),))
5572

    
5573
    instance.primary_node = target_node
5574
    self.cfg.Update(instance, feedback_fn)
5575

    
5576
    self.LogInfo("Removing the disks on the original node")
5577
    _RemoveDisks(self, instance, target_node=source_node)
5578

    
5579
    # Only start the instance if it's marked as up
5580
    if instance.admin_up:
5581
      self.LogInfo("Starting instance %s on node %s",
5582
                   instance.name, target_node)
5583

    
5584
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5585
                                           ignore_secondaries=True)
5586
      if not disks_ok:
5587
        _ShutdownInstanceDisks(self, instance)
5588
        raise errors.OpExecError("Can't activate the instance's disks")
5589

    
5590
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5591
      msg = result.fail_msg
5592
      if msg:
5593
        _ShutdownInstanceDisks(self, instance)
5594
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5595
                                 (instance.name, target_node, msg))
5596

    
5597

    
5598
class LUMigrateNode(LogicalUnit):
5599
  """Migrate all instances from a node.
5600

5601
  """
5602
  HPATH = "node-migrate"
5603
  HTYPE = constants.HTYPE_NODE
5604
  _OP_PARAMS = [
5605
    _PNodeName,
5606
    ("live", False, _TBool),
5607
    ]
5608
  REQ_BGL = False
5609

    
5610
  def ExpandNames(self):
5611
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5612

    
5613
    self.needed_locks = {
5614
      locking.LEVEL_NODE: [self.op.node_name],
5615
      }
5616

    
5617
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5618

    
5619
    # Create tasklets for migrating instances for all instances on this node
5620
    names = []
5621
    tasklets = []
5622

    
5623
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5624
      logging.debug("Migrating instance %s", inst.name)
5625
      names.append(inst.name)
5626

    
5627
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5628

    
5629
    self.tasklets = tasklets
5630

    
5631
    # Declare instance locks
5632
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5633

    
5634
  def DeclareLocks(self, level):
5635
    if level == locking.LEVEL_NODE:
5636
      self._LockInstancesNodes()
5637

    
5638
  def BuildHooksEnv(self):
5639
    """Build hooks env.
5640

5641
    This runs on the master, the primary and all the secondaries.
5642

5643
    """
5644
    env = {
5645
      "NODE_NAME": self.op.node_name,
5646
      }
5647

    
5648
    nl = [self.cfg.GetMasterNode()]
5649

    
5650
    return (env, nl, nl)
5651

    
5652

    
5653
class TLMigrateInstance(Tasklet):
5654
  def __init__(self, lu, instance_name, live, cleanup):
5655
    """Initializes this class.
5656

5657
    """
5658
    Tasklet.__init__(self, lu)
5659

    
5660
    # Parameters
5661
    self.instance_name = instance_name
5662
    self.live = live
5663
    self.cleanup = cleanup
5664

    
5665
  def CheckPrereq(self):
5666
    """Check prerequisites.
5667

5668
    This checks that the instance is in the cluster.
5669

5670
    """
5671
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5672
    instance = self.cfg.GetInstanceInfo(instance_name)
5673
    assert instance is not None
5674

    
5675
    if instance.disk_template != constants.DT_DRBD8:
5676
      raise errors.OpPrereqError("Instance's disk layout is not"
5677
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5678

    
5679
    secondary_nodes = instance.secondary_nodes
5680
    if not secondary_nodes:
5681
      raise errors.ConfigurationError("No secondary node but using"
5682
                                      " drbd8 disk template")
5683

    
5684
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5685

    
5686
    target_node = secondary_nodes[0]
5687
    # check memory requirements on the secondary node
5688
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5689
                         instance.name, i_be[constants.BE_MEMORY],
5690
                         instance.hypervisor)
5691

    
5692
    # check bridge existance
5693
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5694

    
5695
    if not self.cleanup:
5696
      _CheckNodeNotDrained(self.lu, target_node)
5697
      result = self.rpc.call_instance_migratable(instance.primary_node,
5698
                                                 instance)
5699
      result.Raise("Can't migrate, please use failover",
5700
                   prereq=True, ecode=errors.ECODE_STATE)
5701

    
5702
    self.instance = instance
5703

    
5704
  def _WaitUntilSync(self):
5705
    """Poll with custom rpc for disk sync.
5706

5707
    This uses our own step-based rpc call.
5708

5709
    """
5710
    self.feedback_fn("* wait until resync is done")
5711
    all_done = False
5712
    while not all_done:
5713
      all_done = True
5714
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5715
                                            self.nodes_ip,
5716
                                            self.instance.disks)
5717
      min_percent = 100
5718
      for node, nres in result.items():
5719
        nres.Raise("Cannot resync disks on node %s" % node)
5720
        node_done, node_percent = nres.payload
5721
        all_done = all_done and node_done
5722
        if node_percent is not None:
5723
          min_percent = min(min_percent, node_percent)
5724
      if not all_done:
5725
        if min_percent < 100:
5726
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5727
        time.sleep(2)
5728

    
5729
  def _EnsureSecondary(self, node):
5730
    """Demote a node to secondary.
5731

5732
    """
5733
    self.feedback_fn("* switching node %s to secondary mode" % node)
5734

    
5735
    for dev in self.instance.disks:
5736
      self.cfg.SetDiskID(dev, node)
5737

    
5738
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5739
                                          self.instance.disks)
5740
    result.Raise("Cannot change disk to secondary on node %s" % node)
5741

    
5742
  def _GoStandalone(self):
5743
    """Disconnect from the network.
5744

5745
    """
5746
    self.feedback_fn("* changing into standalone mode")
5747
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5748
                                               self.instance.disks)
5749
    for node, nres in result.items():
5750
      nres.Raise("Cannot disconnect disks node %s" % node)
5751

    
5752
  def _GoReconnect(self, multimaster):
5753
    """Reconnect to the network.
5754

5755
    """
5756
    if multimaster:
5757
      msg = "dual-master"
5758
    else:
5759
      msg = "single-master"
5760
    self.feedback_fn("* changing disks into %s mode" % msg)
5761
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5762
                                           self.instance.disks,
5763
                                           self.instance.name, multimaster)
5764
    for node, nres in result.items():
5765
      nres.Raise("Cannot change disks config on node %s" % node)
5766

    
5767
  def _ExecCleanup(self):
5768
    """Try to cleanup after a failed migration.
5769

5770
    The cleanup is done by:
5771
      - check that the instance is running only on one node
5772
        (and update the config if needed)
5773
      - change disks on its secondary node to secondary
5774
      - wait until disks are fully synchronized
5775
      - disconnect from the network
5776
      - change disks into single-master mode
5777
      - wait again until disks are fully synchronized
5778

5779
    """
5780
    instance = self.instance
5781
    target_node = self.target_node
5782
    source_node = self.source_node
5783

    
5784
    # check running on only one node
5785
    self.feedback_fn("* checking where the instance actually runs"
5786
                     " (if this hangs, the hypervisor might be in"
5787
                     " a bad state)")
5788
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5789
    for node, result in ins_l.items():
5790
      result.Raise("Can't contact node %s" % node)
5791

    
5792
    runningon_source = instance.name in ins_l[source_node].payload
5793
    runningon_target = instance.name in ins_l[target_node].payload
5794

    
5795
    if runningon_source and runningon_target:
5796
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5797
                               " or the hypervisor is confused. You will have"
5798
                               " to ensure manually that it runs only on one"
5799
                               " and restart this operation.")
5800

    
5801
    if not (runningon_source or runningon_target):
5802
      raise errors.OpExecError("Instance does not seem to be running at all."
5803
                               " In this case, it's safer to repair by"
5804
                               " running 'gnt-instance stop' to ensure disk"
5805
                               " shutdown, and then restarting it.")
5806

    
5807
    if runningon_target:
5808
      # the migration has actually succeeded, we need to update the config
5809
      self.feedback_fn("* instance running on secondary node (%s),"
5810
                       " updating config" % target_node)
5811
      instance.primary_node = target_node
5812
      self.cfg.Update(instance, self.feedback_fn)
5813
      demoted_node = source_node
5814
    else:
5815
      self.feedback_fn("* instance confirmed to be running on its"
5816
                       " primary node (%s)" % source_node)
5817
      demoted_node = target_node
5818

    
5819
    self._EnsureSecondary(demoted_node)
5820
    try:
5821
      self._WaitUntilSync()
5822
    except errors.OpExecError:
5823
      # we ignore here errors, since if the device is standalone, it
5824
      # won't be able to sync
5825
      pass
5826
    self._GoStandalone()
5827
    self._GoReconnect(False)
5828
    self._WaitUntilSync()
5829

    
5830
    self.feedback_fn("* done")
5831

    
5832
  def _RevertDiskStatus(self):
5833
    """Try to revert the disk status after a failed migration.
5834

5835
    """
5836
    target_node = self.target_node
5837
    try:
5838
      self._EnsureSecondary(target_node)
5839
      self._GoStandalone()
5840
      self._GoReconnect(False)
5841
      self._WaitUntilSync()
5842
    except errors.OpExecError, err:
5843
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5844
                         " drives: error '%s'\n"
5845
                         "Please look and recover the instance status" %
5846
                         str(err))
5847

    
5848
  def _AbortMigration(self):
5849
    """Call the hypervisor code to abort a started migration.
5850

5851
    """
5852
    instance = self.instance
5853
    target_node = self.target_node
5854
    migration_info = self.migration_info
5855

    
5856
    abort_result = self.rpc.call_finalize_migration(target_node,
5857
                                                    instance,
5858
                                                    migration_info,
5859
                                                    False)
5860
    abort_msg = abort_result.fail_msg
5861
    if abort_msg:
5862
      logging.error("Aborting migration failed on target node %s: %s",
5863
                    target_node, abort_msg)
5864
      # Don't raise an exception here, as we stil have to try to revert the
5865
      # disk status, even if this step failed.
5866

    
5867
  def _ExecMigration(self):
5868
    """Migrate an instance.
5869

5870
    The migrate is done by:
5871
      - change the disks into dual-master mode
5872
      - wait until disks are fully synchronized again
5873
      - migrate the instance
5874
      - change disks on the new secondary node (the old primary) to secondary
5875
      - wait until disks are fully synchronized
5876
      - change disks into single-master mode
5877

5878
    """
5879
    instance = self.instance
5880
    target_node = self.target_node
5881
    source_node = self.source_node
5882

    
5883
    self.feedback_fn("* checking disk consistency between source and target")
5884
    for dev in instance.disks:
5885
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5886
        raise errors.OpExecError("Disk %s is degraded or not fully"
5887
                                 " synchronized on target node,"
5888
                                 " aborting migrate." % dev.iv_name)
5889

    
5890
    # First get the migration information from the remote node
5891
    result = self.rpc.call_migration_info(source_node, instance)
5892
    msg = result.fail_msg
5893
    if msg:
5894
      log_err = ("Failed fetching source migration information from %s: %s" %
5895
                 (source_node, msg))
5896
      logging.error(log_err)
5897
      raise errors.OpExecError(log_err)
5898

    
5899
    self.migration_info = migration_info = result.payload
5900

    
5901
    # Then switch the disks to master/master mode
5902
    self._EnsureSecondary(target_node)
5903
    self._GoStandalone()
5904
    self._GoReconnect(True)
5905
    self._WaitUntilSync()
5906

    
5907
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5908
    result = self.rpc.call_accept_instance(target_node,
5909
                                           instance,
5910
                                           migration_info,
5911
                                           self.nodes_ip[target_node])
5912

    
5913
    msg = result.fail_msg
5914
    if msg:
5915
      logging.error("Instance pre-migration failed, trying to revert"
5916
                    " disk status: %s", msg)
5917
      self.feedback_fn("Pre-migration failed, aborting")
5918
      self._AbortMigration()
5919
      self._RevertDiskStatus()
5920
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5921
                               (instance.name, msg))
5922

    
5923
    self.feedback_fn("* migrating instance to %s" % target_node)
5924
    time.sleep(10)
5925
    result = self.rpc.call_instance_migrate(source_node, instance,
5926
                                            self.nodes_ip[target_node],
5927
                                            self.live)
5928
    msg = result.fail_msg
5929
    if msg:
5930
      logging.error("Instance migration failed, trying to revert"
5931
                    " disk status: %s", msg)
5932
      self.feedback_fn("Migration failed, aborting")
5933
      self._AbortMigration()
5934
      self._RevertDiskStatus()
5935
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5936
                               (instance.name, msg))
5937
    time.sleep(10)
5938

    
5939
    instance.primary_node = target_node
5940
    # distribute new instance config to the other nodes
5941
    self.cfg.Update(instance, self.feedback_fn)
5942

    
5943
    result = self.rpc.call_finalize_migration(target_node,
5944
                                              instance,
5945
                                              migration_info,
5946
                                              True)
5947
    msg = result.fail_msg
5948
    if msg:
5949
      logging.error("Instance migration succeeded, but finalization failed:"
5950
                    " %s", msg)
5951
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5952
                               msg)
5953

    
5954
    self._EnsureSecondary(source_node)
5955
    self._WaitUntilSync()
5956
    self._GoStandalone()
5957
    self._GoReconnect(False)
5958
    self._WaitUntilSync()
5959

    
5960
    self.feedback_fn("* done")
5961

    
5962
  def Exec(self, feedback_fn):
5963
    """Perform the migration.
5964

5965
    """
5966
    feedback_fn("Migrating instance %s" % self.instance.name)
5967

    
5968
    self.feedback_fn = feedback_fn
5969

    
5970
    self.source_node = self.instance.primary_node
5971
    self.target_node = self.instance.secondary_nodes[0]
5972
    self.all_nodes = [self.source_node, self.target_node]
5973
    self.nodes_ip = {
5974
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
5975
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
5976
      }
5977

    
5978
    if self.cleanup:
5979
      return self._ExecCleanup()
5980
    else:
5981
      return self._ExecMigration()
5982

    
5983

    
5984
def _CreateBlockDev(lu, node, instance, device, force_create,
5985
                    info, force_open):
5986
  """Create a tree of block devices on a given node.
5987

5988
  If this device type has to be created on secondaries, create it and
5989
  all its children.
5990

5991
  If not, just recurse to children keeping the same 'force' value.
5992

5993
  @param lu: the lu on whose behalf we execute
5994
  @param node: the node on which to create the device
5995
  @type instance: L{objects.Instance}
5996
  @param instance: the instance which owns the device
5997
  @type device: L{objects.Disk}
5998
  @param device: the device to create
5999
  @type force_create: boolean
6000
  @param force_create: whether to force creation of this device; this
6001
      will be change to True whenever we find a device which has
6002
      CreateOnSecondary() attribute
6003
  @param info: the extra 'metadata' we should attach to the device
6004
      (this will be represented as a LVM tag)
6005
  @type force_open: boolean
6006
  @param force_open: this parameter will be passes to the
6007
      L{backend.BlockdevCreate} function where it specifies
6008
      whether we run on primary or not, and it affects both
6009
      the child assembly and the device own Open() execution
6010

6011
  """
6012
  if device.CreateOnSecondary():
6013
    force_create = True
6014

    
6015
  if device.children:
6016
    for child in device.children:
6017
      _CreateBlockDev(lu, node, instance, child, force_create,
6018
                      info, force_open)
6019

    
6020
  if not force_create:
6021
    return
6022

    
6023
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6024

    
6025

    
6026
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6027
  """Create a single block device on a given node.
6028

6029
  This will not recurse over children of the device, so they must be
6030
  created in advance.
6031

6032
  @param lu: the lu on whose behalf we execute
6033
  @param node: the node on which to create the device
6034
  @type instance: L{objects.Instance}
6035
  @param instance: the instance which owns the device
6036
  @type device: L{objects.Disk}
6037
  @param device: the device to create
6038
  @param info: the extra 'metadata' we should attach to the device
6039
      (this will be represented as a LVM tag)
6040
  @type force_open: boolean
6041
  @param force_open: this parameter will be passes to the
6042
      L{backend.BlockdevCreate} function where it specifies
6043
      whether we run on primary or not, and it affects both
6044
      the child assembly and the device own Open() execution
6045

6046
  """
6047
  lu.cfg.SetDiskID(device, node)
6048
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6049
                                       instance.name, force_open, info)
6050
  result.Raise("Can't create block device %s on"
6051
               " node %s for instance %s" % (device, node, instance.name))
6052
  if device.physical_id is None:
6053
    device.physical_id = result.payload
6054

    
6055

    
6056
def _GenerateUniqueNames(lu, exts):
6057
  """Generate a suitable LV name.
6058

6059
  This will generate a logical volume name for the given instance.
6060

6061
  """
6062
  results = []
6063
  for val in exts:
6064
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6065
    results.append("%s%s" % (new_id, val))
6066
  return results
6067

    
6068

    
6069
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6070
                         p_minor, s_minor):
6071
  """Generate a drbd8 device complete with its children.
6072

6073
  """
6074
  port = lu.cfg.AllocatePort()
6075
  vgname = lu.cfg.GetVGName()
6076
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6077
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6078
                          logical_id=(vgname, names[0]))
6079
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6080
                          logical_id=(vgname, names[1]))
6081
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6082
                          logical_id=(primary, secondary, port,
6083
                                      p_minor, s_minor,
6084
                                      shared_secret),
6085
                          children=[dev_data, dev_meta],
6086
                          iv_name=iv_name)
6087
  return drbd_dev
6088

    
6089

    
6090
def _GenerateDiskTemplate(lu, template_name,
6091
                          instance_name, primary_node,
6092
                          secondary_nodes, disk_info,
6093
                          file_storage_dir, file_driver,
6094
                          base_index):
6095
  """Generate the entire disk layout for a given template type.
6096

6097
  """
6098
  #TODO: compute space requirements
6099

    
6100
  vgname = lu.cfg.GetVGName()
6101
  disk_count = len(disk_info)
6102
  disks = []
6103
  if template_name == constants.DT_DISKLESS:
6104
    pass
6105
  elif template_name == constants.DT_PLAIN:
6106
    if len(secondary_nodes) != 0:
6107
      raise errors.ProgrammerError("Wrong template configuration")
6108

    
6109
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6110
                                      for i in range(disk_count)])
6111
    for idx, disk in enumerate(disk_info):
6112
      disk_index = idx + base_index
6113
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6114
                              logical_id=(vgname, names[idx]),
6115
                              iv_name="disk/%d" % disk_index,
6116
                              mode=disk["mode"])
6117
      disks.append(disk_dev)
6118
  elif template_name == constants.DT_DRBD8:
6119
    if len(secondary_nodes) != 1:
6120
      raise errors.ProgrammerError("Wrong template configuration")
6121
    remote_node = secondary_nodes[0]
6122
    minors = lu.cfg.AllocateDRBDMinor(
6123
      [primary_node, remote_node] * len(disk_info), instance_name)
6124

    
6125
    names = []
6126
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6127
                                               for i in range(disk_count)]):
6128
      names.append(lv_prefix + "_data")
6129
      names.append(lv_prefix + "_meta")
6130
    for idx, disk in enumerate(disk_info):
6131
      disk_index = idx + base_index
6132
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6133
                                      disk["size"], names[idx*2:idx*2+2],
6134
                                      "disk/%d" % disk_index,
6135
                                      minors[idx*2], minors[idx*2+1])
6136
      disk_dev.mode = disk["mode"]
6137
      disks.append(disk_dev)
6138
  elif template_name == constants.DT_FILE:
6139
    if len(secondary_nodes) != 0:
6140
      raise errors.ProgrammerError("Wrong template configuration")
6141

    
6142
    _RequireFileStorage()
6143

    
6144
    for idx, disk in enumerate(disk_info):
6145
      disk_index = idx + base_index
6146
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6147
                              iv_name="disk/%d" % disk_index,
6148
                              logical_id=(file_driver,
6149
                                          "%s/disk%d" % (file_storage_dir,
6150
                                                         disk_index)),
6151
                              mode=disk["mode"])
6152
      disks.append(disk_dev)
6153
  else:
6154
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6155
  return disks
6156

    
6157

    
6158
def _GetInstanceInfoText(instance):
6159
  """Compute that text that should be added to the disk's metadata.
6160

6161
  """
6162
  return "originstname+%s" % instance.name
6163

    
6164

    
6165
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6166
  """Create all disks for an instance.
6167

6168
  This abstracts away some work from AddInstance.
6169

6170
  @type lu: L{LogicalUnit}
6171
  @param lu: the logical unit on whose behalf we execute
6172
  @type instance: L{objects.Instance}
6173
  @param instance: the instance whose disks we should create
6174
  @type to_skip: list
6175
  @param to_skip: list of indices to skip
6176
  @type target_node: string
6177
  @param target_node: if passed, overrides the target node for creation
6178
  @rtype: boolean
6179
  @return: the success of the creation
6180

6181
  """
6182
  info = _GetInstanceInfoText(instance)
6183
  if target_node is None:
6184
    pnode = instance.primary_node
6185
    all_nodes = instance.all_nodes
6186
  else:
6187
    pnode = target_node
6188
    all_nodes = [pnode]
6189

    
6190
  if instance.disk_template == constants.DT_FILE:
6191
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6192
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6193

    
6194
    result.Raise("Failed to create directory '%s' on"
6195
                 " node %s" % (file_storage_dir, pnode))
6196

    
6197
  # Note: this needs to be kept in sync with adding of disks in
6198
  # LUSetInstanceParams
6199
  for idx, device in enumerate(instance.disks):
6200
    if to_skip and idx in to_skip:
6201
      continue
6202
    logging.info("Creating volume %s for instance %s",
6203
                 device.iv_name, instance.name)
6204
    #HARDCODE
6205
    for node in all_nodes:
6206
      f_create = node == pnode
6207
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6208

    
6209

    
6210
def _RemoveDisks(lu, instance, target_node=None):
6211
  """Remove all disks for an instance.
6212

6213
  This abstracts away some work from `AddInstance()` and
6214
  `RemoveInstance()`. Note that in case some of the devices couldn't
6215
  be removed, the removal will continue with the other ones (compare
6216
  with `_CreateDisks()`).
6217

6218
  @type lu: L{LogicalUnit}
6219
  @param lu: the logical unit on whose behalf we execute
6220
  @type instance: L{objects.Instance}
6221
  @param instance: the instance whose disks we should remove
6222
  @type target_node: string
6223
  @param target_node: used to override the node on which to remove the disks
6224
  @rtype: boolean
6225
  @return: the success of the removal
6226

6227
  """
6228
  logging.info("Removing block devices for instance %s", instance.name)
6229

    
6230
  all_result = True
6231
  for device in instance.disks:
6232
    if target_node:
6233
      edata = [(target_node, device)]
6234
    else:
6235
      edata = device.ComputeNodeTree(instance.primary_node)
6236
    for node, disk in edata:
6237
      lu.cfg.SetDiskID(disk, node)
6238
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6239
      if msg:
6240
        lu.LogWarning("Could not remove block device %s on node %s,"
6241
                      " continuing anyway: %s", device.iv_name, node, msg)
6242
        all_result = False
6243

    
6244
  if instance.disk_template == constants.DT_FILE:
6245
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6246
    if target_node:
6247
      tgt = target_node
6248
    else:
6249
      tgt = instance.primary_node
6250
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6251
    if result.fail_msg:
6252
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6253
                    file_storage_dir, instance.primary_node, result.fail_msg)
6254
      all_result = False
6255

    
6256
  return all_result
6257

    
6258

    
6259
def _ComputeDiskSize(disk_template, disks):
6260
  """Compute disk size requirements in the volume group
6261

6262
  """
6263
  # Required free disk space as a function of disk and swap space
6264
  req_size_dict = {
6265
    constants.DT_DISKLESS: None,
6266
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6267
    # 128 MB are added for drbd metadata for each disk
6268
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6269
    constants.DT_FILE: None,
6270
  }
6271

    
6272
  if disk_template not in req_size_dict:
6273
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6274
                                 " is unknown" %  disk_template)
6275

    
6276
  return req_size_dict[disk_template]
6277

    
6278

    
6279
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6280
  """Hypervisor parameter validation.
6281

6282
  This function abstract the hypervisor parameter validation to be
6283
  used in both instance create and instance modify.
6284

6285
  @type lu: L{LogicalUnit}
6286
  @param lu: the logical unit for which we check
6287
  @type nodenames: list
6288
  @param nodenames: the list of nodes on which we should check
6289
  @type hvname: string
6290
  @param hvname: the name of the hypervisor we should use
6291
  @type hvparams: dict
6292
  @param hvparams: the parameters which we need to check
6293
  @raise errors.OpPrereqError: if the parameters are not valid
6294

6295
  """
6296
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6297
                                                  hvname,
6298
                                                  hvparams)
6299
  for node in nodenames:
6300
    info = hvinfo[node]
6301
    if info.offline:
6302
      continue
6303
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6304

    
6305

    
6306
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6307
  """OS parameters validation.
6308

6309
  @type lu: L{LogicalUnit}
6310
  @param lu: the logical unit for which we check
6311
  @type required: boolean
6312
  @param required: whether the validation should fail if the OS is not
6313
      found
6314
  @type nodenames: list
6315
  @param nodenames: the list of nodes on which we should check
6316
  @type osname: string
6317
  @param osname: the name of the hypervisor we should use
6318
  @type osparams: dict
6319
  @param osparams: the parameters which we need to check
6320
  @raise errors.OpPrereqError: if the parameters are not valid
6321

6322
  """
6323
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6324
                                   [constants.OS_VALIDATE_PARAMETERS],
6325
                                   osparams)
6326
  for node, nres in result.items():
6327
    # we don't check for offline cases since this should be run only
6328
    # against the master node and/or an instance's nodes
6329
    nres.Raise("OS Parameters validation failed on node %s" % node)
6330
    if not nres.payload:
6331
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6332
                 osname, node)
6333

    
6334

    
6335
class LUCreateInstance(LogicalUnit):
6336
  """Create an instance.
6337

6338
  """
6339
  HPATH = "instance-add"
6340
  HTYPE = constants.HTYPE_INSTANCE
6341
  _OP_PARAMS = [
6342
    _PInstanceName,
6343
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6344
    ("start", True, _TBool),
6345
    ("wait_for_sync", True, _TBool),
6346
    ("ip_check", True, _TBool),
6347
    ("name_check", True, _TBool),
6348
    ("disks", _NoDefault, _TListOf(_TDict)),
6349
    ("nics", _NoDefault, _TListOf(_TDict)),
6350
    ("hvparams", _EmptyDict, _TDict),
6351
    ("beparams", _EmptyDict, _TDict),
6352
    ("osparams", _EmptyDict, _TDict),
6353
    ("no_install", None, _TMaybeBool),
6354
    ("os_type", None, _TMaybeString),
6355
    ("force_variant", False, _TBool),
6356
    ("source_handshake", None, _TOr(_TList, _TNone)),
6357
    ("source_x509_ca", None, _TOr(_TList, _TNone)),
6358
    ("source_instance_name", None, _TMaybeString),
6359
    ("src_node", None, _TMaybeString),
6360
    ("src_path", None, _TMaybeString),
6361
    ("pnode", None, _TMaybeString),
6362
    ("snode", None, _TMaybeString),
6363
    ("iallocator", None, _TMaybeString),
6364
    ("hypervisor", None, _TMaybeString),
6365
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6366
    ("identify_defaults", False, _TBool),
6367
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6368
    ("file_storage_dir", None, _TMaybeString),
6369
    ("dry_run", False, _TBool),
6370
    ]
6371
  REQ_BGL = False
6372

    
6373
  def CheckArguments(self):
6374
    """Check arguments.
6375

6376
    """
6377
    # do not require name_check to ease forward/backward compatibility
6378
    # for tools
6379
    if self.op.no_install and self.op.start:
6380
      self.LogInfo("No-installation mode selected, disabling startup")
6381
      self.op.start = False
6382
    # validate/normalize the instance name
6383
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6384
    if self.op.ip_check and not self.op.name_check:
6385
      # TODO: make the ip check more flexible and not depend on the name check
6386
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6387
                                 errors.ECODE_INVAL)
6388

    
6389
    # check nics' parameter names
6390
    for nic in self.op.nics:
6391
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6392

    
6393
    # check disks. parameter names and consistent adopt/no-adopt strategy
6394
    has_adopt = has_no_adopt = False
6395
    for disk in self.op.disks:
6396
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6397
      if "adopt" in disk:
6398
        has_adopt = True
6399
      else:
6400
        has_no_adopt = True
6401
    if has_adopt and has_no_adopt:
6402
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6403
                                 errors.ECODE_INVAL)
6404
    if has_adopt:
6405
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6406
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6407
                                   " '%s' disk template" %
6408
                                   self.op.disk_template,
6409
                                   errors.ECODE_INVAL)
6410
      if self.op.iallocator is not None:
6411
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6412
                                   " iallocator script", errors.ECODE_INVAL)
6413
      if self.op.mode == constants.INSTANCE_IMPORT:
6414
        raise errors.OpPrereqError("Disk adoption not allowed for"
6415
                                   " instance import", errors.ECODE_INVAL)
6416

    
6417
    self.adopt_disks = has_adopt
6418

    
6419
    # instance name verification
6420
    if self.op.name_check:
6421
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6422
      self.op.instance_name = self.hostname1.name
6423
      # used in CheckPrereq for ip ping check
6424
      self.check_ip = self.hostname1.ip
6425
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6426
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6427
                                 errors.ECODE_INVAL)
6428
    else:
6429
      self.check_ip = None
6430

    
6431
    # file storage checks
6432
    if (self.op.file_driver and
6433
        not self.op.file_driver in constants.FILE_DRIVER):
6434
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6435
                                 self.op.file_driver, errors.ECODE_INVAL)
6436

    
6437
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6438
      raise errors.OpPrereqError("File storage directory path not absolute",
6439
                                 errors.ECODE_INVAL)
6440

    
6441
    ### Node/iallocator related checks
6442
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6443
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6444
                                 " node must be given",
6445
                                 errors.ECODE_INVAL)
6446

    
6447
    self._cds = _GetClusterDomainSecret()
6448

    
6449
    if self.op.mode == constants.INSTANCE_IMPORT:
6450
      # On import force_variant must be True, because if we forced it at
6451
      # initial install, our only chance when importing it back is that it
6452
      # works again!
6453
      self.op.force_variant = True
6454

    
6455
      if self.op.no_install:
6456
        self.LogInfo("No-installation mode has no effect during import")
6457

    
6458
    elif self.op.mode == constants.INSTANCE_CREATE:
6459
      if self.op.os_type is None:
6460
        raise errors.OpPrereqError("No guest OS specified",
6461
                                   errors.ECODE_INVAL)
6462
      if self.op.disk_template is None:
6463
        raise errors.OpPrereqError("No disk template specified",
6464
                                   errors.ECODE_INVAL)
6465

    
6466
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6467
      # Check handshake to ensure both clusters have the same domain secret
6468
      src_handshake = self.op.source_handshake
6469
      if not src_handshake:
6470
        raise errors.OpPrereqError("Missing source handshake",
6471
                                   errors.ECODE_INVAL)
6472

    
6473
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6474
                                                           src_handshake)
6475
      if errmsg:
6476
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6477
                                   errors.ECODE_INVAL)
6478

    
6479
      # Load and check source CA
6480
      self.source_x509_ca_pem = self.op.source_x509_ca
6481
      if not self.source_x509_ca_pem:
6482
        raise errors.OpPrereqError("Missing source X509 CA",
6483
                                   errors.ECODE_INVAL)
6484

    
6485
      try:
6486
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6487
                                                    self._cds)
6488
      except OpenSSL.crypto.Error, err:
6489
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6490
                                   (err, ), errors.ECODE_INVAL)
6491

    
6492
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6493
      if errcode is not None:
6494
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6495
                                   errors.ECODE_INVAL)
6496

    
6497
      self.source_x509_ca = cert
6498

    
6499
      src_instance_name = self.op.source_instance_name
6500
      if not src_instance_name:
6501
        raise errors.OpPrereqError("Missing source instance name",
6502
                                   errors.ECODE_INVAL)
6503

    
6504
      self.source_instance_name = \
6505
        utils.GetHostInfo(utils.HostInfo.NormalizeName(src_instance_name)).name
6506

    
6507
    else:
6508
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6509
                                 self.op.mode, errors.ECODE_INVAL)
6510

    
6511
  def ExpandNames(self):
6512
    """ExpandNames for CreateInstance.
6513

6514
    Figure out the right locks for instance creation.
6515

6516
    """
6517
    self.needed_locks = {}
6518

    
6519
    instance_name = self.op.instance_name
6520
    # this is just a preventive check, but someone might still add this
6521
    # instance in the meantime, and creation will fail at lock-add time
6522
    if instance_name in self.cfg.GetInstanceList():
6523
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6524
                                 instance_name, errors.ECODE_EXISTS)
6525

    
6526
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6527

    
6528
    if self.op.iallocator:
6529
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6530
    else:
6531
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6532
      nodelist = [self.op.pnode]
6533
      if self.op.snode is not None:
6534
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6535
        nodelist.append(self.op.snode)
6536
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6537

    
6538
    # in case of import lock the source node too
6539
    if self.op.mode == constants.INSTANCE_IMPORT:
6540
      src_node = self.op.src_node
6541
      src_path = self.op.src_path
6542

    
6543
      if src_path is None:
6544
        self.op.src_path = src_path = self.op.instance_name
6545

    
6546
      if src_node is None:
6547
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6548
        self.op.src_node = None
6549
        if os.path.isabs(src_path):
6550
          raise errors.OpPrereqError("Importing an instance from an absolute"
6551
                                     " path requires a source node option.",
6552
                                     errors.ECODE_INVAL)
6553
      else:
6554
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6555
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6556
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6557
        if not os.path.isabs(src_path):
6558
          self.op.src_path = src_path = \
6559
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6560

    
6561
  def _RunAllocator(self):
6562
    """Run the allocator based on input opcode.
6563

6564
    """
6565
    nics = [n.ToDict() for n in self.nics]
6566
    ial = IAllocator(self.cfg, self.rpc,
6567
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6568
                     name=self.op.instance_name,
6569
                     disk_template=self.op.disk_template,
6570
                     tags=[],
6571
                     os=self.op.os_type,
6572
                     vcpus=self.be_full[constants.BE_VCPUS],
6573
                     mem_size=self.be_full[constants.BE_MEMORY],
6574
                     disks=self.disks,
6575
                     nics=nics,
6576
                     hypervisor=self.op.hypervisor,
6577
                     )
6578

    
6579
    ial.Run(self.op.iallocator)
6580

    
6581
    if not ial.success:
6582
      raise errors.OpPrereqError("Can't compute nodes using"
6583
                                 " iallocator '%s': %s" %
6584
                                 (self.op.iallocator, ial.info),
6585
                                 errors.ECODE_NORES)
6586
    if len(ial.result) != ial.required_nodes:
6587
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6588
                                 " of nodes (%s), required %s" %
6589
                                 (self.op.iallocator, len(ial.result),
6590
                                  ial.required_nodes), errors.ECODE_FAULT)
6591
    self.op.pnode = ial.result[0]
6592
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6593
                 self.op.instance_name, self.op.iallocator,
6594
                 utils.CommaJoin(ial.result))
6595
    if ial.required_nodes == 2:
6596
      self.op.snode = ial.result[1]
6597

    
6598
  def BuildHooksEnv(self):
6599
    """Build hooks env.
6600

6601
    This runs on master, primary and secondary nodes of the instance.
6602

6603
    """
6604
    env = {
6605
      "ADD_MODE": self.op.mode,
6606
      }
6607
    if self.op.mode == constants.INSTANCE_IMPORT:
6608
      env["SRC_NODE"] = self.op.src_node
6609
      env["SRC_PATH"] = self.op.src_path
6610
      env["SRC_IMAGES"] = self.src_images
6611

    
6612
    env.update(_BuildInstanceHookEnv(
6613
      name=self.op.instance_name,
6614
      primary_node=self.op.pnode,
6615
      secondary_nodes=self.secondaries,
6616
      status=self.op.start,
6617
      os_type=self.op.os_type,
6618
      memory=self.be_full[constants.BE_MEMORY],
6619
      vcpus=self.be_full[constants.BE_VCPUS],
6620
      nics=_NICListToTuple(self, self.nics),
6621
      disk_template=self.op.disk_template,
6622
      disks=[(d["size"], d["mode"]) for d in self.disks],
6623
      bep=self.be_full,
6624
      hvp=self.hv_full,
6625
      hypervisor_name=self.op.hypervisor,
6626
    ))
6627

    
6628
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6629
          self.secondaries)
6630
    return env, nl, nl
6631

    
6632
  def _ReadExportInfo(self):
6633
    """Reads the export information from disk.
6634

6635
    It will override the opcode source node and path with the actual
6636
    information, if these two were not specified before.
6637

6638
    @return: the export information
6639

6640
    """
6641
    assert self.op.mode == constants.INSTANCE_IMPORT
6642

    
6643
    src_node = self.op.src_node
6644
    src_path = self.op.src_path
6645

    
6646
    if src_node is None:
6647
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6648
      exp_list = self.rpc.call_export_list(locked_nodes)
6649
      found = False
6650
      for node in exp_list:
6651
        if exp_list[node].fail_msg:
6652
          continue
6653
        if src_path in exp_list[node].payload:
6654
          found = True
6655
          self.op.src_node = src_node = node
6656
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6657
                                                       src_path)
6658
          break
6659
      if not found:
6660
        raise errors.OpPrereqError("No export found for relative path %s" %
6661
                                    src_path, errors.ECODE_INVAL)
6662

    
6663
    _CheckNodeOnline(self, src_node)
6664
    result = self.rpc.call_export_info(src_node, src_path)
6665
    result.Raise("No export or invalid export found in dir %s" % src_path)
6666

    
6667
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6668
    if not export_info.has_section(constants.INISECT_EXP):
6669
      raise errors.ProgrammerError("Corrupted export config",
6670
                                   errors.ECODE_ENVIRON)
6671

    
6672
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6673
    if (int(ei_version) != constants.EXPORT_VERSION):
6674
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6675
                                 (ei_version, constants.EXPORT_VERSION),
6676
                                 errors.ECODE_ENVIRON)
6677
    return export_info
6678

    
6679
  def _ReadExportParams(self, einfo):
6680
    """Use export parameters as defaults.
6681

6682
    In case the opcode doesn't specify (as in override) some instance
6683
    parameters, then try to use them from the export information, if
6684
    that declares them.
6685

6686
    """
6687
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6688

    
6689
    if self.op.disk_template is None:
6690
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6691
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6692
                                          "disk_template")
6693
      else:
6694
        raise errors.OpPrereqError("No disk template specified and the export"
6695
                                   " is missing the disk_template information",
6696
                                   errors.ECODE_INVAL)
6697

    
6698
    if not self.op.disks:
6699
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6700
        disks = []
6701
        # TODO: import the disk iv_name too
6702
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6703
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6704
          disks.append({"size": disk_sz})
6705
        self.op.disks = disks
6706
      else:
6707
        raise errors.OpPrereqError("No disk info specified and the export"
6708
                                   " is missing the disk information",
6709
                                   errors.ECODE_INVAL)
6710

    
6711
    if (not self.op.nics and
6712
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6713
      nics = []
6714
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6715
        ndict = {}
6716
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6717
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6718
          ndict[name] = v
6719
        nics.append(ndict)
6720
      self.op.nics = nics
6721

    
6722
    if (self.op.hypervisor is None and
6723
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6724
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6725
    if einfo.has_section(constants.INISECT_HYP):
6726
      # use the export parameters but do not override the ones
6727
      # specified by the user
6728
      for name, value in einfo.items(constants.INISECT_HYP):
6729
        if name not in self.op.hvparams:
6730
          self.op.hvparams[name] = value
6731

    
6732
    if einfo.has_section(constants.INISECT_BEP):
6733
      # use the parameters, without overriding
6734
      for name, value in einfo.items(constants.INISECT_BEP):
6735
        if name not in self.op.beparams:
6736
          self.op.beparams[name] = value
6737
    else:
6738
      # try to read the parameters old style, from the main section
6739
      for name in constants.BES_PARAMETERS:
6740
        if (name not in self.op.beparams and
6741
            einfo.has_option(constants.INISECT_INS, name)):
6742
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6743

    
6744
    if einfo.has_section(constants.INISECT_OSP):
6745
      # use the parameters, without overriding
6746
      for name, value in einfo.items(constants.INISECT_OSP):
6747
        if name not in self.op.osparams:
6748
          self.op.osparams[name] = value
6749

    
6750
  def _RevertToDefaults(self, cluster):
6751
    """Revert the instance parameters to the default values.
6752

6753
    """
6754
    # hvparams
6755
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6756
    for name in self.op.hvparams.keys():
6757
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6758
        del self.op.hvparams[name]
6759
    # beparams
6760
    be_defs = cluster.SimpleFillBE({})
6761
    for name in self.op.beparams.keys():
6762
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6763
        del self.op.beparams[name]
6764
    # nic params
6765
    nic_defs = cluster.SimpleFillNIC({})
6766
    for nic in self.op.nics:
6767
      for name in constants.NICS_PARAMETERS:
6768
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6769
          del nic[name]
6770
    # osparams
6771
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6772
    for name in self.op.osparams.keys():
6773
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6774
        del self.op.osparams[name]
6775

    
6776
  def CheckPrereq(self):
6777
    """Check prerequisites.
6778

6779
    """
6780
    if self.op.mode == constants.INSTANCE_IMPORT:
6781
      export_info = self._ReadExportInfo()
6782
      self._ReadExportParams(export_info)
6783

    
6784
    _CheckDiskTemplate(self.op.disk_template)
6785

    
6786
    if (not self.cfg.GetVGName() and
6787
        self.op.disk_template not in constants.DTS_NOT_LVM):
6788
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6789
                                 " instances", errors.ECODE_STATE)
6790

    
6791
    if self.op.hypervisor is None:
6792
      self.op.hypervisor = self.cfg.GetHypervisorType()
6793

    
6794
    cluster = self.cfg.GetClusterInfo()
6795
    enabled_hvs = cluster.enabled_hypervisors
6796
    if self.op.hypervisor not in enabled_hvs:
6797
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6798
                                 " cluster (%s)" % (self.op.hypervisor,
6799
                                  ",".join(enabled_hvs)),
6800
                                 errors.ECODE_STATE)
6801

    
6802
    # check hypervisor parameter syntax (locally)
6803
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6804
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6805
                                      self.op.hvparams)
6806
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6807
    hv_type.CheckParameterSyntax(filled_hvp)
6808
    self.hv_full = filled_hvp
6809
    # check that we don't specify global parameters on an instance
6810
    _CheckGlobalHvParams(self.op.hvparams)
6811

    
6812
    # fill and remember the beparams dict
6813
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6814
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6815

    
6816
    # build os parameters
6817
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6818

    
6819
    # now that hvp/bep are in final format, let's reset to defaults,
6820
    # if told to do so
6821
    if self.op.identify_defaults:
6822
      self._RevertToDefaults(cluster)
6823

    
6824
    # NIC buildup
6825
    self.nics = []
6826
    for idx, nic in enumerate(self.op.nics):
6827
      nic_mode_req = nic.get("mode", None)
6828
      nic_mode = nic_mode_req
6829
      if nic_mode is None:
6830
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6831

    
6832
      # in routed mode, for the first nic, the default ip is 'auto'
6833
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6834
        default_ip_mode = constants.VALUE_AUTO
6835
      else:
6836
        default_ip_mode = constants.VALUE_NONE
6837

    
6838
      # ip validity checks
6839
      ip = nic.get("ip", default_ip_mode)
6840
      if ip is None or ip.lower() == constants.VALUE_NONE:
6841
        nic_ip = None
6842
      elif ip.lower() == constants.VALUE_AUTO:
6843
        if not self.op.name_check:
6844
          raise errors.OpPrereqError("IP address set to auto but name checks"
6845
                                     " have been skipped. Aborting.",
6846
                                     errors.ECODE_INVAL)
6847
        nic_ip = self.hostname1.ip
6848
      else:
6849
        if not utils.IsValidIP4(ip):
6850
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6851
                                     " like a valid IP" % ip,
6852
                                     errors.ECODE_INVAL)
6853
        nic_ip = ip
6854

    
6855
      # TODO: check the ip address for uniqueness
6856
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6857
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6858
                                   errors.ECODE_INVAL)
6859

    
6860
      # MAC address verification
6861
      mac = nic.get("mac", constants.VALUE_AUTO)
6862
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6863
        mac = utils.NormalizeAndValidateMac(mac)
6864

    
6865
        try:
6866
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6867
        except errors.ReservationError:
6868
          raise errors.OpPrereqError("MAC address %s already in use"
6869
                                     " in cluster" % mac,
6870
                                     errors.ECODE_NOTUNIQUE)
6871

    
6872
      # bridge verification
6873
      bridge = nic.get("bridge", None)
6874
      link = nic.get("link", None)
6875
      if bridge and link:
6876
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6877
                                   " at the same time", errors.ECODE_INVAL)
6878
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6879
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6880
                                   errors.ECODE_INVAL)
6881
      elif bridge:
6882
        link = bridge
6883

    
6884
      nicparams = {}
6885
      if nic_mode_req:
6886
        nicparams[constants.NIC_MODE] = nic_mode_req
6887
      if link:
6888
        nicparams[constants.NIC_LINK] = link
6889

    
6890
      check_params = cluster.SimpleFillNIC(nicparams)
6891
      objects.NIC.CheckParameterSyntax(check_params)
6892
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6893

    
6894
    # disk checks/pre-build
6895
    self.disks = []
6896
    for disk in self.op.disks:
6897
      mode = disk.get("mode", constants.DISK_RDWR)
6898
      if mode not in constants.DISK_ACCESS_SET:
6899
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6900
                                   mode, errors.ECODE_INVAL)
6901
      size = disk.get("size", None)
6902
      if size is None:
6903
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6904
      try:
6905
        size = int(size)
6906
      except (TypeError, ValueError):
6907
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6908
                                   errors.ECODE_INVAL)
6909
      new_disk = {"size": size, "mode": mode}
6910
      if "adopt" in disk:
6911
        new_disk["adopt"] = disk["adopt"]
6912
      self.disks.append(new_disk)
6913

    
6914
    if self.op.mode == constants.INSTANCE_IMPORT:
6915

    
6916
      # Check that the new instance doesn't have less disks than the export
6917
      instance_disks = len(self.disks)
6918
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6919
      if instance_disks < export_disks:
6920
        raise errors.OpPrereqError("Not enough disks to import."
6921
                                   " (instance: %d, export: %d)" %
6922
                                   (instance_disks, export_disks),
6923
                                   errors.ECODE_INVAL)
6924

    
6925
      disk_images = []
6926
      for idx in range(export_disks):
6927
        option = 'disk%d_dump' % idx
6928
        if export_info.has_option(constants.INISECT_INS, option):
6929
          # FIXME: are the old os-es, disk sizes, etc. useful?
6930
          export_name = export_info.get(constants.INISECT_INS, option)
6931
          image = utils.PathJoin(self.op.src_path, export_name)
6932
          disk_images.append(image)
6933
        else:
6934
          disk_images.append(False)
6935

    
6936
      self.src_images = disk_images
6937

    
6938
      old_name = export_info.get(constants.INISECT_INS, 'name')
6939
      try:
6940
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6941
      except (TypeError, ValueError), err:
6942
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6943
                                   " an integer: %s" % str(err),
6944
                                   errors.ECODE_STATE)
6945
      if self.op.instance_name == old_name:
6946
        for idx, nic in enumerate(self.nics):
6947
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6948
            nic_mac_ini = 'nic%d_mac' % idx
6949
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6950

    
6951
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6952

    
6953
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6954
    if self.op.ip_check:
6955
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6956
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6957
                                   (self.check_ip, self.op.instance_name),
6958
                                   errors.ECODE_NOTUNIQUE)
6959

    
6960
    #### mac address generation
6961
    # By generating here the mac address both the allocator and the hooks get
6962
    # the real final mac address rather than the 'auto' or 'generate' value.
6963
    # There is a race condition between the generation and the instance object
6964
    # creation, which means that we know the mac is valid now, but we're not
6965
    # sure it will be when we actually add the instance. If things go bad
6966
    # adding the instance will abort because of a duplicate mac, and the
6967
    # creation job will fail.
6968
    for nic in self.nics:
6969
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6970
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
6971

    
6972
    #### allocator run
6973

    
6974
    if self.op.iallocator is not None:
6975
      self._RunAllocator()
6976

    
6977
    #### node related checks
6978

    
6979
    # check primary node
6980
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
6981
    assert self.pnode is not None, \
6982
      "Cannot retrieve locked node %s" % self.op.pnode
6983
    if pnode.offline:
6984
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
6985
                                 pnode.name, errors.ECODE_STATE)
6986
    if pnode.drained:
6987
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
6988
                                 pnode.name, errors.ECODE_STATE)
6989

    
6990
    self.secondaries = []
6991

    
6992
    # mirror node verification
6993
    if self.op.disk_template in constants.DTS_NET_MIRROR:
6994
      if self.op.snode is None:
6995
        raise errors.OpPrereqError("The networked disk templates need"
6996
                                   " a mirror node", errors.ECODE_INVAL)
6997
      if self.op.snode == pnode.name:
6998
        raise errors.OpPrereqError("The secondary node cannot be the"
6999
                                   " primary node.", errors.ECODE_INVAL)
7000
      _CheckNodeOnline(self, self.op.snode)
7001
      _CheckNodeNotDrained(self, self.op.snode)
7002
      self.secondaries.append(self.op.snode)
7003

    
7004
    nodenames = [pnode.name] + self.secondaries
7005

    
7006
    req_size = _ComputeDiskSize(self.op.disk_template,
7007
                                self.disks)
7008

    
7009
    # Check lv size requirements, if not adopting
7010
    if req_size is not None and not self.adopt_disks:
7011
      _CheckNodesFreeDisk(self, nodenames, req_size)
7012

    
7013
    if self.adopt_disks: # instead, we must check the adoption data
7014
      all_lvs = set([i["adopt"] for i in self.disks])
7015
      if len(all_lvs) != len(self.disks):
7016
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7017
                                   errors.ECODE_INVAL)
7018
      for lv_name in all_lvs:
7019
        try:
7020
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7021
        except errors.ReservationError:
7022
          raise errors.OpPrereqError("LV named %s used by another instance" %
7023
                                     lv_name, errors.ECODE_NOTUNIQUE)
7024

    
7025
      node_lvs = self.rpc.call_lv_list([pnode.name],
7026
                                       self.cfg.GetVGName())[pnode.name]
7027
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7028
      node_lvs = node_lvs.payload
7029
      delta = all_lvs.difference(node_lvs.keys())
7030
      if delta:
7031
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7032
                                   utils.CommaJoin(delta),
7033
                                   errors.ECODE_INVAL)
7034
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7035
      if online_lvs:
7036
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7037
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7038
                                   errors.ECODE_STATE)
7039
      # update the size of disk based on what is found
7040
      for dsk in self.disks:
7041
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7042

    
7043
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7044

    
7045
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7046
    # check OS parameters (remotely)
7047
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7048

    
7049
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7050

    
7051
    # memory check on primary node
7052
    if self.op.start:
7053
      _CheckNodeFreeMemory(self, self.pnode.name,
7054
                           "creating instance %s" % self.op.instance_name,
7055
                           self.be_full[constants.BE_MEMORY],
7056
                           self.op.hypervisor)
7057

    
7058
    self.dry_run_result = list(nodenames)
7059

    
7060
  def Exec(self, feedback_fn):
7061
    """Create and add the instance to the cluster.
7062

7063
    """
7064
    instance = self.op.instance_name
7065
    pnode_name = self.pnode.name
7066

    
7067
    ht_kind = self.op.hypervisor
7068
    if ht_kind in constants.HTS_REQ_PORT:
7069
      network_port = self.cfg.AllocatePort()
7070
    else:
7071
      network_port = None
7072

    
7073
    if constants.ENABLE_FILE_STORAGE:
7074
      # this is needed because os.path.join does not accept None arguments
7075
      if self.op.file_storage_dir is None:
7076
        string_file_storage_dir = ""
7077
      else:
7078
        string_file_storage_dir = self.op.file_storage_dir
7079

    
7080
      # build the full file storage dir path
7081
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7082
                                        string_file_storage_dir, instance)
7083
    else:
7084
      file_storage_dir = ""
7085

    
7086
    disks = _GenerateDiskTemplate(self,
7087
                                  self.op.disk_template,
7088
                                  instance, pnode_name,
7089
                                  self.secondaries,
7090
                                  self.disks,
7091
                                  file_storage_dir,
7092
                                  self.op.file_driver,
7093
                                  0)
7094

    
7095
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7096
                            primary_node=pnode_name,
7097
                            nics=self.nics, disks=disks,
7098
                            disk_template=self.op.disk_template,
7099
                            admin_up=False,
7100
                            network_port=network_port,
7101
                            beparams=self.op.beparams,
7102
                            hvparams=self.op.hvparams,
7103
                            hypervisor=self.op.hypervisor,
7104
                            osparams=self.op.osparams,
7105
                            )
7106

    
7107
    if self.adopt_disks:
7108
      # rename LVs to the newly-generated names; we need to construct
7109
      # 'fake' LV disks with the old data, plus the new unique_id
7110
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7111
      rename_to = []
7112
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7113
        rename_to.append(t_dsk.logical_id)
7114
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7115
        self.cfg.SetDiskID(t_dsk, pnode_name)
7116
      result = self.rpc.call_blockdev_rename(pnode_name,
7117
                                             zip(tmp_disks, rename_to))
7118
      result.Raise("Failed to rename adoped LVs")
7119
    else:
7120
      feedback_fn("* creating instance disks...")
7121
      try:
7122
        _CreateDisks(self, iobj)
7123
      except errors.OpExecError:
7124
        self.LogWarning("Device creation failed, reverting...")
7125
        try:
7126
          _RemoveDisks(self, iobj)
7127
        finally:
7128
          self.cfg.ReleaseDRBDMinors(instance)
7129
          raise
7130

    
7131
    feedback_fn("adding instance %s to cluster config" % instance)
7132

    
7133
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7134

    
7135
    # Declare that we don't want to remove the instance lock anymore, as we've
7136
    # added the instance to the config
7137
    del self.remove_locks[locking.LEVEL_INSTANCE]
7138
    # Unlock all the nodes
7139
    if self.op.mode == constants.INSTANCE_IMPORT:
7140
      nodes_keep = [self.op.src_node]
7141
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7142
                       if node != self.op.src_node]
7143
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7144
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7145
    else:
7146
      self.context.glm.release(locking.LEVEL_NODE)
7147
      del self.acquired_locks[locking.LEVEL_NODE]
7148

    
7149
    if self.op.wait_for_sync:
7150
      disk_abort = not _WaitForSync(self, iobj)
7151
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7152
      # make sure the disks are not degraded (still sync-ing is ok)
7153
      time.sleep(15)
7154
      feedback_fn("* checking mirrors status")
7155
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7156
    else:
7157
      disk_abort = False
7158

    
7159
    if disk_abort:
7160
      _RemoveDisks(self, iobj)
7161
      self.cfg.RemoveInstance(iobj.name)
7162
      # Make sure the instance lock gets removed
7163
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7164
      raise errors.OpExecError("There are some degraded disks for"
7165
                               " this instance")
7166

    
7167
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7168
      if self.op.mode == constants.INSTANCE_CREATE:
7169
        if not self.op.no_install:
7170
          feedback_fn("* running the instance OS create scripts...")
7171
          # FIXME: pass debug option from opcode to backend
7172
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7173
                                                 self.op.debug_level)
7174
          result.Raise("Could not add os for instance %s"
7175
                       " on node %s" % (instance, pnode_name))
7176

    
7177
      elif self.op.mode == constants.INSTANCE_IMPORT:
7178
        feedback_fn("* running the instance OS import scripts...")
7179

    
7180
        transfers = []
7181

    
7182
        for idx, image in enumerate(self.src_images):
7183
          if not image:
7184
            continue
7185

    
7186
          # FIXME: pass debug option from opcode to backend
7187
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7188
                                             constants.IEIO_FILE, (image, ),
7189
                                             constants.IEIO_SCRIPT,
7190
                                             (iobj.disks[idx], idx),
7191
                                             None)
7192
          transfers.append(dt)
7193

    
7194
        import_result = \
7195
          masterd.instance.TransferInstanceData(self, feedback_fn,
7196
                                                self.op.src_node, pnode_name,
7197
                                                self.pnode.secondary_ip,
7198
                                                iobj, transfers)
7199
        if not compat.all(import_result):
7200
          self.LogWarning("Some disks for instance %s on node %s were not"
7201
                          " imported successfully" % (instance, pnode_name))
7202

    
7203
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7204
        feedback_fn("* preparing remote import...")
7205
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7206
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7207

    
7208
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7209
                                                     self.source_x509_ca,
7210
                                                     self._cds, timeouts)
7211
        if not compat.all(disk_results):
7212
          # TODO: Should the instance still be started, even if some disks
7213
          # failed to import (valid for local imports, too)?
7214
          self.LogWarning("Some disks for instance %s on node %s were not"
7215
                          " imported successfully" % (instance, pnode_name))
7216

    
7217
        # Run rename script on newly imported instance
7218
        assert iobj.name == instance
7219
        feedback_fn("Running rename script for %s" % instance)
7220
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7221
                                                   self.source_instance_name,
7222
                                                   self.op.debug_level)
7223
        if result.fail_msg:
7224
          self.LogWarning("Failed to run rename script for %s on node"
7225
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7226

    
7227
      else:
7228
        # also checked in the prereq part
7229
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7230
                                     % self.op.mode)
7231

    
7232
    if self.op.start:
7233
      iobj.admin_up = True
7234
      self.cfg.Update(iobj, feedback_fn)
7235
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7236
      feedback_fn("* starting instance...")
7237
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7238
      result.Raise("Could not start instance")
7239

    
7240
    return list(iobj.all_nodes)
7241

    
7242

    
7243
class LUConnectConsole(NoHooksLU):
7244
  """Connect to an instance's console.
7245

7246
  This is somewhat special in that it returns the command line that
7247
  you need to run on the master node in order to connect to the
7248
  console.
7249

7250
  """
7251
  _OP_PARAMS = [
7252
    _PInstanceName
7253
    ]
7254
  REQ_BGL = False
7255

    
7256
  def ExpandNames(self):
7257
    self._ExpandAndLockInstance()
7258

    
7259
  def CheckPrereq(self):
7260
    """Check prerequisites.
7261

7262
    This checks that the instance is in the cluster.
7263

7264
    """
7265
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7266
    assert self.instance is not None, \
7267
      "Cannot retrieve locked instance %s" % self.op.instance_name
7268
    _CheckNodeOnline(self, self.instance.primary_node)
7269

    
7270
  def Exec(self, feedback_fn):
7271
    """Connect to the console of an instance
7272

7273
    """
7274
    instance = self.instance
7275
    node = instance.primary_node
7276

    
7277
    node_insts = self.rpc.call_instance_list([node],
7278
                                             [instance.hypervisor])[node]
7279
    node_insts.Raise("Can't get node information from %s" % node)
7280

    
7281
    if instance.name not in node_insts.payload:
7282
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7283

    
7284
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7285

    
7286
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7287
    cluster = self.cfg.GetClusterInfo()
7288
    # beparams and hvparams are passed separately, to avoid editing the
7289
    # instance and then saving the defaults in the instance itself.
7290
    hvparams = cluster.FillHV(instance)
7291
    beparams = cluster.FillBE(instance)
7292
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7293

    
7294
    # build ssh cmdline
7295
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7296

    
7297

    
7298
class LUReplaceDisks(LogicalUnit):
7299
  """Replace the disks of an instance.
7300

7301
  """
7302
  HPATH = "mirrors-replace"
7303
  HTYPE = constants.HTYPE_INSTANCE
7304
  _OP_PARAMS = [
7305
    _PInstanceName,
7306
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7307
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7308
    ("remote_node", None, _TMaybeString),
7309
    ("iallocator", None, _TMaybeString),
7310
    ("early_release", False, _TBool),
7311
    ]
7312
  REQ_BGL = False
7313

    
7314
  def CheckArguments(self):
7315
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7316
                                  self.op.iallocator)
7317

    
7318
  def ExpandNames(self):
7319
    self._ExpandAndLockInstance()
7320

    
7321
    if self.op.iallocator is not None:
7322
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7323

    
7324
    elif self.op.remote_node is not None:
7325
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7326
      self.op.remote_node = remote_node
7327

    
7328
      # Warning: do not remove the locking of the new secondary here
7329
      # unless DRBD8.AddChildren is changed to work in parallel;
7330
      # currently it doesn't since parallel invocations of
7331
      # FindUnusedMinor will conflict
7332
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7333
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7334

    
7335
    else:
7336
      self.needed_locks[locking.LEVEL_NODE] = []
7337
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7338

    
7339
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7340
                                   self.op.iallocator, self.op.remote_node,
7341
                                   self.op.disks, False, self.op.early_release)
7342

    
7343
    self.tasklets = [self.replacer]
7344

    
7345
  def DeclareLocks(self, level):
7346
    # If we're not already locking all nodes in the set we have to declare the
7347
    # instance's primary/secondary nodes.
7348
    if (level == locking.LEVEL_NODE and
7349
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7350
      self._LockInstancesNodes()
7351

    
7352
  def BuildHooksEnv(self):
7353
    """Build hooks env.
7354

7355
    This runs on the master, the primary and all the secondaries.
7356

7357
    """
7358
    instance = self.replacer.instance
7359
    env = {
7360
      "MODE": self.op.mode,
7361
      "NEW_SECONDARY": self.op.remote_node,
7362
      "OLD_SECONDARY": instance.secondary_nodes[0],
7363
      }
7364
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7365
    nl = [
7366
      self.cfg.GetMasterNode(),
7367
      instance.primary_node,
7368
      ]
7369
    if self.op.remote_node is not None:
7370
      nl.append(self.op.remote_node)
7371
    return env, nl, nl
7372

    
7373

    
7374
class TLReplaceDisks(Tasklet):
7375
  """Replaces disks for an instance.
7376

7377
  Note: Locking is not within the scope of this class.
7378

7379
  """
7380
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7381
               disks, delay_iallocator, early_release):
7382
    """Initializes this class.
7383

7384
    """
7385
    Tasklet.__init__(self, lu)
7386

    
7387
    # Parameters
7388
    self.instance_name = instance_name
7389
    self.mode = mode
7390
    self.iallocator_name = iallocator_name
7391
    self.remote_node = remote_node
7392
    self.disks = disks
7393
    self.delay_iallocator = delay_iallocator
7394
    self.early_release = early_release
7395

    
7396
    # Runtime data
7397
    self.instance = None
7398
    self.new_node = None
7399
    self.target_node = None
7400
    self.other_node = None
7401
    self.remote_node_info = None
7402
    self.node_secondary_ip = None
7403

    
7404
  @staticmethod
7405
  def CheckArguments(mode, remote_node, iallocator):
7406
    """Helper function for users of this class.
7407

7408
    """
7409
    # check for valid parameter combination
7410
    if mode == constants.REPLACE_DISK_CHG:
7411
      if remote_node is None and iallocator is None:
7412
        raise errors.OpPrereqError("When changing the secondary either an"
7413
                                   " iallocator script must be used or the"
7414
                                   " new node given", errors.ECODE_INVAL)
7415

    
7416
      if remote_node is not None and iallocator is not None:
7417
        raise errors.OpPrereqError("Give either the iallocator or the new"
7418
                                   " secondary, not both", errors.ECODE_INVAL)
7419

    
7420
    elif remote_node is not None or iallocator is not None:
7421
      # Not replacing the secondary
7422
      raise errors.OpPrereqError("The iallocator and new node options can"
7423
                                 " only be used when changing the"
7424
                                 " secondary node", errors.ECODE_INVAL)
7425

    
7426
  @staticmethod
7427
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7428
    """Compute a new secondary node using an IAllocator.
7429

7430
    """
7431
    ial = IAllocator(lu.cfg, lu.rpc,
7432
                     mode=constants.IALLOCATOR_MODE_RELOC,
7433
                     name=instance_name,
7434
                     relocate_from=relocate_from)
7435

    
7436
    ial.Run(iallocator_name)
7437

    
7438
    if not ial.success:
7439
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7440
                                 " %s" % (iallocator_name, ial.info),
7441
                                 errors.ECODE_NORES)
7442

    
7443
    if len(ial.result) != ial.required_nodes:
7444
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7445
                                 " of nodes (%s), required %s" %
7446
                                 (iallocator_name,
7447
                                  len(ial.result), ial.required_nodes),
7448
                                 errors.ECODE_FAULT)
7449

    
7450
    remote_node_name = ial.result[0]
7451

    
7452
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7453
               instance_name, remote_node_name)
7454

    
7455
    return remote_node_name
7456

    
7457
  def _FindFaultyDisks(self, node_name):
7458
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7459
                                    node_name, True)
7460

    
7461
  def CheckPrereq(self):
7462
    """Check prerequisites.
7463

7464
    This checks that the instance is in the cluster.
7465

7466
    """
7467
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7468
    assert instance is not None, \
7469
      "Cannot retrieve locked instance %s" % self.instance_name
7470

    
7471
    if instance.disk_template != constants.DT_DRBD8:
7472
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7473
                                 " instances", errors.ECODE_INVAL)
7474

    
7475
    if len(instance.secondary_nodes) != 1:
7476
      raise errors.OpPrereqError("The instance has a strange layout,"
7477
                                 " expected one secondary but found %d" %
7478
                                 len(instance.secondary_nodes),
7479
                                 errors.ECODE_FAULT)
7480

    
7481
    if not self.delay_iallocator:
7482
      self._CheckPrereq2()
7483

    
7484
  def _CheckPrereq2(self):
7485
    """Check prerequisites, second part.
7486

7487
    This function should always be part of CheckPrereq. It was separated and is
7488
    now called from Exec because during node evacuation iallocator was only
7489
    called with an unmodified cluster model, not taking planned changes into
7490
    account.
7491

7492
    """
7493
    instance = self.instance
7494
    secondary_node = instance.secondary_nodes[0]
7495

    
7496
    if self.iallocator_name is None:
7497
      remote_node = self.remote_node
7498
    else:
7499
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7500
                                       instance.name, instance.secondary_nodes)
7501

    
7502
    if remote_node is not None:
7503
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7504
      assert self.remote_node_info is not None, \
7505
        "Cannot retrieve locked node %s" % remote_node
7506
    else:
7507
      self.remote_node_info = None
7508

    
7509
    if remote_node == self.instance.primary_node:
7510
      raise errors.OpPrereqError("The specified node is the primary node of"
7511
                                 " the instance.", errors.ECODE_INVAL)
7512

    
7513
    if remote_node == secondary_node:
7514
      raise errors.OpPrereqError("The specified node is already the"
7515
                                 " secondary node of the instance.",
7516
                                 errors.ECODE_INVAL)
7517

    
7518
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7519
                                    constants.REPLACE_DISK_CHG):
7520
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7521
                                 errors.ECODE_INVAL)
7522

    
7523
    if self.mode == constants.REPLACE_DISK_AUTO:
7524
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7525
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7526

    
7527
      if faulty_primary and faulty_secondary:
7528
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7529
                                   " one node and can not be repaired"
7530
                                   " automatically" % self.instance_name,
7531
                                   errors.ECODE_STATE)
7532

    
7533
      if faulty_primary:
7534
        self.disks = faulty_primary
7535
        self.target_node = instance.primary_node
7536
        self.other_node = secondary_node
7537
        check_nodes = [self.target_node, self.other_node]
7538
      elif faulty_secondary:
7539
        self.disks = faulty_secondary
7540
        self.target_node = secondary_node
7541
        self.other_node = instance.primary_node
7542
        check_nodes = [self.target_node, self.other_node]
7543
      else:
7544
        self.disks = []
7545
        check_nodes = []
7546

    
7547
    else:
7548
      # Non-automatic modes
7549
      if self.mode == constants.REPLACE_DISK_PRI:
7550
        self.target_node = instance.primary_node
7551
        self.other_node = secondary_node
7552
        check_nodes = [self.target_node, self.other_node]
7553

    
7554
      elif self.mode == constants.REPLACE_DISK_SEC:
7555
        self.target_node = secondary_node
7556
        self.other_node = instance.primary_node
7557
        check_nodes = [self.target_node, self.other_node]
7558

    
7559
      elif self.mode == constants.REPLACE_DISK_CHG:
7560
        self.new_node = remote_node
7561
        self.other_node = instance.primary_node
7562
        self.target_node = secondary_node
7563
        check_nodes = [self.new_node, self.other_node]
7564

    
7565
        _CheckNodeNotDrained(self.lu, remote_node)
7566

    
7567
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7568
        assert old_node_info is not None
7569
        if old_node_info.offline and not self.early_release:
7570
          # doesn't make sense to delay the release
7571
          self.early_release = True
7572
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7573
                          " early-release mode", secondary_node)
7574

    
7575
      else:
7576
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7577
                                     self.mode)
7578

    
7579
      # If not specified all disks should be replaced
7580
      if not self.disks:
7581
        self.disks = range(len(self.instance.disks))
7582

    
7583
    for node in check_nodes:
7584
      _CheckNodeOnline(self.lu, node)
7585

    
7586
    # Check whether disks are valid
7587
    for disk_idx in self.disks:
7588
      instance.FindDisk(disk_idx)
7589

    
7590
    # Get secondary node IP addresses
7591
    node_2nd_ip = {}
7592

    
7593
    for node_name in [self.target_node, self.other_node, self.new_node]:
7594
      if node_name is not None:
7595
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7596

    
7597
    self.node_secondary_ip = node_2nd_ip
7598

    
7599
  def Exec(self, feedback_fn):
7600
    """Execute disk replacement.
7601

7602
    This dispatches the disk replacement to the appropriate handler.
7603

7604
    """
7605
    if self.delay_iallocator:
7606
      self._CheckPrereq2()
7607

    
7608
    if not self.disks:
7609
      feedback_fn("No disks need replacement")
7610
      return
7611

    
7612
    feedback_fn("Replacing disk(s) %s for %s" %
7613
                (utils.CommaJoin(self.disks), self.instance.name))
7614

    
7615
    activate_disks = (not self.instance.admin_up)
7616

    
7617
    # Activate the instance disks if we're replacing them on a down instance
7618
    if activate_disks:
7619
      _StartInstanceDisks(self.lu, self.instance, True)
7620

    
7621
    try:
7622
      # Should we replace the secondary node?
7623
      if self.new_node is not None:
7624
        fn = self._ExecDrbd8Secondary
7625
      else:
7626
        fn = self._ExecDrbd8DiskOnly
7627

    
7628
      return fn(feedback_fn)
7629

    
7630
    finally:
7631
      # Deactivate the instance disks if we're replacing them on a
7632
      # down instance
7633
      if activate_disks:
7634
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7635

    
7636
  def _CheckVolumeGroup(self, nodes):
7637
    self.lu.LogInfo("Checking volume groups")
7638

    
7639
    vgname = self.cfg.GetVGName()
7640

    
7641
    # Make sure volume group exists on all involved nodes
7642
    results = self.rpc.call_vg_list(nodes)
7643
    if not results:
7644
      raise errors.OpExecError("Can't list volume groups on the nodes")
7645

    
7646
    for node in nodes:
7647
      res = results[node]
7648
      res.Raise("Error checking node %s" % node)
7649
      if vgname not in res.payload:
7650
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7651
                                 (vgname, node))
7652

    
7653
  def _CheckDisksExistence(self, nodes):
7654
    # Check disk existence
7655
    for idx, dev in enumerate(self.instance.disks):
7656
      if idx not in self.disks:
7657
        continue
7658

    
7659
      for node in nodes:
7660
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7661
        self.cfg.SetDiskID(dev, node)
7662

    
7663
        result = self.rpc.call_blockdev_find(node, dev)
7664

    
7665
        msg = result.fail_msg
7666
        if msg or not result.payload:
7667
          if not msg:
7668
            msg = "disk not found"
7669
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7670
                                   (idx, node, msg))
7671

    
7672
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7673
    for idx, dev in enumerate(self.instance.disks):
7674
      if idx not in self.disks:
7675
        continue
7676

    
7677
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7678
                      (idx, node_name))
7679

    
7680
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7681
                                   ldisk=ldisk):
7682
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7683
                                 " replace disks for instance %s" %
7684
                                 (node_name, self.instance.name))
7685

    
7686
  def _CreateNewStorage(self, node_name):
7687
    vgname = self.cfg.GetVGName()
7688
    iv_names = {}
7689

    
7690
    for idx, dev in enumerate(self.instance.disks):
7691
      if idx not in self.disks:
7692
        continue
7693

    
7694
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7695

    
7696
      self.cfg.SetDiskID(dev, node_name)
7697

    
7698
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7699
      names = _GenerateUniqueNames(self.lu, lv_names)
7700

    
7701
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7702
                             logical_id=(vgname, names[0]))
7703
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7704
                             logical_id=(vgname, names[1]))
7705

    
7706
      new_lvs = [lv_data, lv_meta]
7707
      old_lvs = dev.children
7708
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7709

    
7710
      # we pass force_create=True to force the LVM creation
7711
      for new_lv in new_lvs:
7712
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7713
                        _GetInstanceInfoText(self.instance), False)
7714

    
7715
    return iv_names
7716

    
7717
  def _CheckDevices(self, node_name, iv_names):
7718
    for name, (dev, _, _) in iv_names.iteritems():
7719
      self.cfg.SetDiskID(dev, node_name)
7720

    
7721
      result = self.rpc.call_blockdev_find(node_name, dev)
7722

    
7723
      msg = result.fail_msg
7724
      if msg or not result.payload:
7725
        if not msg:
7726
          msg = "disk not found"
7727
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7728
                                 (name, msg))
7729

    
7730
      if result.payload.is_degraded:
7731
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7732

    
7733
  def _RemoveOldStorage(self, node_name, iv_names):
7734
    for name, (_, old_lvs, _) in iv_names.iteritems():
7735
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7736

    
7737
      for lv in old_lvs:
7738
        self.cfg.SetDiskID(lv, node_name)
7739

    
7740
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7741
        if msg:
7742
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7743
                             hint="remove unused LVs manually")
7744

    
7745
  def _ReleaseNodeLock(self, node_name):
7746
    """Releases the lock for a given node."""
7747
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7748

    
7749
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7750
    """Replace a disk on the primary or secondary for DRBD 8.
7751

7752
    The algorithm for replace is quite complicated:
7753

7754
      1. for each disk to be replaced:
7755

7756
        1. create new LVs on the target node with unique names
7757
        1. detach old LVs from the drbd device
7758
        1. rename old LVs to name_replaced.<time_t>
7759
        1. rename new LVs to old LVs
7760
        1. attach the new LVs (with the old names now) to the drbd device
7761

7762
      1. wait for sync across all devices
7763

7764
      1. for each modified disk:
7765

7766
        1. remove old LVs (which have the name name_replaces.<time_t>)
7767

7768
    Failures are not very well handled.
7769

7770
    """
7771
    steps_total = 6
7772

    
7773
    # Step: check device activation
7774
    self.lu.LogStep(1, steps_total, "Check device existence")
7775
    self._CheckDisksExistence([self.other_node, self.target_node])
7776
    self._CheckVolumeGroup([self.target_node, self.other_node])
7777

    
7778
    # Step: check other node consistency
7779
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7780
    self._CheckDisksConsistency(self.other_node,
7781
                                self.other_node == self.instance.primary_node,
7782
                                False)
7783

    
7784
    # Step: create new storage
7785
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7786
    iv_names = self._CreateNewStorage(self.target_node)
7787

    
7788
    # Step: for each lv, detach+rename*2+attach
7789
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7790
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7791
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7792

    
7793
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7794
                                                     old_lvs)
7795
      result.Raise("Can't detach drbd from local storage on node"
7796
                   " %s for device %s" % (self.target_node, dev.iv_name))
7797
      #dev.children = []
7798
      #cfg.Update(instance)
7799

    
7800
      # ok, we created the new LVs, so now we know we have the needed
7801
      # storage; as such, we proceed on the target node to rename
7802
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7803
      # using the assumption that logical_id == physical_id (which in
7804
      # turn is the unique_id on that node)
7805

    
7806
      # FIXME(iustin): use a better name for the replaced LVs
7807
      temp_suffix = int(time.time())
7808
      ren_fn = lambda d, suff: (d.physical_id[0],
7809
                                d.physical_id[1] + "_replaced-%s" % suff)
7810

    
7811
      # Build the rename list based on what LVs exist on the node
7812
      rename_old_to_new = []
7813
      for to_ren in old_lvs:
7814
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7815
        if not result.fail_msg and result.payload:
7816
          # device exists
7817
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7818

    
7819
      self.lu.LogInfo("Renaming the old LVs on the target node")
7820
      result = self.rpc.call_blockdev_rename(self.target_node,
7821
                                             rename_old_to_new)
7822
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7823

    
7824
      # Now we rename the new LVs to the old LVs
7825
      self.lu.LogInfo("Renaming the new LVs on the target node")
7826
      rename_new_to_old = [(new, old.physical_id)
7827
                           for old, new in zip(old_lvs, new_lvs)]
7828
      result = self.rpc.call_blockdev_rename(self.target_node,
7829
                                             rename_new_to_old)
7830
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7831

    
7832
      for old, new in zip(old_lvs, new_lvs):
7833
        new.logical_id = old.logical_id
7834
        self.cfg.SetDiskID(new, self.target_node)
7835

    
7836
      for disk in old_lvs:
7837
        disk.logical_id = ren_fn(disk, temp_suffix)
7838
        self.cfg.SetDiskID(disk, self.target_node)
7839

    
7840
      # Now that the new lvs have the old name, we can add them to the device
7841
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7842
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7843
                                                  new_lvs)
7844
      msg = result.fail_msg
7845
      if msg:
7846
        for new_lv in new_lvs:
7847
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7848
                                               new_lv).fail_msg
7849
          if msg2:
7850
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7851
                               hint=("cleanup manually the unused logical"
7852
                                     "volumes"))
7853
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7854

    
7855
      dev.children = new_lvs
7856

    
7857
      self.cfg.Update(self.instance, feedback_fn)
7858

    
7859
    cstep = 5
7860
    if self.early_release:
7861
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7862
      cstep += 1
7863
      self._RemoveOldStorage(self.target_node, iv_names)
7864
      # WARNING: we release both node locks here, do not do other RPCs
7865
      # than WaitForSync to the primary node
7866
      self._ReleaseNodeLock([self.target_node, self.other_node])
7867

    
7868
    # Wait for sync
7869
    # This can fail as the old devices are degraded and _WaitForSync
7870
    # does a combined result over all disks, so we don't check its return value
7871
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7872
    cstep += 1
7873
    _WaitForSync(self.lu, self.instance)
7874

    
7875
    # Check all devices manually
7876
    self._CheckDevices(self.instance.primary_node, iv_names)
7877

    
7878
    # Step: remove old storage
7879
    if not self.early_release:
7880
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7881
      cstep += 1
7882
      self._RemoveOldStorage(self.target_node, iv_names)
7883

    
7884
  def _ExecDrbd8Secondary(self, feedback_fn):
7885
    """Replace the secondary node for DRBD 8.
7886

7887
    The algorithm for replace is quite complicated:
7888
      - for all disks of the instance:
7889
        - create new LVs on the new node with same names
7890
        - shutdown the drbd device on the old secondary
7891
        - disconnect the drbd network on the primary
7892
        - create the drbd device on the new secondary
7893
        - network attach the drbd on the primary, using an artifice:
7894
          the drbd code for Attach() will connect to the network if it
7895
          finds a device which is connected to the good local disks but
7896
          not network enabled
7897
      - wait for sync across all devices
7898
      - remove all disks from the old secondary
7899

7900
    Failures are not very well handled.
7901

7902
    """
7903
    steps_total = 6
7904

    
7905
    # Step: check device activation
7906
    self.lu.LogStep(1, steps_total, "Check device existence")
7907
    self._CheckDisksExistence([self.instance.primary_node])
7908
    self._CheckVolumeGroup([self.instance.primary_node])
7909

    
7910
    # Step: check other node consistency
7911
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7912
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7913

    
7914
    # Step: create new storage
7915
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7916
    for idx, dev in enumerate(self.instance.disks):
7917
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7918
                      (self.new_node, idx))
7919
      # we pass force_create=True to force LVM creation
7920
      for new_lv in dev.children:
7921
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7922
                        _GetInstanceInfoText(self.instance), False)
7923

    
7924
    # Step 4: dbrd minors and drbd setups changes
7925
    # after this, we must manually remove the drbd minors on both the
7926
    # error and the success paths
7927
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7928
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7929
                                         for dev in self.instance.disks],
7930
                                        self.instance.name)
7931
    logging.debug("Allocated minors %r", minors)
7932

    
7933
    iv_names = {}
7934
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7935
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7936
                      (self.new_node, idx))
7937
      # create new devices on new_node; note that we create two IDs:
7938
      # one without port, so the drbd will be activated without
7939
      # networking information on the new node at this stage, and one
7940
      # with network, for the latter activation in step 4
7941
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7942
      if self.instance.primary_node == o_node1:
7943
        p_minor = o_minor1
7944
      else:
7945
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7946
        p_minor = o_minor2
7947

    
7948
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7949
                      p_minor, new_minor, o_secret)
7950
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7951
                    p_minor, new_minor, o_secret)
7952

    
7953
      iv_names[idx] = (dev, dev.children, new_net_id)
7954
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7955
                    new_net_id)
7956
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7957
                              logical_id=new_alone_id,
7958
                              children=dev.children,
7959
                              size=dev.size)
7960
      try:
7961
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
7962
                              _GetInstanceInfoText(self.instance), False)
7963
      except errors.GenericError:
7964
        self.cfg.ReleaseDRBDMinors(self.instance.name)
7965
        raise
7966

    
7967
    # We have new devices, shutdown the drbd on the old secondary
7968
    for idx, dev in enumerate(self.instance.disks):
7969
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
7970
      self.cfg.SetDiskID(dev, self.target_node)
7971
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
7972
      if msg:
7973
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
7974
                           "node: %s" % (idx, msg),
7975
                           hint=("Please cleanup this device manually as"
7976
                                 " soon as possible"))
7977

    
7978
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
7979
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
7980
                                               self.node_secondary_ip,
7981
                                               self.instance.disks)\
7982
                                              [self.instance.primary_node]
7983

    
7984
    msg = result.fail_msg
7985
    if msg:
7986
      # detaches didn't succeed (unlikely)
7987
      self.cfg.ReleaseDRBDMinors(self.instance.name)
7988
      raise errors.OpExecError("Can't detach the disks from the network on"
7989
                               " old node: %s" % (msg,))
7990

    
7991
    # if we managed to detach at least one, we update all the disks of
7992
    # the instance to point to the new secondary
7993
    self.lu.LogInfo("Updating instance configuration")
7994
    for dev, _, new_logical_id in iv_names.itervalues():
7995
      dev.logical_id = new_logical_id
7996
      self.cfg.SetDiskID(dev, self.instance.primary_node)
7997

    
7998
    self.cfg.Update(self.instance, feedback_fn)
7999

    
8000
    # and now perform the drbd attach
8001
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8002
                    " (standalone => connected)")
8003
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8004
                                            self.new_node],
8005
                                           self.node_secondary_ip,
8006
                                           self.instance.disks,
8007
                                           self.instance.name,
8008
                                           False)
8009
    for to_node, to_result in result.items():
8010
      msg = to_result.fail_msg
8011
      if msg:
8012
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8013
                           to_node, msg,
8014
                           hint=("please do a gnt-instance info to see the"
8015
                                 " status of disks"))
8016
    cstep = 5
8017
    if self.early_release:
8018
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8019
      cstep += 1
8020
      self._RemoveOldStorage(self.target_node, iv_names)
8021
      # WARNING: we release all node locks here, do not do other RPCs
8022
      # than WaitForSync to the primary node
8023
      self._ReleaseNodeLock([self.instance.primary_node,
8024
                             self.target_node,
8025
                             self.new_node])
8026

    
8027
    # Wait for sync
8028
    # This can fail as the old devices are degraded and _WaitForSync
8029
    # does a combined result over all disks, so we don't check its return value
8030
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8031
    cstep += 1
8032
    _WaitForSync(self.lu, self.instance)
8033

    
8034
    # Check all devices manually
8035
    self._CheckDevices(self.instance.primary_node, iv_names)
8036

    
8037
    # Step: remove old storage
8038
    if not self.early_release:
8039
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8040
      self._RemoveOldStorage(self.target_node, iv_names)
8041

    
8042

    
8043
class LURepairNodeStorage(NoHooksLU):
8044
  """Repairs the volume group on a node.
8045

8046
  """
8047
  _OP_PARAMS = [
8048
    _PNodeName,
8049
    ("storage_type", _NoDefault, _CheckStorageType),
8050
    ("name", _NoDefault, _TNonEmptyString),
8051
    ("ignore_consistency", False, _TBool),
8052
    ]
8053
  REQ_BGL = False
8054

    
8055
  def CheckArguments(self):
8056
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8057

    
8058
    storage_type = self.op.storage_type
8059

    
8060
    if (constants.SO_FIX_CONSISTENCY not in
8061
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8062
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8063
                                 " repaired" % storage_type,
8064
                                 errors.ECODE_INVAL)
8065

    
8066
  def ExpandNames(self):
8067
    self.needed_locks = {
8068
      locking.LEVEL_NODE: [self.op.node_name],
8069
      }
8070

    
8071
  def _CheckFaultyDisks(self, instance, node_name):
8072
    """Ensure faulty disks abort the opcode or at least warn."""
8073
    try:
8074
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8075
                                  node_name, True):
8076
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8077
                                   " node '%s'" % (instance.name, node_name),
8078
                                   errors.ECODE_STATE)
8079
    except errors.OpPrereqError, err:
8080
      if self.op.ignore_consistency:
8081
        self.proc.LogWarning(str(err.args[0]))
8082
      else:
8083
        raise
8084

    
8085
  def CheckPrereq(self):
8086
    """Check prerequisites.
8087

8088
    """
8089
    # Check whether any instance on this node has faulty disks
8090
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8091
      if not inst.admin_up:
8092
        continue
8093
      check_nodes = set(inst.all_nodes)
8094
      check_nodes.discard(self.op.node_name)
8095
      for inst_node_name in check_nodes:
8096
        self._CheckFaultyDisks(inst, inst_node_name)
8097

    
8098
  def Exec(self, feedback_fn):
8099
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8100
                (self.op.name, self.op.node_name))
8101

    
8102
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8103
    result = self.rpc.call_storage_execute(self.op.node_name,
8104
                                           self.op.storage_type, st_args,
8105
                                           self.op.name,
8106
                                           constants.SO_FIX_CONSISTENCY)
8107
    result.Raise("Failed to repair storage unit '%s' on %s" %
8108
                 (self.op.name, self.op.node_name))
8109

    
8110

    
8111
class LUNodeEvacuationStrategy(NoHooksLU):
8112
  """Computes the node evacuation strategy.
8113

8114
  """
8115
  _OP_PARAMS = [
8116
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8117
    ("remote_node", None, _TMaybeString),
8118
    ("iallocator", None, _TMaybeString),
8119
    ]
8120
  REQ_BGL = False
8121

    
8122
  def CheckArguments(self):
8123
    if self.op.remote_node is not None and self.op.iallocator is not None:
8124
      raise errors.OpPrereqError("Give either the iallocator or the new"
8125
                                 " secondary, not both", errors.ECODE_INVAL)
8126

    
8127
  def ExpandNames(self):
8128
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8129
    self.needed_locks = locks = {}
8130
    if self.op.remote_node is None:
8131
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8132
    else:
8133
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8134
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8135

    
8136
  def Exec(self, feedback_fn):
8137
    if self.op.remote_node is not None:
8138
      instances = []
8139
      for node in self.op.nodes:
8140
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8141
      result = []
8142
      for i in instances:
8143
        if i.primary_node == self.op.remote_node:
8144
          raise errors.OpPrereqError("Node %s is the primary node of"
8145
                                     " instance %s, cannot use it as"
8146
                                     " secondary" %
8147
                                     (self.op.remote_node, i.name),
8148
                                     errors.ECODE_INVAL)
8149
        result.append([i.name, self.op.remote_node])
8150
    else:
8151
      ial = IAllocator(self.cfg, self.rpc,
8152
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8153
                       evac_nodes=self.op.nodes)
8154
      ial.Run(self.op.iallocator, validate=True)
8155
      if not ial.success:
8156
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8157
                                 errors.ECODE_NORES)
8158
      result = ial.result
8159
    return result
8160

    
8161

    
8162
class LUGrowDisk(LogicalUnit):
8163
  """Grow a disk of an instance.
8164

8165
  """
8166
  HPATH = "disk-grow"
8167
  HTYPE = constants.HTYPE_INSTANCE
8168
  _OP_PARAMS = [
8169
    _PInstanceName,
8170
    ("disk", _NoDefault, _TInt),
8171
    ("amount", _NoDefault, _TInt),
8172
    ("wait_for_sync", True, _TBool),
8173
    ]
8174
  REQ_BGL = False
8175

    
8176
  def ExpandNames(self):
8177
    self._ExpandAndLockInstance()
8178
    self.needed_locks[locking.LEVEL_NODE] = []
8179
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8180

    
8181
  def DeclareLocks(self, level):
8182
    if level == locking.LEVEL_NODE:
8183
      self._LockInstancesNodes()
8184

    
8185
  def BuildHooksEnv(self):
8186
    """Build hooks env.
8187

8188
    This runs on the master, the primary and all the secondaries.
8189

8190
    """
8191
    env = {
8192
      "DISK": self.op.disk,
8193
      "AMOUNT": self.op.amount,
8194
      }
8195
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8196
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8197
    return env, nl, nl
8198

    
8199
  def CheckPrereq(self):
8200
    """Check prerequisites.
8201

8202
    This checks that the instance is in the cluster.
8203

8204
    """
8205
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8206
    assert instance is not None, \
8207
      "Cannot retrieve locked instance %s" % self.op.instance_name
8208
    nodenames = list(instance.all_nodes)
8209
    for node in nodenames:
8210
      _CheckNodeOnline(self, node)
8211

    
8212
    self.instance = instance
8213

    
8214
    if instance.disk_template not in constants.DTS_GROWABLE:
8215
      raise errors.OpPrereqError("Instance's disk layout does not support"
8216
                                 " growing.", errors.ECODE_INVAL)
8217

    
8218
    self.disk = instance.FindDisk(self.op.disk)
8219

    
8220
    if instance.disk_template != constants.DT_FILE:
8221
      # TODO: check the free disk space for file, when that feature will be
8222
      # supported
8223
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8224

    
8225
  def Exec(self, feedback_fn):
8226
    """Execute disk grow.
8227

8228
    """
8229
    instance = self.instance
8230
    disk = self.disk
8231

    
8232
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8233
    if not disks_ok:
8234
      raise errors.OpExecError("Cannot activate block device to grow")
8235

    
8236
    for node in instance.all_nodes:
8237
      self.cfg.SetDiskID(disk, node)
8238
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8239
      result.Raise("Grow request failed to node %s" % node)
8240

    
8241
      # TODO: Rewrite code to work properly
8242
      # DRBD goes into sync mode for a short amount of time after executing the
8243
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8244
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8245
      # time is a work-around.
8246
      time.sleep(5)
8247

    
8248
    disk.RecordGrow(self.op.amount)
8249
    self.cfg.Update(instance, feedback_fn)
8250
    if self.op.wait_for_sync:
8251
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8252
      if disk_abort:
8253
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8254
                             " status.\nPlease check the instance.")
8255
      if not instance.admin_up:
8256
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8257
    elif not instance.admin_up:
8258
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8259
                           " not supposed to be running because no wait for"
8260
                           " sync mode was requested.")
8261

    
8262

    
8263
class LUQueryInstanceData(NoHooksLU):
8264
  """Query runtime instance data.
8265

8266
  """
8267
  _OP_PARAMS = [
8268
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8269
    ("static", False, _TBool),
8270
    ]
8271
  REQ_BGL = False
8272

    
8273
  def ExpandNames(self):
8274
    self.needed_locks = {}
8275
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8276

    
8277
    if self.op.instances:
8278
      self.wanted_names = []
8279
      for name in self.op.instances:
8280
        full_name = _ExpandInstanceName(self.cfg, name)
8281
        self.wanted_names.append(full_name)
8282
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8283
    else:
8284
      self.wanted_names = None
8285
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8286

    
8287
    self.needed_locks[locking.LEVEL_NODE] = []
8288
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8289

    
8290
  def DeclareLocks(self, level):
8291
    if level == locking.LEVEL_NODE:
8292
      self._LockInstancesNodes()
8293

    
8294
  def CheckPrereq(self):
8295
    """Check prerequisites.
8296

8297
    This only checks the optional instance list against the existing names.
8298

8299
    """
8300
    if self.wanted_names is None:
8301
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8302

    
8303
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8304
                             in self.wanted_names]
8305

    
8306
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8307
    """Returns the status of a block device
8308

8309
    """
8310
    if self.op.static or not node:
8311
      return None
8312

    
8313
    self.cfg.SetDiskID(dev, node)
8314

    
8315
    result = self.rpc.call_blockdev_find(node, dev)
8316
    if result.offline:
8317
      return None
8318

    
8319
    result.Raise("Can't compute disk status for %s" % instance_name)
8320

    
8321
    status = result.payload
8322
    if status is None:
8323
      return None
8324

    
8325
    return (status.dev_path, status.major, status.minor,
8326
            status.sync_percent, status.estimated_time,
8327
            status.is_degraded, status.ldisk_status)
8328

    
8329
  def _ComputeDiskStatus(self, instance, snode, dev):
8330
    """Compute block device status.
8331

8332
    """
8333
    if dev.dev_type in constants.LDS_DRBD:
8334
      # we change the snode then (otherwise we use the one passed in)
8335
      if dev.logical_id[0] == instance.primary_node:
8336
        snode = dev.logical_id[1]
8337
      else:
8338
        snode = dev.logical_id[0]
8339

    
8340
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8341
                                              instance.name, dev)
8342
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8343

    
8344
    if dev.children:
8345
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8346
                      for child in dev.children]
8347
    else:
8348
      dev_children = []
8349

    
8350
    data = {
8351
      "iv_name": dev.iv_name,
8352
      "dev_type": dev.dev_type,
8353
      "logical_id": dev.logical_id,
8354
      "physical_id": dev.physical_id,
8355
      "pstatus": dev_pstatus,
8356
      "sstatus": dev_sstatus,
8357
      "children": dev_children,
8358
      "mode": dev.mode,
8359
      "size": dev.size,
8360
      }
8361

    
8362
    return data
8363

    
8364
  def Exec(self, feedback_fn):
8365
    """Gather and return data"""
8366
    result = {}
8367

    
8368
    cluster = self.cfg.GetClusterInfo()
8369

    
8370
    for instance in self.wanted_instances:
8371
      if not self.op.static:
8372
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8373
                                                  instance.name,
8374
                                                  instance.hypervisor)
8375
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8376
        remote_info = remote_info.payload
8377
        if remote_info and "state" in remote_info:
8378
          remote_state = "up"
8379
        else:
8380
          remote_state = "down"
8381
      else:
8382
        remote_state = None
8383
      if instance.admin_up:
8384
        config_state = "up"
8385
      else:
8386
        config_state = "down"
8387

    
8388
      disks = [self._ComputeDiskStatus(instance, None, device)
8389
               for device in instance.disks]
8390

    
8391
      idict = {
8392
        "name": instance.name,
8393
        "config_state": config_state,
8394
        "run_state": remote_state,
8395
        "pnode": instance.primary_node,
8396
        "snodes": instance.secondary_nodes,
8397
        "os": instance.os,
8398
        # this happens to be the same format used for hooks
8399
        "nics": _NICListToTuple(self, instance.nics),
8400
        "disk_template": instance.disk_template,
8401
        "disks": disks,
8402
        "hypervisor": instance.hypervisor,
8403
        "network_port": instance.network_port,
8404
        "hv_instance": instance.hvparams,
8405
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8406
        "be_instance": instance.beparams,
8407
        "be_actual": cluster.FillBE(instance),
8408
        "os_instance": instance.osparams,
8409
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8410
        "serial_no": instance.serial_no,
8411
        "mtime": instance.mtime,
8412
        "ctime": instance.ctime,
8413
        "uuid": instance.uuid,
8414
        }
8415

    
8416
      result[instance.name] = idict
8417

    
8418
    return result
8419

    
8420

    
8421
class LUSetInstanceParams(LogicalUnit):
8422
  """Modifies an instances's parameters.
8423

8424
  """
8425
  HPATH = "instance-modify"
8426
  HTYPE = constants.HTYPE_INSTANCE
8427
  _OP_PARAMS = [
8428
    _PInstanceName,
8429
    ("nics", _EmptyList, _TList),
8430
    ("disks", _EmptyList, _TList),
8431
    ("beparams", _EmptyDict, _TDict),
8432
    ("hvparams", _EmptyDict, _TDict),
8433
    ("disk_template", None, _TMaybeString),
8434
    ("remote_node", None, _TMaybeString),
8435
    ("os_name", None, _TMaybeString),
8436
    ("force_variant", False, _TBool),
8437
    ("osparams", None, _TOr(_TDict, _TNone)),
8438
    _PForce,
8439
    ]
8440
  REQ_BGL = False
8441

    
8442
  def CheckArguments(self):
8443
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8444
            self.op.hvparams or self.op.beparams or self.op.os_name):
8445
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8446

    
8447
    if self.op.hvparams:
8448
      _CheckGlobalHvParams(self.op.hvparams)
8449

    
8450
    # Disk validation
8451
    disk_addremove = 0
8452
    for disk_op, disk_dict in self.op.disks:
8453
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8454
      if disk_op == constants.DDM_REMOVE:
8455
        disk_addremove += 1
8456
        continue
8457
      elif disk_op == constants.DDM_ADD:
8458
        disk_addremove += 1
8459
      else:
8460
        if not isinstance(disk_op, int):
8461
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8462
        if not isinstance(disk_dict, dict):
8463
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8464
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8465

    
8466
      if disk_op == constants.DDM_ADD:
8467
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8468
        if mode not in constants.DISK_ACCESS_SET:
8469
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8470
                                     errors.ECODE_INVAL)
8471
        size = disk_dict.get('size', None)
8472
        if size is None:
8473
          raise errors.OpPrereqError("Required disk parameter size missing",
8474
                                     errors.ECODE_INVAL)
8475
        try:
8476
          size = int(size)
8477
        except (TypeError, ValueError), err:
8478
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8479
                                     str(err), errors.ECODE_INVAL)
8480
        disk_dict['size'] = size
8481
      else:
8482
        # modification of disk
8483
        if 'size' in disk_dict:
8484
          raise errors.OpPrereqError("Disk size change not possible, use"
8485
                                     " grow-disk", errors.ECODE_INVAL)
8486

    
8487
    if disk_addremove > 1:
8488
      raise errors.OpPrereqError("Only one disk add or remove operation"
8489
                                 " supported at a time", errors.ECODE_INVAL)
8490

    
8491
    if self.op.disks and self.op.disk_template is not None:
8492
      raise errors.OpPrereqError("Disk template conversion and other disk"
8493
                                 " changes not supported at the same time",
8494
                                 errors.ECODE_INVAL)
8495

    
8496
    if self.op.disk_template:
8497
      _CheckDiskTemplate(self.op.disk_template)
8498
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8499
          self.op.remote_node is None):
8500
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8501
                                   " one requires specifying a secondary node",
8502
                                   errors.ECODE_INVAL)
8503

    
8504
    # NIC validation
8505
    nic_addremove = 0
8506
    for nic_op, nic_dict in self.op.nics:
8507
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8508
      if nic_op == constants.DDM_REMOVE:
8509
        nic_addremove += 1
8510
        continue
8511
      elif nic_op == constants.DDM_ADD:
8512
        nic_addremove += 1
8513
      else:
8514
        if not isinstance(nic_op, int):
8515
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8516
        if not isinstance(nic_dict, dict):
8517
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8518
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8519

    
8520
      # nic_dict should be a dict
8521
      nic_ip = nic_dict.get('ip', None)
8522
      if nic_ip is not None:
8523
        if nic_ip.lower() == constants.VALUE_NONE:
8524
          nic_dict['ip'] = None
8525
        else:
8526
          if not utils.IsValidIP4(nic_ip):
8527
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8528
                                       errors.ECODE_INVAL)
8529

    
8530
      nic_bridge = nic_dict.get('bridge', None)
8531
      nic_link = nic_dict.get('link', None)
8532
      if nic_bridge and nic_link:
8533
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8534
                                   " at the same time", errors.ECODE_INVAL)
8535
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8536
        nic_dict['bridge'] = None
8537
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8538
        nic_dict['link'] = None
8539

    
8540
      if nic_op == constants.DDM_ADD:
8541
        nic_mac = nic_dict.get('mac', None)
8542
        if nic_mac is None:
8543
          nic_dict['mac'] = constants.VALUE_AUTO
8544

    
8545
      if 'mac' in nic_dict:
8546
        nic_mac = nic_dict['mac']
8547
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8548
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8549

    
8550
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8551
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8552
                                     " modifying an existing nic",
8553
                                     errors.ECODE_INVAL)
8554

    
8555
    if nic_addremove > 1:
8556
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8557
                                 " supported at a time", errors.ECODE_INVAL)
8558

    
8559
  def ExpandNames(self):
8560
    self._ExpandAndLockInstance()
8561
    self.needed_locks[locking.LEVEL_NODE] = []
8562
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8563

    
8564
  def DeclareLocks(self, level):
8565
    if level == locking.LEVEL_NODE:
8566
      self._LockInstancesNodes()
8567
      if self.op.disk_template and self.op.remote_node:
8568
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8569
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8570

    
8571
  def BuildHooksEnv(self):
8572
    """Build hooks env.
8573

8574
    This runs on the master, primary and secondaries.
8575

8576
    """
8577
    args = dict()
8578
    if constants.BE_MEMORY in self.be_new:
8579
      args['memory'] = self.be_new[constants.BE_MEMORY]
8580
    if constants.BE_VCPUS in self.be_new:
8581
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8582
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8583
    # information at all.
8584
    if self.op.nics:
8585
      args['nics'] = []
8586
      nic_override = dict(self.op.nics)
8587
      for idx, nic in enumerate(self.instance.nics):
8588
        if idx in nic_override:
8589
          this_nic_override = nic_override[idx]
8590
        else:
8591
          this_nic_override = {}
8592
        if 'ip' in this_nic_override:
8593
          ip = this_nic_override['ip']
8594
        else:
8595
          ip = nic.ip
8596
        if 'mac' in this_nic_override:
8597
          mac = this_nic_override['mac']
8598
        else:
8599
          mac = nic.mac
8600
        if idx in self.nic_pnew:
8601
          nicparams = self.nic_pnew[idx]
8602
        else:
8603
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8604
        mode = nicparams[constants.NIC_MODE]
8605
        link = nicparams[constants.NIC_LINK]
8606
        args['nics'].append((ip, mac, mode, link))
8607
      if constants.DDM_ADD in nic_override:
8608
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8609
        mac = nic_override[constants.DDM_ADD]['mac']
8610
        nicparams = self.nic_pnew[constants.DDM_ADD]
8611
        mode = nicparams[constants.NIC_MODE]
8612
        link = nicparams[constants.NIC_LINK]
8613
        args['nics'].append((ip, mac, mode, link))
8614
      elif constants.DDM_REMOVE in nic_override:
8615
        del args['nics'][-1]
8616

    
8617
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8618
    if self.op.disk_template:
8619
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8620
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8621
    return env, nl, nl
8622

    
8623
  def CheckPrereq(self):
8624
    """Check prerequisites.
8625

8626
    This only checks the instance list against the existing names.
8627

8628
    """
8629
    # checking the new params on the primary/secondary nodes
8630

    
8631
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8632
    cluster = self.cluster = self.cfg.GetClusterInfo()
8633
    assert self.instance is not None, \
8634
      "Cannot retrieve locked instance %s" % self.op.instance_name
8635
    pnode = instance.primary_node
8636
    nodelist = list(instance.all_nodes)
8637

    
8638
    # OS change
8639
    if self.op.os_name and not self.op.force:
8640
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8641
                      self.op.force_variant)
8642
      instance_os = self.op.os_name
8643
    else:
8644
      instance_os = instance.os
8645

    
8646
    if self.op.disk_template:
8647
      if instance.disk_template == self.op.disk_template:
8648
        raise errors.OpPrereqError("Instance already has disk template %s" %
8649
                                   instance.disk_template, errors.ECODE_INVAL)
8650

    
8651
      if (instance.disk_template,
8652
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8653
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8654
                                   " %s to %s" % (instance.disk_template,
8655
                                                  self.op.disk_template),
8656
                                   errors.ECODE_INVAL)
8657
      _CheckInstanceDown(self, instance, "cannot change disk template")
8658
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8659
        _CheckNodeOnline(self, self.op.remote_node)
8660
        _CheckNodeNotDrained(self, self.op.remote_node)
8661
        disks = [{"size": d.size} for d in instance.disks]
8662
        required = _ComputeDiskSize(self.op.disk_template, disks)
8663
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8664

    
8665
    # hvparams processing
8666
    if self.op.hvparams:
8667
      hv_type = instance.hypervisor
8668
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8669
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8670
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8671

    
8672
      # local check
8673
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8674
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8675
      self.hv_new = hv_new # the new actual values
8676
      self.hv_inst = i_hvdict # the new dict (without defaults)
8677
    else:
8678
      self.hv_new = self.hv_inst = {}
8679

    
8680
    # beparams processing
8681
    if self.op.beparams:
8682
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8683
                                   use_none=True)
8684
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8685
      be_new = cluster.SimpleFillBE(i_bedict)
8686
      self.be_new = be_new # the new actual values
8687
      self.be_inst = i_bedict # the new dict (without defaults)
8688
    else:
8689
      self.be_new = self.be_inst = {}
8690

    
8691
    # osparams processing
8692
    if self.op.osparams:
8693
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8694
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8695
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8696
      self.os_inst = i_osdict # the new dict (without defaults)
8697
    else:
8698
      self.os_new = self.os_inst = {}
8699

    
8700
    self.warn = []
8701

    
8702
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8703
      mem_check_list = [pnode]
8704
      if be_new[constants.BE_AUTO_BALANCE]:
8705
        # either we changed auto_balance to yes or it was from before
8706
        mem_check_list.extend(instance.secondary_nodes)
8707
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8708
                                                  instance.hypervisor)
8709
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8710
                                         instance.hypervisor)
8711
      pninfo = nodeinfo[pnode]
8712
      msg = pninfo.fail_msg
8713
      if msg:
8714
        # Assume the primary node is unreachable and go ahead
8715
        self.warn.append("Can't get info from primary node %s: %s" %
8716
                         (pnode,  msg))
8717
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8718
        self.warn.append("Node data from primary node %s doesn't contain"
8719
                         " free memory information" % pnode)
8720
      elif instance_info.fail_msg:
8721
        self.warn.append("Can't get instance runtime information: %s" %
8722
                        instance_info.fail_msg)
8723
      else:
8724
        if instance_info.payload:
8725
          current_mem = int(instance_info.payload['memory'])
8726
        else:
8727
          # Assume instance not running
8728
          # (there is a slight race condition here, but it's not very probable,
8729
          # and we have no other way to check)
8730
          current_mem = 0
8731
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8732
                    pninfo.payload['memory_free'])
8733
        if miss_mem > 0:
8734
          raise errors.OpPrereqError("This change will prevent the instance"
8735
                                     " from starting, due to %d MB of memory"
8736
                                     " missing on its primary node" % miss_mem,
8737
                                     errors.ECODE_NORES)
8738

    
8739
      if be_new[constants.BE_AUTO_BALANCE]:
8740
        for node, nres in nodeinfo.items():
8741
          if node not in instance.secondary_nodes:
8742
            continue
8743
          msg = nres.fail_msg
8744
          if msg:
8745
            self.warn.append("Can't get info from secondary node %s: %s" %
8746
                             (node, msg))
8747
          elif not isinstance(nres.payload.get('memory_free', None), int):
8748
            self.warn.append("Secondary node %s didn't return free"
8749
                             " memory information" % node)
8750
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8751
            self.warn.append("Not enough memory to failover instance to"
8752
                             " secondary node %s" % node)
8753

    
8754
    # NIC processing
8755
    self.nic_pnew = {}
8756
    self.nic_pinst = {}
8757
    for nic_op, nic_dict in self.op.nics:
8758
      if nic_op == constants.DDM_REMOVE:
8759
        if not instance.nics:
8760
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8761
                                     errors.ECODE_INVAL)
8762
        continue
8763
      if nic_op != constants.DDM_ADD:
8764
        # an existing nic
8765
        if not instance.nics:
8766
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8767
                                     " no NICs" % nic_op,
8768
                                     errors.ECODE_INVAL)
8769
        if nic_op < 0 or nic_op >= len(instance.nics):
8770
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8771
                                     " are 0 to %d" %
8772
                                     (nic_op, len(instance.nics) - 1),
8773
                                     errors.ECODE_INVAL)
8774
        old_nic_params = instance.nics[nic_op].nicparams
8775
        old_nic_ip = instance.nics[nic_op].ip
8776
      else:
8777
        old_nic_params = {}
8778
        old_nic_ip = None
8779

    
8780
      update_params_dict = dict([(key, nic_dict[key])
8781
                                 for key in constants.NICS_PARAMETERS
8782
                                 if key in nic_dict])
8783

    
8784
      if 'bridge' in nic_dict:
8785
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8786

    
8787
      new_nic_params = _GetUpdatedParams(old_nic_params,
8788
                                         update_params_dict)
8789
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8790
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8791
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8792
      self.nic_pinst[nic_op] = new_nic_params
8793
      self.nic_pnew[nic_op] = new_filled_nic_params
8794
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8795

    
8796
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8797
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8798
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8799
        if msg:
8800
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8801
          if self.op.force:
8802
            self.warn.append(msg)
8803
          else:
8804
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8805
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8806
        if 'ip' in nic_dict:
8807
          nic_ip = nic_dict['ip']
8808
        else:
8809
          nic_ip = old_nic_ip
8810
        if nic_ip is None:
8811
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8812
                                     ' on a routed nic', errors.ECODE_INVAL)
8813
      if 'mac' in nic_dict:
8814
        nic_mac = nic_dict['mac']
8815
        if nic_mac is None:
8816
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8817
                                     errors.ECODE_INVAL)
8818
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8819
          # otherwise generate the mac
8820
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8821
        else:
8822
          # or validate/reserve the current one
8823
          try:
8824
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8825
          except errors.ReservationError:
8826
            raise errors.OpPrereqError("MAC address %s already in use"
8827
                                       " in cluster" % nic_mac,
8828
                                       errors.ECODE_NOTUNIQUE)
8829

    
8830
    # DISK processing
8831
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8832
      raise errors.OpPrereqError("Disk operations not supported for"
8833
                                 " diskless instances",
8834
                                 errors.ECODE_INVAL)
8835
    for disk_op, _ in self.op.disks:
8836
      if disk_op == constants.DDM_REMOVE:
8837
        if len(instance.disks) == 1:
8838
          raise errors.OpPrereqError("Cannot remove the last disk of"
8839
                                     " an instance", errors.ECODE_INVAL)
8840
        _CheckInstanceDown(self, instance, "cannot remove disks")
8841

    
8842
      if (disk_op == constants.DDM_ADD and
8843
          len(instance.nics) >= constants.MAX_DISKS):
8844
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8845
                                   " add more" % constants.MAX_DISKS,
8846
                                   errors.ECODE_STATE)
8847
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8848
        # an existing disk
8849
        if disk_op < 0 or disk_op >= len(instance.disks):
8850
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8851
                                     " are 0 to %d" %
8852
                                     (disk_op, len(instance.disks)),
8853
                                     errors.ECODE_INVAL)
8854

    
8855
    return
8856

    
8857
  def _ConvertPlainToDrbd(self, feedback_fn):
8858
    """Converts an instance from plain to drbd.
8859

8860
    """
8861
    feedback_fn("Converting template to drbd")
8862
    instance = self.instance
8863
    pnode = instance.primary_node
8864
    snode = self.op.remote_node
8865

    
8866
    # create a fake disk info for _GenerateDiskTemplate
8867
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8868
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8869
                                      instance.name, pnode, [snode],
8870
                                      disk_info, None, None, 0)
8871
    info = _GetInstanceInfoText(instance)
8872
    feedback_fn("Creating aditional volumes...")
8873
    # first, create the missing data and meta devices
8874
    for disk in new_disks:
8875
      # unfortunately this is... not too nice
8876
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8877
                            info, True)
8878
      for child in disk.children:
8879
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8880
    # at this stage, all new LVs have been created, we can rename the
8881
    # old ones
8882
    feedback_fn("Renaming original volumes...")
8883
    rename_list = [(o, n.children[0].logical_id)
8884
                   for (o, n) in zip(instance.disks, new_disks)]
8885
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8886
    result.Raise("Failed to rename original LVs")
8887

    
8888
    feedback_fn("Initializing DRBD devices...")
8889
    # all child devices are in place, we can now create the DRBD devices
8890
    for disk in new_disks:
8891
      for node in [pnode, snode]:
8892
        f_create = node == pnode
8893
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8894

    
8895
    # at this point, the instance has been modified
8896
    instance.disk_template = constants.DT_DRBD8
8897
    instance.disks = new_disks
8898
    self.cfg.Update(instance, feedback_fn)
8899

    
8900
    # disks are created, waiting for sync
8901
    disk_abort = not _WaitForSync(self, instance)
8902
    if disk_abort:
8903
      raise errors.OpExecError("There are some degraded disks for"
8904
                               " this instance, please cleanup manually")
8905

    
8906
  def _ConvertDrbdToPlain(self, feedback_fn):
8907
    """Converts an instance from drbd to plain.
8908

8909
    """
8910
    instance = self.instance
8911
    assert len(instance.secondary_nodes) == 1
8912
    pnode = instance.primary_node
8913
    snode = instance.secondary_nodes[0]
8914
    feedback_fn("Converting template to plain")
8915

    
8916
    old_disks = instance.disks
8917
    new_disks = [d.children[0] for d in old_disks]
8918

    
8919
    # copy over size and mode
8920
    for parent, child in zip(old_disks, new_disks):
8921
      child.size = parent.size
8922
      child.mode = parent.mode
8923

    
8924
    # update instance structure
8925
    instance.disks = new_disks
8926
    instance.disk_template = constants.DT_PLAIN
8927
    self.cfg.Update(instance, feedback_fn)
8928

    
8929
    feedback_fn("Removing volumes on the secondary node...")
8930
    for disk in old_disks:
8931
      self.cfg.SetDiskID(disk, snode)
8932
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8933
      if msg:
8934
        self.LogWarning("Could not remove block device %s on node %s,"
8935
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8936

    
8937
    feedback_fn("Removing unneeded volumes on the primary node...")
8938
    for idx, disk in enumerate(old_disks):
8939
      meta = disk.children[1]
8940
      self.cfg.SetDiskID(meta, pnode)
8941
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8942
      if msg:
8943
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8944
                        " continuing anyway: %s", idx, pnode, msg)
8945

    
8946

    
8947
  def Exec(self, feedback_fn):
8948
    """Modifies an instance.
8949

8950
    All parameters take effect only at the next restart of the instance.
8951

8952
    """
8953
    # Process here the warnings from CheckPrereq, as we don't have a
8954
    # feedback_fn there.
8955
    for warn in self.warn:
8956
      feedback_fn("WARNING: %s" % warn)
8957

    
8958
    result = []
8959
    instance = self.instance
8960
    # disk changes
8961
    for disk_op, disk_dict in self.op.disks:
8962
      if disk_op == constants.DDM_REMOVE:
8963
        # remove the last disk
8964
        device = instance.disks.pop()
8965
        device_idx = len(instance.disks)
8966
        for node, disk in device.ComputeNodeTree(instance.primary_node):
8967
          self.cfg.SetDiskID(disk, node)
8968
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
8969
          if msg:
8970
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
8971
                            " continuing anyway", device_idx, node, msg)
8972
        result.append(("disk/%d" % device_idx, "remove"))
8973
      elif disk_op == constants.DDM_ADD:
8974
        # add a new disk
8975
        if instance.disk_template == constants.DT_FILE:
8976
          file_driver, file_path = instance.disks[0].logical_id
8977
          file_path = os.path.dirname(file_path)
8978
        else:
8979
          file_driver = file_path = None
8980
        disk_idx_base = len(instance.disks)
8981
        new_disk = _GenerateDiskTemplate(self,
8982
                                         instance.disk_template,
8983
                                         instance.name, instance.primary_node,
8984
                                         instance.secondary_nodes,
8985
                                         [disk_dict],
8986
                                         file_path,
8987
                                         file_driver,
8988
                                         disk_idx_base)[0]
8989
        instance.disks.append(new_disk)
8990
        info = _GetInstanceInfoText(instance)
8991

    
8992
        logging.info("Creating volume %s for instance %s",
8993
                     new_disk.iv_name, instance.name)
8994
        # Note: this needs to be kept in sync with _CreateDisks
8995
        #HARDCODE
8996
        for node in instance.all_nodes:
8997
          f_create = node == instance.primary_node
8998
          try:
8999
            _CreateBlockDev(self, node, instance, new_disk,
9000
                            f_create, info, f_create)
9001
          except errors.OpExecError, err:
9002
            self.LogWarning("Failed to create volume %s (%s) on"
9003
                            " node %s: %s",
9004
                            new_disk.iv_name, new_disk, node, err)
9005
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9006
                       (new_disk.size, new_disk.mode)))
9007
      else:
9008
        # change a given disk
9009
        instance.disks[disk_op].mode = disk_dict['mode']
9010
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9011

    
9012
    if self.op.disk_template:
9013
      r_shut = _ShutdownInstanceDisks(self, instance)
9014
      if not r_shut:
9015
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9016
                                 " proceed with disk template conversion")
9017
      mode = (instance.disk_template, self.op.disk_template)
9018
      try:
9019
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9020
      except:
9021
        self.cfg.ReleaseDRBDMinors(instance.name)
9022
        raise
9023
      result.append(("disk_template", self.op.disk_template))
9024

    
9025
    # NIC changes
9026
    for nic_op, nic_dict in self.op.nics:
9027
      if nic_op == constants.DDM_REMOVE:
9028
        # remove the last nic
9029
        del instance.nics[-1]
9030
        result.append(("nic.%d" % len(instance.nics), "remove"))
9031
      elif nic_op == constants.DDM_ADD:
9032
        # mac and bridge should be set, by now
9033
        mac = nic_dict['mac']
9034
        ip = nic_dict.get('ip', None)
9035
        nicparams = self.nic_pinst[constants.DDM_ADD]
9036
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9037
        instance.nics.append(new_nic)
9038
        result.append(("nic.%d" % (len(instance.nics) - 1),
9039
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9040
                       (new_nic.mac, new_nic.ip,
9041
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9042
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9043
                       )))
9044
      else:
9045
        for key in 'mac', 'ip':
9046
          if key in nic_dict:
9047
            setattr(instance.nics[nic_op], key, nic_dict[key])
9048
        if nic_op in self.nic_pinst:
9049
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9050
        for key, val in nic_dict.iteritems():
9051
          result.append(("nic.%s/%d" % (key, nic_op), val))
9052

    
9053
    # hvparams changes
9054
    if self.op.hvparams:
9055
      instance.hvparams = self.hv_inst
9056
      for key, val in self.op.hvparams.iteritems():
9057
        result.append(("hv/%s" % key, val))
9058

    
9059
    # beparams changes
9060
    if self.op.beparams:
9061
      instance.beparams = self.be_inst
9062
      for key, val in self.op.beparams.iteritems():
9063
        result.append(("be/%s" % key, val))
9064

    
9065
    # OS change
9066
    if self.op.os_name:
9067
      instance.os = self.op.os_name
9068

    
9069
    # osparams changes
9070
    if self.op.osparams:
9071
      instance.osparams = self.os_inst
9072
      for key, val in self.op.osparams.iteritems():
9073
        result.append(("os/%s" % key, val))
9074

    
9075
    self.cfg.Update(instance, feedback_fn)
9076

    
9077
    return result
9078

    
9079
  _DISK_CONVERSIONS = {
9080
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9081
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9082
    }
9083

    
9084

    
9085
class LUQueryExports(NoHooksLU):
9086
  """Query the exports list
9087

9088
  """
9089
  _OP_PARAMS = [
9090
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9091
    ("use_locking", False, _TBool),
9092
    ]
9093
  REQ_BGL = False
9094

    
9095
  def ExpandNames(self):
9096
    self.needed_locks = {}
9097
    self.share_locks[locking.LEVEL_NODE] = 1
9098
    if not self.op.nodes:
9099
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9100
    else:
9101
      self.needed_locks[locking.LEVEL_NODE] = \
9102
        _GetWantedNodes(self, self.op.nodes)
9103

    
9104
  def Exec(self, feedback_fn):
9105
    """Compute the list of all the exported system images.
9106

9107
    @rtype: dict
9108
    @return: a dictionary with the structure node->(export-list)
9109
        where export-list is a list of the instances exported on
9110
        that node.
9111

9112
    """
9113
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9114
    rpcresult = self.rpc.call_export_list(self.nodes)
9115
    result = {}
9116
    for node in rpcresult:
9117
      if rpcresult[node].fail_msg:
9118
        result[node] = False
9119
      else:
9120
        result[node] = rpcresult[node].payload
9121

    
9122
    return result
9123

    
9124

    
9125
class LUPrepareExport(NoHooksLU):
9126
  """Prepares an instance for an export and returns useful information.
9127

9128
  """
9129
  _OP_PARAMS = [
9130
    _PInstanceName,
9131
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9132
    ]
9133
  REQ_BGL = False
9134

    
9135
  def ExpandNames(self):
9136
    self._ExpandAndLockInstance()
9137

    
9138
  def CheckPrereq(self):
9139
    """Check prerequisites.
9140

9141
    """
9142
    instance_name = self.op.instance_name
9143

    
9144
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9145
    assert self.instance is not None, \
9146
          "Cannot retrieve locked instance %s" % self.op.instance_name
9147
    _CheckNodeOnline(self, self.instance.primary_node)
9148

    
9149
    self._cds = _GetClusterDomainSecret()
9150

    
9151
  def Exec(self, feedback_fn):
9152
    """Prepares an instance for an export.
9153

9154
    """
9155
    instance = self.instance
9156

    
9157
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9158
      salt = utils.GenerateSecret(8)
9159

    
9160
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9161
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9162
                                              constants.RIE_CERT_VALIDITY)
9163
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9164

    
9165
      (name, cert_pem) = result.payload
9166

    
9167
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9168
                                             cert_pem)
9169

    
9170
      return {
9171
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9172
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9173
                          salt),
9174
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9175
        }
9176

    
9177
    return None
9178

    
9179

    
9180
class LUExportInstance(LogicalUnit):
9181
  """Export an instance to an image in the cluster.
9182

9183
  """
9184
  HPATH = "instance-export"
9185
  HTYPE = constants.HTYPE_INSTANCE
9186
  _OP_PARAMS = [
9187
    _PInstanceName,
9188
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9189
    ("shutdown", True, _TBool),
9190
    _PShutdownTimeout,
9191
    ("remove_instance", False, _TBool),
9192
    ("ignore_remove_failures", False, _TBool),
9193
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9194
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9195
    ("destination_x509_ca", None, _TMaybeString),
9196
    ]
9197
  REQ_BGL = False
9198

    
9199
  def CheckArguments(self):
9200
    """Check the arguments.
9201

9202
    """
9203
    self.x509_key_name = self.op.x509_key_name
9204
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9205

    
9206
    if self.op.remove_instance and not self.op.shutdown:
9207
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9208
                                 " down before")
9209

    
9210
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9211
      if not self.x509_key_name:
9212
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9213
                                   errors.ECODE_INVAL)
9214

    
9215
      if not self.dest_x509_ca_pem:
9216
        raise errors.OpPrereqError("Missing destination X509 CA",
9217
                                   errors.ECODE_INVAL)
9218

    
9219
  def ExpandNames(self):
9220
    self._ExpandAndLockInstance()
9221

    
9222
    # Lock all nodes for local exports
9223
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9224
      # FIXME: lock only instance primary and destination node
9225
      #
9226
      # Sad but true, for now we have do lock all nodes, as we don't know where
9227
      # the previous export might be, and in this LU we search for it and
9228
      # remove it from its current node. In the future we could fix this by:
9229
      #  - making a tasklet to search (share-lock all), then create the
9230
      #    new one, then one to remove, after
9231
      #  - removing the removal operation altogether
9232
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9233

    
9234
  def DeclareLocks(self, level):
9235
    """Last minute lock declaration."""
9236
    # All nodes are locked anyway, so nothing to do here.
9237

    
9238
  def BuildHooksEnv(self):
9239
    """Build hooks env.
9240

9241
    This will run on the master, primary node and target node.
9242

9243
    """
9244
    env = {
9245
      "EXPORT_MODE": self.op.mode,
9246
      "EXPORT_NODE": self.op.target_node,
9247
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9248
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9249
      # TODO: Generic function for boolean env variables
9250
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9251
      }
9252

    
9253
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9254

    
9255
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9256

    
9257
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9258
      nl.append(self.op.target_node)
9259

    
9260
    return env, nl, nl
9261

    
9262
  def CheckPrereq(self):
9263
    """Check prerequisites.
9264

9265
    This checks that the instance and node names are valid.
9266

9267
    """
9268
    instance_name = self.op.instance_name
9269

    
9270
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9271
    assert self.instance is not None, \
9272
          "Cannot retrieve locked instance %s" % self.op.instance_name
9273
    _CheckNodeOnline(self, self.instance.primary_node)
9274

    
9275
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9276
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9277
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9278
      assert self.dst_node is not None
9279

    
9280
      _CheckNodeOnline(self, self.dst_node.name)
9281
      _CheckNodeNotDrained(self, self.dst_node.name)
9282

    
9283
      self._cds = None
9284
      self.dest_disk_info = None
9285
      self.dest_x509_ca = None
9286

    
9287
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9288
      self.dst_node = None
9289

    
9290
      if len(self.op.target_node) != len(self.instance.disks):
9291
        raise errors.OpPrereqError(("Received destination information for %s"
9292
                                    " disks, but instance %s has %s disks") %
9293
                                   (len(self.op.target_node), instance_name,
9294
                                    len(self.instance.disks)),
9295
                                   errors.ECODE_INVAL)
9296

    
9297
      cds = _GetClusterDomainSecret()
9298

    
9299
      # Check X509 key name
9300
      try:
9301
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9302
      except (TypeError, ValueError), err:
9303
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9304

    
9305
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9306
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9307
                                   errors.ECODE_INVAL)
9308

    
9309
      # Load and verify CA
9310
      try:
9311
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9312
      except OpenSSL.crypto.Error, err:
9313
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9314
                                   (err, ), errors.ECODE_INVAL)
9315

    
9316
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9317
      if errcode is not None:
9318
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9319
                                   (msg, ), errors.ECODE_INVAL)
9320

    
9321
      self.dest_x509_ca = cert
9322

    
9323
      # Verify target information
9324
      disk_info = []
9325
      for idx, disk_data in enumerate(self.op.target_node):
9326
        try:
9327
          (host, port, magic) = \
9328
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9329
        except errors.GenericError, err:
9330
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9331
                                     (idx, err), errors.ECODE_INVAL)
9332

    
9333
        disk_info.append((host, port, magic))
9334

    
9335
      assert len(disk_info) == len(self.op.target_node)
9336
      self.dest_disk_info = disk_info
9337

    
9338
    else:
9339
      raise errors.ProgrammerError("Unhandled export mode %r" %
9340
                                   self.op.mode)
9341

    
9342
    # instance disk type verification
9343
    # TODO: Implement export support for file-based disks
9344
    for disk in self.instance.disks:
9345
      if disk.dev_type == constants.LD_FILE:
9346
        raise errors.OpPrereqError("Export not supported for instances with"
9347
                                   " file-based disks", errors.ECODE_INVAL)
9348

    
9349
  def _CleanupExports(self, feedback_fn):
9350
    """Removes exports of current instance from all other nodes.
9351

9352
    If an instance in a cluster with nodes A..D was exported to node C, its
9353
    exports will be removed from the nodes A, B and D.
9354

9355
    """
9356
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9357

    
9358
    nodelist = self.cfg.GetNodeList()
9359
    nodelist.remove(self.dst_node.name)
9360

    
9361
    # on one-node clusters nodelist will be empty after the removal
9362
    # if we proceed the backup would be removed because OpQueryExports
9363
    # substitutes an empty list with the full cluster node list.
9364
    iname = self.instance.name
9365
    if nodelist:
9366
      feedback_fn("Removing old exports for instance %s" % iname)
9367
      exportlist = self.rpc.call_export_list(nodelist)
9368
      for node in exportlist:
9369
        if exportlist[node].fail_msg:
9370
          continue
9371
        if iname in exportlist[node].payload:
9372
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9373
          if msg:
9374
            self.LogWarning("Could not remove older export for instance %s"
9375
                            " on node %s: %s", iname, node, msg)
9376

    
9377
  def Exec(self, feedback_fn):
9378
    """Export an instance to an image in the cluster.
9379

9380
    """
9381
    assert self.op.mode in constants.EXPORT_MODES
9382

    
9383
    instance = self.instance
9384
    src_node = instance.primary_node
9385

    
9386
    if self.op.shutdown:
9387
      # shutdown the instance, but not the disks
9388
      feedback_fn("Shutting down instance %s" % instance.name)
9389
      result = self.rpc.call_instance_shutdown(src_node, instance,
9390
                                               self.op.shutdown_timeout)
9391
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9392
      result.Raise("Could not shutdown instance %s on"
9393
                   " node %s" % (instance.name, src_node))
9394

    
9395
    # set the disks ID correctly since call_instance_start needs the
9396
    # correct drbd minor to create the symlinks
9397
    for disk in instance.disks:
9398
      self.cfg.SetDiskID(disk, src_node)
9399

    
9400
    activate_disks = (not instance.admin_up)
9401

    
9402
    if activate_disks:
9403
      # Activate the instance disks if we'exporting a stopped instance
9404
      feedback_fn("Activating disks for %s" % instance.name)
9405
      _StartInstanceDisks(self, instance, None)
9406

    
9407
    try:
9408
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9409
                                                     instance)
9410

    
9411
      helper.CreateSnapshots()
9412
      try:
9413
        if (self.op.shutdown and instance.admin_up and
9414
            not self.op.remove_instance):
9415
          assert not activate_disks
9416
          feedback_fn("Starting instance %s" % instance.name)
9417
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9418
          msg = result.fail_msg
9419
          if msg:
9420
            feedback_fn("Failed to start instance: %s" % msg)
9421
            _ShutdownInstanceDisks(self, instance)
9422
            raise errors.OpExecError("Could not start instance: %s" % msg)
9423

    
9424
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9425
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9426
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9427
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9428
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9429

    
9430
          (key_name, _, _) = self.x509_key_name
9431

    
9432
          dest_ca_pem = \
9433
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9434
                                            self.dest_x509_ca)
9435

    
9436
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9437
                                                     key_name, dest_ca_pem,
9438
                                                     timeouts)
9439
      finally:
9440
        helper.Cleanup()
9441

    
9442
      # Check for backwards compatibility
9443
      assert len(dresults) == len(instance.disks)
9444
      assert compat.all(isinstance(i, bool) for i in dresults), \
9445
             "Not all results are boolean: %r" % dresults
9446

    
9447
    finally:
9448
      if activate_disks:
9449
        feedback_fn("Deactivating disks for %s" % instance.name)
9450
        _ShutdownInstanceDisks(self, instance)
9451

    
9452
    # Remove instance if requested
9453
    if self.op.remove_instance:
9454
      if not (compat.all(dresults) and fin_resu):
9455
        feedback_fn("Not removing instance %s as parts of the export failed" %
9456
                    instance.name)
9457
      else:
9458
        feedback_fn("Removing instance %s" % instance.name)
9459
        _RemoveInstance(self, feedback_fn, instance,
9460
                        self.op.ignore_remove_failures)
9461

    
9462
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9463
      self._CleanupExports(feedback_fn)
9464

    
9465
    return fin_resu, dresults
9466

    
9467

    
9468
class LURemoveExport(NoHooksLU):
9469
  """Remove exports related to the named instance.
9470

9471
  """
9472
  _OP_PARAMS = [
9473
    _PInstanceName,
9474
    ]
9475
  REQ_BGL = False
9476

    
9477
  def ExpandNames(self):
9478
    self.needed_locks = {}
9479
    # We need all nodes to be locked in order for RemoveExport to work, but we
9480
    # don't need to lock the instance itself, as nothing will happen to it (and
9481
    # we can remove exports also for a removed instance)
9482
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9483

    
9484
  def Exec(self, feedback_fn):
9485
    """Remove any export.
9486

9487
    """
9488
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9489
    # If the instance was not found we'll try with the name that was passed in.
9490
    # This will only work if it was an FQDN, though.
9491
    fqdn_warn = False
9492
    if not instance_name:
9493
      fqdn_warn = True
9494
      instance_name = self.op.instance_name
9495

    
9496
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9497
    exportlist = self.rpc.call_export_list(locked_nodes)
9498
    found = False
9499
    for node in exportlist:
9500
      msg = exportlist[node].fail_msg
9501
      if msg:
9502
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9503
        continue
9504
      if instance_name in exportlist[node].payload:
9505
        found = True
9506
        result = self.rpc.call_export_remove(node, instance_name)
9507
        msg = result.fail_msg
9508
        if msg:
9509
          logging.error("Could not remove export for instance %s"
9510
                        " on node %s: %s", instance_name, node, msg)
9511

    
9512
    if fqdn_warn and not found:
9513
      feedback_fn("Export not found. If trying to remove an export belonging"
9514
                  " to a deleted instance please use its Fully Qualified"
9515
                  " Domain Name.")
9516

    
9517

    
9518
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9519
  """Generic tags LU.
9520

9521
  This is an abstract class which is the parent of all the other tags LUs.
9522

9523
  """
9524

    
9525
  def ExpandNames(self):
9526
    self.needed_locks = {}
9527
    if self.op.kind == constants.TAG_NODE:
9528
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9529
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9530
    elif self.op.kind == constants.TAG_INSTANCE:
9531
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9532
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9533

    
9534
  def CheckPrereq(self):
9535
    """Check prerequisites.
9536

9537
    """
9538
    if self.op.kind == constants.TAG_CLUSTER:
9539
      self.target = self.cfg.GetClusterInfo()
9540
    elif self.op.kind == constants.TAG_NODE:
9541
      self.target = self.cfg.GetNodeInfo(self.op.name)
9542
    elif self.op.kind == constants.TAG_INSTANCE:
9543
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9544
    else:
9545
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9546
                                 str(self.op.kind), errors.ECODE_INVAL)
9547

    
9548

    
9549
class LUGetTags(TagsLU):
9550
  """Returns the tags of a given object.
9551

9552
  """
9553
  _OP_PARAMS = [
9554
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9555
    ("name", _NoDefault, _TNonEmptyString),
9556
    ]
9557
  REQ_BGL = False
9558

    
9559
  def Exec(self, feedback_fn):
9560
    """Returns the tag list.
9561

9562
    """
9563
    return list(self.target.GetTags())
9564

    
9565

    
9566
class LUSearchTags(NoHooksLU):
9567
  """Searches the tags for a given pattern.
9568

9569
  """
9570
  _OP_PARAMS = [
9571
    ("pattern", _NoDefault, _TNonEmptyString),
9572
    ]
9573
  REQ_BGL = False
9574

    
9575
  def ExpandNames(self):
9576
    self.needed_locks = {}
9577

    
9578
  def CheckPrereq(self):
9579
    """Check prerequisites.
9580

9581
    This checks the pattern passed for validity by compiling it.
9582

9583
    """
9584
    try:
9585
      self.re = re.compile(self.op.pattern)
9586
    except re.error, err:
9587
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9588
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9589

    
9590
  def Exec(self, feedback_fn):
9591
    """Returns the tag list.
9592

9593
    """
9594
    cfg = self.cfg
9595
    tgts = [("/cluster", cfg.GetClusterInfo())]
9596
    ilist = cfg.GetAllInstancesInfo().values()
9597
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9598
    nlist = cfg.GetAllNodesInfo().values()
9599
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9600
    results = []
9601
    for path, target in tgts:
9602
      for tag in target.GetTags():
9603
        if self.re.search(tag):
9604
          results.append((path, tag))
9605
    return results
9606

    
9607

    
9608
class LUAddTags(TagsLU):
9609
  """Sets a tag on a given object.
9610

9611
  """
9612
  _OP_PARAMS = [
9613
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9614
    ("name", _NoDefault, _TNonEmptyString),
9615
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9616
    ]
9617
  REQ_BGL = False
9618

    
9619
  def CheckPrereq(self):
9620
    """Check prerequisites.
9621

9622
    This checks the type and length of the tag name and value.
9623

9624
    """
9625
    TagsLU.CheckPrereq(self)
9626
    for tag in self.op.tags:
9627
      objects.TaggableObject.ValidateTag(tag)
9628

    
9629
  def Exec(self, feedback_fn):
9630
    """Sets the tag.
9631

9632
    """
9633
    try:
9634
      for tag in self.op.tags:
9635
        self.target.AddTag(tag)
9636
    except errors.TagError, err:
9637
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9638
    self.cfg.Update(self.target, feedback_fn)
9639

    
9640

    
9641
class LUDelTags(TagsLU):
9642
  """Delete a list of tags from a given object.
9643

9644
  """
9645
  _OP_PARAMS = [
9646
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9647
    ("name", _NoDefault, _TNonEmptyString),
9648
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9649
    ]
9650
  REQ_BGL = False
9651

    
9652
  def CheckPrereq(self):
9653
    """Check prerequisites.
9654

9655
    This checks that we have the given tag.
9656

9657
    """
9658
    TagsLU.CheckPrereq(self)
9659
    for tag in self.op.tags:
9660
      objects.TaggableObject.ValidateTag(tag)
9661
    del_tags = frozenset(self.op.tags)
9662
    cur_tags = self.target.GetTags()
9663
    if not del_tags <= cur_tags:
9664
      diff_tags = del_tags - cur_tags
9665
      diff_names = ["'%s'" % tag for tag in diff_tags]
9666
      diff_names.sort()
9667
      raise errors.OpPrereqError("Tag(s) %s not found" %
9668
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9669

    
9670
  def Exec(self, feedback_fn):
9671
    """Remove the tag from the object.
9672

9673
    """
9674
    for tag in self.op.tags:
9675
      self.target.RemoveTag(tag)
9676
    self.cfg.Update(self.target, feedback_fn)
9677

    
9678

    
9679
class LUTestDelay(NoHooksLU):
9680
  """Sleep for a specified amount of time.
9681

9682
  This LU sleeps on the master and/or nodes for a specified amount of
9683
  time.
9684

9685
  """
9686
  _OP_PARAMS = [
9687
    ("duration", _NoDefault, _TFloat),
9688
    ("on_master", True, _TBool),
9689
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9690
    ("repeat", 0, _TPositiveInt)
9691
    ]
9692
  REQ_BGL = False
9693

    
9694
  def ExpandNames(self):
9695
    """Expand names and set required locks.
9696

9697
    This expands the node list, if any.
9698

9699
    """
9700
    self.needed_locks = {}
9701
    if self.op.on_nodes:
9702
      # _GetWantedNodes can be used here, but is not always appropriate to use
9703
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9704
      # more information.
9705
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9706
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9707

    
9708
  def _TestDelay(self):
9709
    """Do the actual sleep.
9710

9711
    """
9712
    if self.op.on_master:
9713
      if not utils.TestDelay(self.op.duration):
9714
        raise errors.OpExecError("Error during master delay test")
9715
    if self.op.on_nodes:
9716
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9717
      for node, node_result in result.items():
9718
        node_result.Raise("Failure during rpc call to node %s" % node)
9719

    
9720
  def Exec(self, feedback_fn):
9721
    """Execute the test delay opcode, with the wanted repetitions.
9722

9723
    """
9724
    if self.op.repeat == 0:
9725
      self._TestDelay()
9726
    else:
9727
      top_value = self.op.repeat - 1
9728
      for i in range(self.op.repeat):
9729
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9730
        self._TestDelay()
9731

    
9732

    
9733
class IAllocator(object):
9734
  """IAllocator framework.
9735

9736
  An IAllocator instance has three sets of attributes:
9737
    - cfg that is needed to query the cluster
9738
    - input data (all members of the _KEYS class attribute are required)
9739
    - four buffer attributes (in|out_data|text), that represent the
9740
      input (to the external script) in text and data structure format,
9741
      and the output from it, again in two formats
9742
    - the result variables from the script (success, info, nodes) for
9743
      easy usage
9744

9745
  """
9746
  # pylint: disable-msg=R0902
9747
  # lots of instance attributes
9748
  _ALLO_KEYS = [
9749
    "name", "mem_size", "disks", "disk_template",
9750
    "os", "tags", "nics", "vcpus", "hypervisor",
9751
    ]
9752
  _RELO_KEYS = [
9753
    "name", "relocate_from",
9754
    ]
9755
  _EVAC_KEYS = [
9756
    "evac_nodes",
9757
    ]
9758

    
9759
  def __init__(self, cfg, rpc, mode, **kwargs):
9760
    self.cfg = cfg
9761
    self.rpc = rpc
9762
    # init buffer variables
9763
    self.in_text = self.out_text = self.in_data = self.out_data = None
9764
    # init all input fields so that pylint is happy
9765
    self.mode = mode
9766
    self.mem_size = self.disks = self.disk_template = None
9767
    self.os = self.tags = self.nics = self.vcpus = None
9768
    self.hypervisor = None
9769
    self.relocate_from = None
9770
    self.name = None
9771
    self.evac_nodes = None
9772
    # computed fields
9773
    self.required_nodes = None
9774
    # init result fields
9775
    self.success = self.info = self.result = None
9776
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9777
      keyset = self._ALLO_KEYS
9778
      fn = self._AddNewInstance
9779
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9780
      keyset = self._RELO_KEYS
9781
      fn = self._AddRelocateInstance
9782
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9783
      keyset = self._EVAC_KEYS
9784
      fn = self._AddEvacuateNodes
9785
    else:
9786
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9787
                                   " IAllocator" % self.mode)
9788
    for key in kwargs:
9789
      if key not in keyset:
9790
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9791
                                     " IAllocator" % key)
9792
      setattr(self, key, kwargs[key])
9793

    
9794
    for key in keyset:
9795
      if key not in kwargs:
9796
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9797
                                     " IAllocator" % key)
9798
    self._BuildInputData(fn)
9799

    
9800
  def _ComputeClusterData(self):
9801
    """Compute the generic allocator input data.
9802

9803
    This is the data that is independent of the actual operation.
9804

9805
    """
9806
    cfg = self.cfg
9807
    cluster_info = cfg.GetClusterInfo()
9808
    # cluster data
9809
    data = {
9810
      "version": constants.IALLOCATOR_VERSION,
9811
      "cluster_name": cfg.GetClusterName(),
9812
      "cluster_tags": list(cluster_info.GetTags()),
9813
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9814
      # we don't have job IDs
9815
      }
9816
    iinfo = cfg.GetAllInstancesInfo().values()
9817
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9818

    
9819
    # node data
9820
    node_results = {}
9821
    node_list = cfg.GetNodeList()
9822

    
9823
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9824
      hypervisor_name = self.hypervisor
9825
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9826
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9827
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9828
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9829

    
9830
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9831
                                        hypervisor_name)
9832
    node_iinfo = \
9833
      self.rpc.call_all_instances_info(node_list,
9834
                                       cluster_info.enabled_hypervisors)
9835
    for nname, nresult in node_data.items():
9836
      # first fill in static (config-based) values
9837
      ninfo = cfg.GetNodeInfo(nname)
9838
      pnr = {
9839
        "tags": list(ninfo.GetTags()),
9840
        "primary_ip": ninfo.primary_ip,
9841
        "secondary_ip": ninfo.secondary_ip,
9842
        "offline": ninfo.offline,
9843
        "drained": ninfo.drained,
9844
        "master_candidate": ninfo.master_candidate,
9845
        }
9846

    
9847
      if not (ninfo.offline or ninfo.drained):
9848
        nresult.Raise("Can't get data for node %s" % nname)
9849
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9850
                                nname)
9851
        remote_info = nresult.payload
9852

    
9853
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9854
                     'vg_size', 'vg_free', 'cpu_total']:
9855
          if attr not in remote_info:
9856
            raise errors.OpExecError("Node '%s' didn't return attribute"
9857
                                     " '%s'" % (nname, attr))
9858
          if not isinstance(remote_info[attr], int):
9859
            raise errors.OpExecError("Node '%s' returned invalid value"
9860
                                     " for '%s': %s" %
9861
                                     (nname, attr, remote_info[attr]))
9862
        # compute memory used by primary instances
9863
        i_p_mem = i_p_up_mem = 0
9864
        for iinfo, beinfo in i_list:
9865
          if iinfo.primary_node == nname:
9866
            i_p_mem += beinfo[constants.BE_MEMORY]
9867
            if iinfo.name not in node_iinfo[nname].payload:
9868
              i_used_mem = 0
9869
            else:
9870
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9871
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9872
            remote_info['memory_free'] -= max(0, i_mem_diff)
9873

    
9874
            if iinfo.admin_up:
9875
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9876

    
9877
        # compute memory used by instances
9878
        pnr_dyn = {
9879
          "total_memory": remote_info['memory_total'],
9880
          "reserved_memory": remote_info['memory_dom0'],
9881
          "free_memory": remote_info['memory_free'],
9882
          "total_disk": remote_info['vg_size'],
9883
          "free_disk": remote_info['vg_free'],
9884
          "total_cpus": remote_info['cpu_total'],
9885
          "i_pri_memory": i_p_mem,
9886
          "i_pri_up_memory": i_p_up_mem,
9887
          }
9888
        pnr.update(pnr_dyn)
9889

    
9890
      node_results[nname] = pnr
9891
    data["nodes"] = node_results
9892

    
9893
    # instance data
9894
    instance_data = {}
9895
    for iinfo, beinfo in i_list:
9896
      nic_data = []
9897
      for nic in iinfo.nics:
9898
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
9899
        nic_dict = {"mac": nic.mac,
9900
                    "ip": nic.ip,
9901
                    "mode": filled_params[constants.NIC_MODE],
9902
                    "link": filled_params[constants.NIC_LINK],
9903
                   }
9904
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9905
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9906
        nic_data.append(nic_dict)
9907
      pir = {
9908
        "tags": list(iinfo.GetTags()),
9909
        "admin_up": iinfo.admin_up,
9910
        "vcpus": beinfo[constants.BE_VCPUS],
9911
        "memory": beinfo[constants.BE_MEMORY],
9912
        "os": iinfo.os,
9913
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9914
        "nics": nic_data,
9915
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9916
        "disk_template": iinfo.disk_template,
9917
        "hypervisor": iinfo.hypervisor,
9918
        }
9919
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9920
                                                 pir["disks"])
9921
      instance_data[iinfo.name] = pir
9922

    
9923
    data["instances"] = instance_data
9924

    
9925
    self.in_data = data
9926

    
9927
  def _AddNewInstance(self):
9928
    """Add new instance data to allocator structure.
9929

9930
    This in combination with _AllocatorGetClusterData will create the
9931
    correct structure needed as input for the allocator.
9932

9933
    The checks for the completeness of the opcode must have already been
9934
    done.
9935

9936
    """
9937
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9938

    
9939
    if self.disk_template in constants.DTS_NET_MIRROR:
9940
      self.required_nodes = 2
9941
    else:
9942
      self.required_nodes = 1
9943
    request = {
9944
      "name": self.name,
9945
      "disk_template": self.disk_template,
9946
      "tags": self.tags,
9947
      "os": self.os,
9948
      "vcpus": self.vcpus,
9949
      "memory": self.mem_size,
9950
      "disks": self.disks,
9951
      "disk_space_total": disk_space,
9952
      "nics": self.nics,
9953
      "required_nodes": self.required_nodes,
9954
      }
9955
    return request
9956

    
9957
  def _AddRelocateInstance(self):
9958
    """Add relocate instance data to allocator structure.
9959

9960
    This in combination with _IAllocatorGetClusterData will create the
9961
    correct structure needed as input for the allocator.
9962

9963
    The checks for the completeness of the opcode must have already been
9964
    done.
9965

9966
    """
9967
    instance = self.cfg.GetInstanceInfo(self.name)
9968
    if instance is None:
9969
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
9970
                                   " IAllocator" % self.name)
9971

    
9972
    if instance.disk_template not in constants.DTS_NET_MIRROR:
9973
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
9974
                                 errors.ECODE_INVAL)
9975

    
9976
    if len(instance.secondary_nodes) != 1:
9977
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
9978
                                 errors.ECODE_STATE)
9979

    
9980
    self.required_nodes = 1
9981
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
9982
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
9983

    
9984
    request = {
9985
      "name": self.name,
9986
      "disk_space_total": disk_space,
9987
      "required_nodes": self.required_nodes,
9988
      "relocate_from": self.relocate_from,
9989
      }
9990
    return request
9991

    
9992
  def _AddEvacuateNodes(self):
9993
    """Add evacuate nodes data to allocator structure.
9994

9995
    """
9996
    request = {
9997
      "evac_nodes": self.evac_nodes
9998
      }
9999
    return request
10000

    
10001
  def _BuildInputData(self, fn):
10002
    """Build input data structures.
10003

10004
    """
10005
    self._ComputeClusterData()
10006

    
10007
    request = fn()
10008
    request["type"] = self.mode
10009
    self.in_data["request"] = request
10010

    
10011
    self.in_text = serializer.Dump(self.in_data)
10012

    
10013
  def Run(self, name, validate=True, call_fn=None):
10014
    """Run an instance allocator and return the results.
10015

10016
    """
10017
    if call_fn is None:
10018
      call_fn = self.rpc.call_iallocator_runner
10019

    
10020
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10021
    result.Raise("Failure while running the iallocator script")
10022

    
10023
    self.out_text = result.payload
10024
    if validate:
10025
      self._ValidateResult()
10026

    
10027
  def _ValidateResult(self):
10028
    """Process the allocator results.
10029

10030
    This will process and if successful save the result in
10031
    self.out_data and the other parameters.
10032

10033
    """
10034
    try:
10035
      rdict = serializer.Load(self.out_text)
10036
    except Exception, err:
10037
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10038

    
10039
    if not isinstance(rdict, dict):
10040
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10041

    
10042
    # TODO: remove backwards compatiblity in later versions
10043
    if "nodes" in rdict and "result" not in rdict:
10044
      rdict["result"] = rdict["nodes"]
10045
      del rdict["nodes"]
10046

    
10047
    for key in "success", "info", "result":
10048
      if key not in rdict:
10049
        raise errors.OpExecError("Can't parse iallocator results:"
10050
                                 " missing key '%s'" % key)
10051
      setattr(self, key, rdict[key])
10052

    
10053
    if not isinstance(rdict["result"], list):
10054
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10055
                               " is not a list")
10056
    self.out_data = rdict
10057

    
10058

    
10059
class LUTestAllocator(NoHooksLU):
10060
  """Run allocator tests.
10061

10062
  This LU runs the allocator tests
10063

10064
  """
10065
  _OP_PARAMS = [
10066
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10067
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10068
    ("name", _NoDefault, _TNonEmptyString),
10069
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10070
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10071
               _TOr(_TNone, _TNonEmptyString))))),
10072
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10073
    ("hypervisor", None, _TMaybeString),
10074
    ("allocator", None, _TMaybeString),
10075
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10076
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10077
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10078
    ("os", None, _TMaybeString),
10079
    ("disk_template", None, _TMaybeString),
10080
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10081
    ]
10082

    
10083
  def CheckPrereq(self):
10084
    """Check prerequisites.
10085

10086
    This checks the opcode parameters depending on the director and mode test.
10087

10088
    """
10089
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10090
      for attr in ["mem_size", "disks", "disk_template",
10091
                   "os", "tags", "nics", "vcpus"]:
10092
        if not hasattr(self.op, attr):
10093
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10094
                                     attr, errors.ECODE_INVAL)
10095
      iname = self.cfg.ExpandInstanceName(self.op.name)
10096
      if iname is not None:
10097
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10098
                                   iname, errors.ECODE_EXISTS)
10099
      if not isinstance(self.op.nics, list):
10100
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10101
                                   errors.ECODE_INVAL)
10102
      if not isinstance(self.op.disks, list):
10103
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10104
                                   errors.ECODE_INVAL)
10105
      for row in self.op.disks:
10106
        if (not isinstance(row, dict) or
10107
            "size" not in row or
10108
            not isinstance(row["size"], int) or
10109
            "mode" not in row or
10110
            row["mode"] not in ['r', 'w']):
10111
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10112
                                     " parameter", errors.ECODE_INVAL)
10113
      if self.op.hypervisor is None:
10114
        self.op.hypervisor = self.cfg.GetHypervisorType()
10115
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10116
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10117
      self.op.name = fname
10118
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10119
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10120
      if not hasattr(self.op, "evac_nodes"):
10121
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10122
                                   " opcode input", errors.ECODE_INVAL)
10123
    else:
10124
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10125
                                 self.op.mode, errors.ECODE_INVAL)
10126

    
10127
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10128
      if self.op.allocator is None:
10129
        raise errors.OpPrereqError("Missing allocator name",
10130
                                   errors.ECODE_INVAL)
10131
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10132
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10133
                                 self.op.direction, errors.ECODE_INVAL)
10134

    
10135
  def Exec(self, feedback_fn):
10136
    """Run the allocator test.
10137

10138
    """
10139
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10140
      ial = IAllocator(self.cfg, self.rpc,
10141
                       mode=self.op.mode,
10142
                       name=self.op.name,
10143
                       mem_size=self.op.mem_size,
10144
                       disks=self.op.disks,
10145
                       disk_template=self.op.disk_template,
10146
                       os=self.op.os,
10147
                       tags=self.op.tags,
10148
                       nics=self.op.nics,
10149
                       vcpus=self.op.vcpus,
10150
                       hypervisor=self.op.hypervisor,
10151
                       )
10152
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10153
      ial = IAllocator(self.cfg, self.rpc,
10154
                       mode=self.op.mode,
10155
                       name=self.op.name,
10156
                       relocate_from=list(self.relocate_from),
10157
                       )
10158
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10159
      ial = IAllocator(self.cfg, self.rpc,
10160
                       mode=self.op.mode,
10161
                       evac_nodes=self.op.evac_nodes)
10162
    else:
10163
      raise errors.ProgrammerError("Uncatched mode %s in"
10164
                                   " LUTestAllocator.Exec", self.op.mode)
10165

    
10166
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10167
      result = ial.in_text
10168
    else:
10169
      ial.Run(self.op.allocator, validate=False)
10170
      result = ial.out_text
10171
    return result