Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 7b2cd2b4

History | View | Annotate | Download (356.3 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
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1291
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1292
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1293
  ENODEHV = (TNODE, "ENODEHV")
1294
  ENODELVM = (TNODE, "ENODELVM")
1295
  ENODEN1 = (TNODE, "ENODEN1")
1296
  ENODENET = (TNODE, "ENODENET")
1297
  ENODEOS = (TNODE, "ENODEOS")
1298
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1299
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1300
  ENODERPC = (TNODE, "ENODERPC")
1301
  ENODESSH = (TNODE, "ENODESSH")
1302
  ENODEVERSION = (TNODE, "ENODEVERSION")
1303
  ENODESETUP = (TNODE, "ENODESETUP")
1304
  ENODETIME = (TNODE, "ENODETIME")
1305

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

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

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

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

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

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

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

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

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

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

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

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

1404
    Test list:
1405

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

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

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

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

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

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

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

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

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

    
1463

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

    
1469
    return True
1470

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1582

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1731
    """
1732
    node = ninfo.name
1733
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1734

    
1735
    if drbd_helper:
1736
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1737
      test = (helper_result == None)
1738
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1739
               "no drbd usermode helper returned")
1740
      if helper_result:
1741
        status, payload = helper_result
1742
        test = not status
1743
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1744
                 "drbd usermode helper check unsuccessful: %s", payload)
1745
        test = status and (payload != drbd_helper)
1746
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1747
                 "wrong drbd usermode helper: %s", payload)
1748

    
1749
    # compute the DRBD minors
1750
    node_drbd = {}
1751
    for minor, instance in drbd_map[node].items():
1752
      test = instance not in instanceinfo
1753
      _ErrorIf(test, self.ECLUSTERCFG, None,
1754
               "ghost instance '%s' in temporary DRBD map", instance)
1755
        # ghost instance should not be running, but otherwise we
1756
        # don't give double warnings (both ghost instance and
1757
        # unallocated minor in use)
1758
      if test:
1759
        node_drbd[minor] = (instance, False)
1760
      else:
1761
        instance = instanceinfo[instance]
1762
        node_drbd[minor] = (instance.name, instance.admin_up)
1763

    
1764
    # and now check them
1765
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1766
    test = not isinstance(used_minors, (tuple, list))
1767
    _ErrorIf(test, self.ENODEDRBD, node,
1768
             "cannot parse drbd status file: %s", str(used_minors))
1769
    if test:
1770
      # we cannot check drbd status
1771
      return
1772

    
1773
    for minor, (iname, must_exist) in node_drbd.items():
1774
      test = minor not in used_minors and must_exist
1775
      _ErrorIf(test, self.ENODEDRBD, node,
1776
               "drbd minor %d of instance %s is not active", minor, iname)
1777
    for minor in used_minors:
1778
      test = minor not in node_drbd
1779
      _ErrorIf(test, self.ENODEDRBD, node,
1780
               "unallocated drbd minor %d is in use", minor)
1781

    
1782
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1783
    """Builds the node OS structures.
1784

1785
    @type ninfo: L{objects.Node}
1786
    @param ninfo: the node to check
1787
    @param nresult: the remote results for the node
1788
    @param nimg: the node image object
1789

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

    
1794
    remote_os = nresult.get(constants.NV_OSLIST, None)
1795
    test = (not isinstance(remote_os, list) or
1796
            not compat.all(isinstance(v, list) and len(v) == 7
1797
                           for v in remote_os))
1798

    
1799
    _ErrorIf(test, self.ENODEOS, node,
1800
             "node hasn't returned valid OS data")
1801

    
1802
    nimg.os_fail = test
1803

    
1804
    if test:
1805
      return
1806

    
1807
    os_dict = {}
1808

    
1809
    for (name, os_path, status, diagnose,
1810
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1811

    
1812
      if name not in os_dict:
1813
        os_dict[name] = []
1814

    
1815
      # parameters is a list of lists instead of list of tuples due to
1816
      # JSON lacking a real tuple type, fix it:
1817
      parameters = [tuple(v) for v in parameters]
1818
      os_dict[name].append((os_path, status, diagnose,
1819
                            set(variants), set(parameters), set(api_ver)))
1820

    
1821
    nimg.oslist = os_dict
1822

    
1823
  def _VerifyNodeOS(self, ninfo, nimg, base):
1824
    """Verifies the node OS list.
1825

1826
    @type ninfo: L{objects.Node}
1827
    @param ninfo: the node to check
1828
    @param nimg: the node image object
1829
    @param base: the 'template' node we match against (e.g. from the master)
1830

1831
    """
1832
    node = ninfo.name
1833
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1834

    
1835
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1836

    
1837
    for os_name, os_data in nimg.oslist.items():
1838
      assert os_data, "Empty OS status for OS %s?!" % os_name
1839
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1840
      _ErrorIf(not f_status, self.ENODEOS, node,
1841
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1842
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1843
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1844
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1845
      # this will catched in backend too
1846
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1847
               and not f_var, self.ENODEOS, node,
1848
               "OS %s with API at least %d does not declare any variant",
1849
               os_name, constants.OS_API_V15)
1850
      # comparisons with the 'base' image
1851
      test = os_name not in base.oslist
1852
      _ErrorIf(test, self.ENODEOS, node,
1853
               "Extra OS %s not present on reference node (%s)",
1854
               os_name, base.name)
1855
      if test:
1856
        continue
1857
      assert base.oslist[os_name], "Base node has empty OS status?"
1858
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1859
      if not b_status:
1860
        # base OS is invalid, skipping
1861
        continue
1862
      for kind, a, b in [("API version", f_api, b_api),
1863
                         ("variants list", f_var, b_var),
1864
                         ("parameters", f_param, b_param)]:
1865
        _ErrorIf(a != b, self.ENODEOS, node,
1866
                 "OS %s %s differs from reference node %s: %s vs. %s",
1867
                 kind, os_name, base.name,
1868
                 utils.CommaJoin(a), utils.CommaJoin(b))
1869

    
1870
    # check any missing OSes
1871
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1872
    _ErrorIf(missing, self.ENODEOS, node,
1873
             "OSes present on reference node %s but missing on this node: %s",
1874
             base.name, utils.CommaJoin(missing))
1875

    
1876
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1877
    """Verifies and updates the node volume data.
1878

1879
    This function will update a L{NodeImage}'s internal structures
1880
    with data from the remote call.
1881

1882
    @type ninfo: L{objects.Node}
1883
    @param ninfo: the node to check
1884
    @param nresult: the remote results for the node
1885
    @param nimg: the node image object
1886
    @param vg_name: the configured VG name
1887

1888
    """
1889
    node = ninfo.name
1890
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1891

    
1892
    nimg.lvm_fail = True
1893
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1894
    if vg_name is None:
1895
      pass
1896
    elif isinstance(lvdata, basestring):
1897
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1898
               utils.SafeEncode(lvdata))
1899
    elif not isinstance(lvdata, dict):
1900
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1901
    else:
1902
      nimg.volumes = lvdata
1903
      nimg.lvm_fail = False
1904

    
1905
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1906
    """Verifies and updates the node instance list.
1907

1908
    If the listing was successful, then updates this node's instance
1909
    list. Otherwise, it marks the RPC call as failed for the instance
1910
    list key.
1911

1912
    @type ninfo: L{objects.Node}
1913
    @param ninfo: the node to check
1914
    @param nresult: the remote results for the node
1915
    @param nimg: the node image object
1916

1917
    """
1918
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1919
    test = not isinstance(idata, list)
1920
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1921
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1922
    if test:
1923
      nimg.hyp_fail = True
1924
    else:
1925
      nimg.instances = idata
1926

    
1927
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1928
    """Verifies and computes a node information map
1929

1930
    @type ninfo: L{objects.Node}
1931
    @param ninfo: the node to check
1932
    @param nresult: the remote results for the node
1933
    @param nimg: the node image object
1934
    @param vg_name: the configured VG name
1935

1936
    """
1937
    node = ninfo.name
1938
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1939

    
1940
    # try to read free memory (from the hypervisor)
1941
    hv_info = nresult.get(constants.NV_HVINFO, None)
1942
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1943
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1944
    if not test:
1945
      try:
1946
        nimg.mfree = int(hv_info["memory_free"])
1947
      except (ValueError, TypeError):
1948
        _ErrorIf(True, self.ENODERPC, node,
1949
                 "node returned invalid nodeinfo, check hypervisor")
1950

    
1951
    # FIXME: devise a free space model for file based instances as well
1952
    if vg_name is not None:
1953
      test = (constants.NV_VGLIST not in nresult or
1954
              vg_name not in nresult[constants.NV_VGLIST])
1955
      _ErrorIf(test, self.ENODELVM, node,
1956
               "node didn't return data for the volume group '%s'"
1957
               " - it is either missing or broken", vg_name)
1958
      if not test:
1959
        try:
1960
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1961
        except (ValueError, TypeError):
1962
          _ErrorIf(True, self.ENODERPC, node,
1963
                   "node returned invalid LVM info, check LVM status")
1964

    
1965
  def BuildHooksEnv(self):
1966
    """Build hooks env.
1967

1968
    Cluster-Verify hooks just ran in the post phase and their failure makes
1969
    the output be logged in the verify output and the verification to fail.
1970

1971
    """
1972
    all_nodes = self.cfg.GetNodeList()
1973
    env = {
1974
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1975
      }
1976
    for node in self.cfg.GetAllNodesInfo().values():
1977
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1978

    
1979
    return env, [], all_nodes
1980

    
1981
  def Exec(self, feedback_fn):
1982
    """Verify integrity of cluster, performing various test on nodes.
1983

1984
    """
1985
    self.bad = False
1986
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1987
    verbose = self.op.verbose
1988
    self._feedback_fn = feedback_fn
1989
    feedback_fn("* Verifying global settings")
1990
    for msg in self.cfg.VerifyConfig():
1991
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1992

    
1993
    # Check the cluster certificates
1994
    for cert_filename in constants.ALL_CERT_FILES:
1995
      (errcode, msg) = _VerifyCertificate(cert_filename)
1996
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1997

    
1998
    vg_name = self.cfg.GetVGName()
1999
    drbd_helper = self.cfg.GetDRBDHelper()
2000
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2001
    cluster = self.cfg.GetClusterInfo()
2002
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2003
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2004
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2005
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2006
                        for iname in instancelist)
2007
    i_non_redundant = [] # Non redundant instances
2008
    i_non_a_balanced = [] # Non auto-balanced instances
2009
    n_offline = 0 # Count of offline nodes
2010
    n_drained = 0 # Count of nodes being drained
2011
    node_vol_should = {}
2012

    
2013
    # FIXME: verify OS list
2014
    # do local checksums
2015
    master_files = [constants.CLUSTER_CONF_FILE]
2016
    master_node = self.master_node = self.cfg.GetMasterNode()
2017
    master_ip = self.cfg.GetMasterIP()
2018

    
2019
    file_names = ssconf.SimpleStore().GetFileList()
2020
    file_names.extend(constants.ALL_CERT_FILES)
2021
    file_names.extend(master_files)
2022
    if cluster.modify_etc_hosts:
2023
      file_names.append(constants.ETC_HOSTS)
2024

    
2025
    local_checksums = utils.FingerprintFiles(file_names)
2026

    
2027
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2028
    node_verify_param = {
2029
      constants.NV_FILELIST: file_names,
2030
      constants.NV_NODELIST: [node.name for node in nodeinfo
2031
                              if not node.offline],
2032
      constants.NV_HYPERVISOR: hypervisors,
2033
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2034
                                  node.secondary_ip) for node in nodeinfo
2035
                                 if not node.offline],
2036
      constants.NV_INSTANCELIST: hypervisors,
2037
      constants.NV_VERSION: None,
2038
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2039
      constants.NV_NODESETUP: None,
2040
      constants.NV_TIME: None,
2041
      constants.NV_MASTERIP: (master_node, master_ip),
2042
      constants.NV_OSLIST: None,
2043
      }
2044

    
2045
    if vg_name is not None:
2046
      node_verify_param[constants.NV_VGLIST] = None
2047
      node_verify_param[constants.NV_LVLIST] = vg_name
2048
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2049
      node_verify_param[constants.NV_DRBDLIST] = None
2050

    
2051
    if drbd_helper:
2052
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2053

    
2054
    # Build our expected cluster state
2055
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2056
                                                 name=node.name))
2057
                      for node in nodeinfo)
2058

    
2059
    for instance in instancelist:
2060
      inst_config = instanceinfo[instance]
2061

    
2062
      for nname in inst_config.all_nodes:
2063
        if nname not in node_image:
2064
          # ghost node
2065
          gnode = self.NodeImage(name=nname)
2066
          gnode.ghost = True
2067
          node_image[nname] = gnode
2068

    
2069
      inst_config.MapLVsByNode(node_vol_should)
2070

    
2071
      pnode = inst_config.primary_node
2072
      node_image[pnode].pinst.append(instance)
2073

    
2074
      for snode in inst_config.secondary_nodes:
2075
        nimg = node_image[snode]
2076
        nimg.sinst.append(instance)
2077
        if pnode not in nimg.sbp:
2078
          nimg.sbp[pnode] = []
2079
        nimg.sbp[pnode].append(instance)
2080

    
2081
    # At this point, we have the in-memory data structures complete,
2082
    # except for the runtime information, which we'll gather next
2083

    
2084
    # Due to the way our RPC system works, exact response times cannot be
2085
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2086
    # time before and after executing the request, we can at least have a time
2087
    # window.
2088
    nvinfo_starttime = time.time()
2089
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2090
                                           self.cfg.GetClusterName())
2091
    nvinfo_endtime = time.time()
2092

    
2093
    all_drbd_map = self.cfg.ComputeDRBDMap()
2094

    
2095
    feedback_fn("* Verifying node status")
2096

    
2097
    refos_img = None
2098

    
2099
    for node_i in nodeinfo:
2100
      node = node_i.name
2101
      nimg = node_image[node]
2102

    
2103
      if node_i.offline:
2104
        if verbose:
2105
          feedback_fn("* Skipping offline node %s" % (node,))
2106
        n_offline += 1
2107
        continue
2108

    
2109
      if node == master_node:
2110
        ntype = "master"
2111
      elif node_i.master_candidate:
2112
        ntype = "master candidate"
2113
      elif node_i.drained:
2114
        ntype = "drained"
2115
        n_drained += 1
2116
      else:
2117
        ntype = "regular"
2118
      if verbose:
2119
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2120

    
2121
      msg = all_nvinfo[node].fail_msg
2122
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2123
      if msg:
2124
        nimg.rpc_fail = True
2125
        continue
2126

    
2127
      nresult = all_nvinfo[node].payload
2128

    
2129
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2130
      self._VerifyNodeNetwork(node_i, nresult)
2131
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2132
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2133
                            master_files)
2134
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2135
                           all_drbd_map)
2136
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2137

    
2138
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2139
      self._UpdateNodeInstances(node_i, nresult, nimg)
2140
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2141
      self._UpdateNodeOS(node_i, nresult, nimg)
2142
      if not nimg.os_fail:
2143
        if refos_img is None:
2144
          refos_img = nimg
2145
        self._VerifyNodeOS(node_i, nimg, refos_img)
2146

    
2147
    feedback_fn("* Verifying instance status")
2148
    for instance in instancelist:
2149
      if verbose:
2150
        feedback_fn("* Verifying instance %s" % instance)
2151
      inst_config = instanceinfo[instance]
2152
      self._VerifyInstance(instance, inst_config, node_image)
2153
      inst_nodes_offline = []
2154

    
2155
      pnode = inst_config.primary_node
2156
      pnode_img = node_image[pnode]
2157
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2158
               self.ENODERPC, pnode, "instance %s, connection to"
2159
               " primary node failed", instance)
2160

    
2161
      if pnode_img.offline:
2162
        inst_nodes_offline.append(pnode)
2163

    
2164
      # If the instance is non-redundant we cannot survive losing its primary
2165
      # node, so we are not N+1 compliant. On the other hand we have no disk
2166
      # templates with more than one secondary so that situation is not well
2167
      # supported either.
2168
      # FIXME: does not support file-backed instances
2169
      if not inst_config.secondary_nodes:
2170
        i_non_redundant.append(instance)
2171
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2172
               instance, "instance has multiple secondary nodes: %s",
2173
               utils.CommaJoin(inst_config.secondary_nodes),
2174
               code=self.ETYPE_WARNING)
2175

    
2176
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2177
        i_non_a_balanced.append(instance)
2178

    
2179
      for snode in inst_config.secondary_nodes:
2180
        s_img = node_image[snode]
2181
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2182
                 "instance %s, connection to secondary node failed", instance)
2183

    
2184
        if s_img.offline:
2185
          inst_nodes_offline.append(snode)
2186

    
2187
      # warn that the instance lives on offline nodes
2188
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2189
               "instance lives on offline node(s) %s",
2190
               utils.CommaJoin(inst_nodes_offline))
2191
      # ... or ghost nodes
2192
      for node in inst_config.all_nodes:
2193
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2194
                 "instance lives on ghost node %s", node)
2195

    
2196
    feedback_fn("* Verifying orphan volumes")
2197
    self._VerifyOrphanVolumes(node_vol_should, node_image)
2198

    
2199
    feedback_fn("* Verifying orphan instances")
2200
    self._VerifyOrphanInstances(instancelist, node_image)
2201

    
2202
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2203
      feedback_fn("* Verifying N+1 Memory redundancy")
2204
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2205

    
2206
    feedback_fn("* Other Notes")
2207
    if i_non_redundant:
2208
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2209
                  % len(i_non_redundant))
2210

    
2211
    if i_non_a_balanced:
2212
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2213
                  % len(i_non_a_balanced))
2214

    
2215
    if n_offline:
2216
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2217

    
2218
    if n_drained:
2219
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2220

    
2221
    return not self.bad
2222

    
2223
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2224
    """Analyze the post-hooks' result
2225

2226
    This method analyses the hook result, handles it, and sends some
2227
    nicely-formatted feedback back to the user.
2228

2229
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2230
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2231
    @param hooks_results: the results of the multi-node hooks rpc call
2232
    @param feedback_fn: function used send feedback back to the caller
2233
    @param lu_result: previous Exec result
2234
    @return: the new Exec result, based on the previous result
2235
        and hook results
2236

2237
    """
2238
    # We only really run POST phase hooks, and are only interested in
2239
    # their results
2240
    if phase == constants.HOOKS_PHASE_POST:
2241
      # Used to change hooks' output to proper indentation
2242
      indent_re = re.compile('^', re.M)
2243
      feedback_fn("* Hooks Results")
2244
      assert hooks_results, "invalid result from hooks"
2245

    
2246
      for node_name in hooks_results:
2247
        res = hooks_results[node_name]
2248
        msg = res.fail_msg
2249
        test = msg and not res.offline
2250
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2251
                      "Communication failure in hooks execution: %s", msg)
2252
        if res.offline or msg:
2253
          # No need to investigate payload if node is offline or gave an error.
2254
          # override manually lu_result here as _ErrorIf only
2255
          # overrides self.bad
2256
          lu_result = 1
2257
          continue
2258
        for script, hkr, output in res.payload:
2259
          test = hkr == constants.HKR_FAIL
2260
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2261
                        "Script %s failed, output:", script)
2262
          if test:
2263
            output = indent_re.sub('      ', output)
2264
            feedback_fn("%s" % output)
2265
            lu_result = 0
2266

    
2267
      return lu_result
2268

    
2269

    
2270
class LUVerifyDisks(NoHooksLU):
2271
  """Verifies the cluster disks status.
2272

2273
  """
2274
  REQ_BGL = False
2275

    
2276
  def ExpandNames(self):
2277
    self.needed_locks = {
2278
      locking.LEVEL_NODE: locking.ALL_SET,
2279
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2280
    }
2281
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2282

    
2283
  def Exec(self, feedback_fn):
2284
    """Verify integrity of cluster disks.
2285

2286
    @rtype: tuple of three items
2287
    @return: a tuple of (dict of node-to-node_error, list of instances
2288
        which need activate-disks, dict of instance: (node, volume) for
2289
        missing volumes
2290

2291
    """
2292
    result = res_nodes, res_instances, res_missing = {}, [], {}
2293

    
2294
    vg_name = self.cfg.GetVGName()
2295
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2296
    instances = [self.cfg.GetInstanceInfo(name)
2297
                 for name in self.cfg.GetInstanceList()]
2298

    
2299
    nv_dict = {}
2300
    for inst in instances:
2301
      inst_lvs = {}
2302
      if (not inst.admin_up or
2303
          inst.disk_template not in constants.DTS_NET_MIRROR):
2304
        continue
2305
      inst.MapLVsByNode(inst_lvs)
2306
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2307
      for node, vol_list in inst_lvs.iteritems():
2308
        for vol in vol_list:
2309
          nv_dict[(node, vol)] = inst
2310

    
2311
    if not nv_dict:
2312
      return result
2313

    
2314
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2315

    
2316
    for node in nodes:
2317
      # node_volume
2318
      node_res = node_lvs[node]
2319
      if node_res.offline:
2320
        continue
2321
      msg = node_res.fail_msg
2322
      if msg:
2323
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2324
        res_nodes[node] = msg
2325
        continue
2326

    
2327
      lvs = node_res.payload
2328
      for lv_name, (_, _, lv_online) in lvs.items():
2329
        inst = nv_dict.pop((node, lv_name), None)
2330
        if (not lv_online and inst is not None
2331
            and inst.name not in res_instances):
2332
          res_instances.append(inst.name)
2333

    
2334
    # any leftover items in nv_dict are missing LVs, let's arrange the
2335
    # data better
2336
    for key, inst in nv_dict.iteritems():
2337
      if inst.name not in res_missing:
2338
        res_missing[inst.name] = []
2339
      res_missing[inst.name].append(key)
2340

    
2341
    return result
2342

    
2343

    
2344
class LURepairDiskSizes(NoHooksLU):
2345
  """Verifies the cluster disks sizes.
2346

2347
  """
2348
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2349
  REQ_BGL = False
2350

    
2351
  def ExpandNames(self):
2352
    if self.op.instances:
2353
      self.wanted_names = []
2354
      for name in self.op.instances:
2355
        full_name = _ExpandInstanceName(self.cfg, name)
2356
        self.wanted_names.append(full_name)
2357
      self.needed_locks = {
2358
        locking.LEVEL_NODE: [],
2359
        locking.LEVEL_INSTANCE: self.wanted_names,
2360
        }
2361
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2362
    else:
2363
      self.wanted_names = None
2364
      self.needed_locks = {
2365
        locking.LEVEL_NODE: locking.ALL_SET,
2366
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2367
        }
2368
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2369

    
2370
  def DeclareLocks(self, level):
2371
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2372
      self._LockInstancesNodes(primary_only=True)
2373

    
2374
  def CheckPrereq(self):
2375
    """Check prerequisites.
2376

2377
    This only checks the optional instance list against the existing names.
2378

2379
    """
2380
    if self.wanted_names is None:
2381
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2382

    
2383
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2384
                             in self.wanted_names]
2385

    
2386
  def _EnsureChildSizes(self, disk):
2387
    """Ensure children of the disk have the needed disk size.
2388

2389
    This is valid mainly for DRBD8 and fixes an issue where the
2390
    children have smaller disk size.
2391

2392
    @param disk: an L{ganeti.objects.Disk} object
2393

2394
    """
2395
    if disk.dev_type == constants.LD_DRBD8:
2396
      assert disk.children, "Empty children for DRBD8?"
2397
      fchild = disk.children[0]
2398
      mismatch = fchild.size < disk.size
2399
      if mismatch:
2400
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2401
                     fchild.size, disk.size)
2402
        fchild.size = disk.size
2403

    
2404
      # and we recurse on this child only, not on the metadev
2405
      return self._EnsureChildSizes(fchild) or mismatch
2406
    else:
2407
      return False
2408

    
2409
  def Exec(self, feedback_fn):
2410
    """Verify the size of cluster disks.
2411

2412
    """
2413
    # TODO: check child disks too
2414
    # TODO: check differences in size between primary/secondary nodes
2415
    per_node_disks = {}
2416
    for instance in self.wanted_instances:
2417
      pnode = instance.primary_node
2418
      if pnode not in per_node_disks:
2419
        per_node_disks[pnode] = []
2420
      for idx, disk in enumerate(instance.disks):
2421
        per_node_disks[pnode].append((instance, idx, disk))
2422

    
2423
    changed = []
2424
    for node, dskl in per_node_disks.items():
2425
      newl = [v[2].Copy() for v in dskl]
2426
      for dsk in newl:
2427
        self.cfg.SetDiskID(dsk, node)
2428
      result = self.rpc.call_blockdev_getsizes(node, newl)
2429
      if result.fail_msg:
2430
        self.LogWarning("Failure in blockdev_getsizes call to node"
2431
                        " %s, ignoring", node)
2432
        continue
2433
      if len(result.data) != len(dskl):
2434
        self.LogWarning("Invalid result from node %s, ignoring node results",
2435
                        node)
2436
        continue
2437
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2438
        if size is None:
2439
          self.LogWarning("Disk %d of instance %s did not return size"
2440
                          " information, ignoring", idx, instance.name)
2441
          continue
2442
        if not isinstance(size, (int, long)):
2443
          self.LogWarning("Disk %d of instance %s did not return valid"
2444
                          " size information, ignoring", idx, instance.name)
2445
          continue
2446
        size = size >> 20
2447
        if size != disk.size:
2448
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2449
                       " correcting: recorded %d, actual %d", idx,
2450
                       instance.name, disk.size, size)
2451
          disk.size = size
2452
          self.cfg.Update(instance, feedback_fn)
2453
          changed.append((instance.name, idx, size))
2454
        if self._EnsureChildSizes(disk):
2455
          self.cfg.Update(instance, feedback_fn)
2456
          changed.append((instance.name, idx, disk.size))
2457
    return changed
2458

    
2459

    
2460
class LURenameCluster(LogicalUnit):
2461
  """Rename the cluster.
2462

2463
  """
2464
  HPATH = "cluster-rename"
2465
  HTYPE = constants.HTYPE_CLUSTER
2466
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2467

    
2468
  def BuildHooksEnv(self):
2469
    """Build hooks env.
2470

2471
    """
2472
    env = {
2473
      "OP_TARGET": self.cfg.GetClusterName(),
2474
      "NEW_NAME": self.op.name,
2475
      }
2476
    mn = self.cfg.GetMasterNode()
2477
    all_nodes = self.cfg.GetNodeList()
2478
    return env, [mn], all_nodes
2479

    
2480
  def CheckPrereq(self):
2481
    """Verify that the passed name is a valid one.
2482

2483
    """
2484
    hostname = utils.GetHostInfo(self.op.name)
2485

    
2486
    new_name = hostname.name
2487
    self.ip = new_ip = hostname.ip
2488
    old_name = self.cfg.GetClusterName()
2489
    old_ip = self.cfg.GetMasterIP()
2490
    if new_name == old_name and new_ip == old_ip:
2491
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2492
                                 " cluster has changed",
2493
                                 errors.ECODE_INVAL)
2494
    if new_ip != old_ip:
2495
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2496
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2497
                                   " reachable on the network. Aborting." %
2498
                                   new_ip, errors.ECODE_NOTUNIQUE)
2499

    
2500
    self.op.name = new_name
2501

    
2502
  def Exec(self, feedback_fn):
2503
    """Rename the cluster.
2504

2505
    """
2506
    clustername = self.op.name
2507
    ip = self.ip
2508

    
2509
    # shutdown the master IP
2510
    master = self.cfg.GetMasterNode()
2511
    result = self.rpc.call_node_stop_master(master, False)
2512
    result.Raise("Could not disable the master role")
2513

    
2514
    try:
2515
      cluster = self.cfg.GetClusterInfo()
2516
      cluster.cluster_name = clustername
2517
      cluster.master_ip = ip
2518
      self.cfg.Update(cluster, feedback_fn)
2519

    
2520
      # update the known hosts file
2521
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2522
      node_list = self.cfg.GetNodeList()
2523
      try:
2524
        node_list.remove(master)
2525
      except ValueError:
2526
        pass
2527
      result = self.rpc.call_upload_file(node_list,
2528
                                         constants.SSH_KNOWN_HOSTS_FILE)
2529
      for to_node, to_result in result.iteritems():
2530
        msg = to_result.fail_msg
2531
        if msg:
2532
          msg = ("Copy of file %s to node %s failed: %s" %
2533
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2534
          self.proc.LogWarning(msg)
2535

    
2536
    finally:
2537
      result = self.rpc.call_node_start_master(master, False, False)
2538
      msg = result.fail_msg
2539
      if msg:
2540
        self.LogWarning("Could not re-enable the master role on"
2541
                        " the master, please restart manually: %s", msg)
2542

    
2543

    
2544
class LUSetClusterParams(LogicalUnit):
2545
  """Change the parameters of the cluster.
2546

2547
  """
2548
  HPATH = "cluster-modify"
2549
  HTYPE = constants.HTYPE_CLUSTER
2550
  _OP_PARAMS = [
2551
    ("vg_name", None, _TMaybeString),
2552
    ("enabled_hypervisors", None,
2553
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2554
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2555
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2556
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2557
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2558
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2559
    ("uid_pool", None, _NoType),
2560
    ("add_uids", None, _NoType),
2561
    ("remove_uids", None, _NoType),
2562
    ("maintain_node_health", None, _TMaybeBool),
2563
    ("nicparams", None, _TOr(_TDict, _TNone)),
2564
    ("drbd_helper", None, _TOr(_TString, _TNone)),
2565
    ]
2566
  REQ_BGL = False
2567

    
2568
  def CheckArguments(self):
2569
    """Check parameters
2570

2571
    """
2572
    if self.op.uid_pool:
2573
      uidpool.CheckUidPool(self.op.uid_pool)
2574

    
2575
    if self.op.add_uids:
2576
      uidpool.CheckUidPool(self.op.add_uids)
2577

    
2578
    if self.op.remove_uids:
2579
      uidpool.CheckUidPool(self.op.remove_uids)
2580

    
2581
  def ExpandNames(self):
2582
    # FIXME: in the future maybe other cluster params won't require checking on
2583
    # all nodes to be modified.
2584
    self.needed_locks = {
2585
      locking.LEVEL_NODE: locking.ALL_SET,
2586
    }
2587
    self.share_locks[locking.LEVEL_NODE] = 1
2588

    
2589
  def BuildHooksEnv(self):
2590
    """Build hooks env.
2591

2592
    """
2593
    env = {
2594
      "OP_TARGET": self.cfg.GetClusterName(),
2595
      "NEW_VG_NAME": self.op.vg_name,
2596
      }
2597
    mn = self.cfg.GetMasterNode()
2598
    return env, [mn], [mn]
2599

    
2600
  def CheckPrereq(self):
2601
    """Check prerequisites.
2602

2603
    This checks whether the given params don't conflict and
2604
    if the given volume group is valid.
2605

2606
    """
2607
    if self.op.vg_name is not None and not self.op.vg_name:
2608
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2609
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2610
                                   " instances exist", errors.ECODE_INVAL)
2611

    
2612
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2613
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2614
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2615
                                   " drbd-based instances exist",
2616
                                   errors.ECODE_INVAL)
2617

    
2618
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2619

    
2620
    # if vg_name not None, checks given volume group on all nodes
2621
    if self.op.vg_name:
2622
      vglist = self.rpc.call_vg_list(node_list)
2623
      for node in node_list:
2624
        msg = vglist[node].fail_msg
2625
        if msg:
2626
          # ignoring down node
2627
          self.LogWarning("Error while gathering data on node %s"
2628
                          " (ignoring node): %s", node, msg)
2629
          continue
2630
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2631
                                              self.op.vg_name,
2632
                                              constants.MIN_VG_SIZE)
2633
        if vgstatus:
2634
          raise errors.OpPrereqError("Error on node '%s': %s" %
2635
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2636

    
2637
    if self.op.drbd_helper:
2638
      # checks given drbd helper on all nodes
2639
      helpers = self.rpc.call_drbd_helper(node_list)
2640
      for node in node_list:
2641
        ninfo = self.cfg.GetNodeInfo(node)
2642
        if ninfo.offline:
2643
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2644
          continue
2645
        msg = helpers[node].fail_msg
2646
        if msg:
2647
          raise errors.OpPrereqError("Error checking drbd helper on node"
2648
                                     " '%s': %s" % (node, msg),
2649
                                     errors.ECODE_ENVIRON)
2650
        node_helper = helpers[node].payload
2651
        if node_helper != self.op.drbd_helper:
2652
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2653
                                     (node, node_helper), errors.ECODE_ENVIRON)
2654

    
2655
    self.cluster = cluster = self.cfg.GetClusterInfo()
2656
    # validate params changes
2657
    if self.op.beparams:
2658
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2659
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2660

    
2661
    if self.op.nicparams:
2662
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2663
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2664
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2665
      nic_errors = []
2666

    
2667
      # check all instances for consistency
2668
      for instance in self.cfg.GetAllInstancesInfo().values():
2669
        for nic_idx, nic in enumerate(instance.nics):
2670
          params_copy = copy.deepcopy(nic.nicparams)
2671
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2672

    
2673
          # check parameter syntax
2674
          try:
2675
            objects.NIC.CheckParameterSyntax(params_filled)
2676
          except errors.ConfigurationError, err:
2677
            nic_errors.append("Instance %s, nic/%d: %s" %
2678
                              (instance.name, nic_idx, err))
2679

    
2680
          # if we're moving instances to routed, check that they have an ip
2681
          target_mode = params_filled[constants.NIC_MODE]
2682
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2683
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2684
                              (instance.name, nic_idx))
2685
      if nic_errors:
2686
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2687
                                   "\n".join(nic_errors))
2688

    
2689
    # hypervisor list/parameters
2690
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2691
    if self.op.hvparams:
2692
      for hv_name, hv_dict in self.op.hvparams.items():
2693
        if hv_name not in self.new_hvparams:
2694
          self.new_hvparams[hv_name] = hv_dict
2695
        else:
2696
          self.new_hvparams[hv_name].update(hv_dict)
2697

    
2698
    # os hypervisor parameters
2699
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2700
    if self.op.os_hvp:
2701
      for os_name, hvs in self.op.os_hvp.items():
2702
        if os_name not in self.new_os_hvp:
2703
          self.new_os_hvp[os_name] = hvs
2704
        else:
2705
          for hv_name, hv_dict in hvs.items():
2706
            if hv_name not in self.new_os_hvp[os_name]:
2707
              self.new_os_hvp[os_name][hv_name] = hv_dict
2708
            else:
2709
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2710

    
2711
    # os parameters
2712
    self.new_osp = objects.FillDict(cluster.osparams, {})
2713
    if self.op.osparams:
2714
      for os_name, osp in self.op.osparams.items():
2715
        if os_name not in self.new_osp:
2716
          self.new_osp[os_name] = {}
2717

    
2718
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2719
                                                  use_none=True)
2720

    
2721
        if not self.new_osp[os_name]:
2722
          # we removed all parameters
2723
          del self.new_osp[os_name]
2724
        else:
2725
          # check the parameter validity (remote check)
2726
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2727
                         os_name, self.new_osp[os_name])
2728

    
2729
    # changes to the hypervisor list
2730
    if self.op.enabled_hypervisors is not None:
2731
      self.hv_list = self.op.enabled_hypervisors
2732
      for hv in self.hv_list:
2733
        # if the hypervisor doesn't already exist in the cluster
2734
        # hvparams, we initialize it to empty, and then (in both
2735
        # cases) we make sure to fill the defaults, as we might not
2736
        # have a complete defaults list if the hypervisor wasn't
2737
        # enabled before
2738
        if hv not in new_hvp:
2739
          new_hvp[hv] = {}
2740
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2741
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2742
    else:
2743
      self.hv_list = cluster.enabled_hypervisors
2744

    
2745
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2746
      # either the enabled list has changed, or the parameters have, validate
2747
      for hv_name, hv_params in self.new_hvparams.items():
2748
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2749
            (self.op.enabled_hypervisors and
2750
             hv_name in self.op.enabled_hypervisors)):
2751
          # either this is a new hypervisor, or its parameters have changed
2752
          hv_class = hypervisor.GetHypervisor(hv_name)
2753
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2754
          hv_class.CheckParameterSyntax(hv_params)
2755
          _CheckHVParams(self, node_list, hv_name, hv_params)
2756

    
2757
    if self.op.os_hvp:
2758
      # no need to check any newly-enabled hypervisors, since the
2759
      # defaults have already been checked in the above code-block
2760
      for os_name, os_hvp in self.new_os_hvp.items():
2761
        for hv_name, hv_params in os_hvp.items():
2762
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2763
          # we need to fill in the new os_hvp on top of the actual hv_p
2764
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2765
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2766
          hv_class = hypervisor.GetHypervisor(hv_name)
2767
          hv_class.CheckParameterSyntax(new_osp)
2768
          _CheckHVParams(self, node_list, hv_name, new_osp)
2769

    
2770

    
2771
  def Exec(self, feedback_fn):
2772
    """Change the parameters of the cluster.
2773

2774
    """
2775
    if self.op.vg_name is not None:
2776
      new_volume = self.op.vg_name
2777
      if not new_volume:
2778
        new_volume = None
2779
      if new_volume != self.cfg.GetVGName():
2780
        self.cfg.SetVGName(new_volume)
2781
      else:
2782
        feedback_fn("Cluster LVM configuration already in desired"
2783
                    " state, not changing")
2784
    if self.op.drbd_helper is not None:
2785
      new_helper = self.op.drbd_helper
2786
      if not new_helper:
2787
        new_helper = None
2788
      if new_helper != self.cfg.GetDRBDHelper():
2789
        self.cfg.SetDRBDHelper(new_helper)
2790
      else:
2791
        feedback_fn("Cluster DRBD helper already in desired state,"
2792
                    " not changing")
2793
    if self.op.hvparams:
2794
      self.cluster.hvparams = self.new_hvparams
2795
    if self.op.os_hvp:
2796
      self.cluster.os_hvp = self.new_os_hvp
2797
    if self.op.enabled_hypervisors is not None:
2798
      self.cluster.hvparams = self.new_hvparams
2799
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2800
    if self.op.beparams:
2801
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2802
    if self.op.nicparams:
2803
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2804
    if self.op.osparams:
2805
      self.cluster.osparams = self.new_osp
2806

    
2807
    if self.op.candidate_pool_size is not None:
2808
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2809
      # we need to update the pool size here, otherwise the save will fail
2810
      _AdjustCandidatePool(self, [])
2811

    
2812
    if self.op.maintain_node_health is not None:
2813
      self.cluster.maintain_node_health = self.op.maintain_node_health
2814

    
2815
    if self.op.add_uids is not None:
2816
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2817

    
2818
    if self.op.remove_uids is not None:
2819
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2820

    
2821
    if self.op.uid_pool is not None:
2822
      self.cluster.uid_pool = self.op.uid_pool
2823

    
2824
    self.cfg.Update(self.cluster, feedback_fn)
2825

    
2826

    
2827
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2828
  """Distribute additional files which are part of the cluster configuration.
2829

2830
  ConfigWriter takes care of distributing the config and ssconf files, but
2831
  there are more files which should be distributed to all nodes. This function
2832
  makes sure those are copied.
2833

2834
  @param lu: calling logical unit
2835
  @param additional_nodes: list of nodes not in the config to distribute to
2836

2837
  """
2838
  # 1. Gather target nodes
2839
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2840
  dist_nodes = lu.cfg.GetOnlineNodeList()
2841
  if additional_nodes is not None:
2842
    dist_nodes.extend(additional_nodes)
2843
  if myself.name in dist_nodes:
2844
    dist_nodes.remove(myself.name)
2845

    
2846
  # 2. Gather files to distribute
2847
  dist_files = set([constants.ETC_HOSTS,
2848
                    constants.SSH_KNOWN_HOSTS_FILE,
2849
                    constants.RAPI_CERT_FILE,
2850
                    constants.RAPI_USERS_FILE,
2851
                    constants.CONFD_HMAC_KEY,
2852
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2853
                   ])
2854

    
2855
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2856
  for hv_name in enabled_hypervisors:
2857
    hv_class = hypervisor.GetHypervisor(hv_name)
2858
    dist_files.update(hv_class.GetAncillaryFiles())
2859

    
2860
  # 3. Perform the files upload
2861
  for fname in dist_files:
2862
    if os.path.exists(fname):
2863
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2864
      for to_node, to_result in result.items():
2865
        msg = to_result.fail_msg
2866
        if msg:
2867
          msg = ("Copy of file %s to node %s failed: %s" %
2868
                 (fname, to_node, msg))
2869
          lu.proc.LogWarning(msg)
2870

    
2871

    
2872
class LURedistributeConfig(NoHooksLU):
2873
  """Force the redistribution of cluster configuration.
2874

2875
  This is a very simple LU.
2876

2877
  """
2878
  REQ_BGL = False
2879

    
2880
  def ExpandNames(self):
2881
    self.needed_locks = {
2882
      locking.LEVEL_NODE: locking.ALL_SET,
2883
    }
2884
    self.share_locks[locking.LEVEL_NODE] = 1
2885

    
2886
  def Exec(self, feedback_fn):
2887
    """Redistribute the configuration.
2888

2889
    """
2890
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2891
    _RedistributeAncillaryFiles(self)
2892

    
2893

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

2897
  """
2898
  if not instance.disks or disks is not None and not disks:
2899
    return True
2900

    
2901
  disks = _ExpandCheckDisks(instance, disks)
2902

    
2903
  if not oneshot:
2904
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2905

    
2906
  node = instance.primary_node
2907

    
2908
  for dev in disks:
2909
    lu.cfg.SetDiskID(dev, node)
2910

    
2911
  # TODO: Convert to utils.Retry
2912

    
2913
  retries = 0
2914
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2915
  while True:
2916
    max_time = 0
2917
    done = True
2918
    cumul_degraded = False
2919
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2920
    msg = rstats.fail_msg
2921
    if msg:
2922
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2923
      retries += 1
2924
      if retries >= 10:
2925
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2926
                                 " aborting." % node)
2927
      time.sleep(6)
2928
      continue
2929
    rstats = rstats.payload
2930
    retries = 0
2931
    for i, mstat in enumerate(rstats):
2932
      if mstat is None:
2933
        lu.LogWarning("Can't compute data for node %s/%s",
2934
                           node, disks[i].iv_name)
2935
        continue
2936

    
2937
      cumul_degraded = (cumul_degraded or
2938
                        (mstat.is_degraded and mstat.sync_percent is None))
2939
      if mstat.sync_percent is not None:
2940
        done = False
2941
        if mstat.estimated_time is not None:
2942
          rem_time = ("%s remaining (estimated)" %
2943
                      utils.FormatSeconds(mstat.estimated_time))
2944
          max_time = mstat.estimated_time
2945
        else:
2946
          rem_time = "no time estimate"
2947
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2948
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2949

    
2950
    # if we're done but degraded, let's do a few small retries, to
2951
    # make sure we see a stable and not transient situation; therefore
2952
    # we force restart of the loop
2953
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2954
      logging.info("Degraded disks found, %d retries left", degr_retries)
2955
      degr_retries -= 1
2956
      time.sleep(1)
2957
      continue
2958

    
2959
    if done or oneshot:
2960
      break
2961

    
2962
    time.sleep(min(60, max_time))
2963

    
2964
  if done:
2965
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2966
  return not cumul_degraded
2967

    
2968

    
2969
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2970
  """Check that mirrors are not degraded.
2971

2972
  The ldisk parameter, if True, will change the test from the
2973
  is_degraded attribute (which represents overall non-ok status for
2974
  the device(s)) to the ldisk (representing the local storage status).
2975

2976
  """
2977
  lu.cfg.SetDiskID(dev, node)
2978

    
2979
  result = True
2980

    
2981
  if on_primary or dev.AssembleOnSecondary():
2982
    rstats = lu.rpc.call_blockdev_find(node, dev)
2983
    msg = rstats.fail_msg
2984
    if msg:
2985
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2986
      result = False
2987
    elif not rstats.payload:
2988
      lu.LogWarning("Can't find disk on node %s", node)
2989
      result = False
2990
    else:
2991
      if ldisk:
2992
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2993
      else:
2994
        result = result and not rstats.payload.is_degraded
2995

    
2996
  if dev.children:
2997
    for child in dev.children:
2998
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2999

    
3000
  return result
3001

    
3002

    
3003
class LUDiagnoseOS(NoHooksLU):
3004
  """Logical unit for OS diagnose/query.
3005

3006
  """
3007
  _OP_PARAMS = [
3008
    _POutputFields,
3009
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3010
    ]
3011
  REQ_BGL = False
3012
  _FIELDS_STATIC = utils.FieldSet()
3013
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3014
                                   "parameters", "api_versions")
3015

    
3016
  def CheckArguments(self):
3017
    if self.op.names:
3018
      raise errors.OpPrereqError("Selective OS query not supported",
3019
                                 errors.ECODE_INVAL)
3020

    
3021
    _CheckOutputFields(static=self._FIELDS_STATIC,
3022
                       dynamic=self._FIELDS_DYNAMIC,
3023
                       selected=self.op.output_fields)
3024

    
3025
  def ExpandNames(self):
3026
    # Lock all nodes, in shared mode
3027
    # Temporary removal of locks, should be reverted later
3028
    # TODO: reintroduce locks when they are lighter-weight
3029
    self.needed_locks = {}
3030
    #self.share_locks[locking.LEVEL_NODE] = 1
3031
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3032

    
3033
  @staticmethod
3034
  def _DiagnoseByOS(rlist):
3035
    """Remaps a per-node return list into an a per-os per-node dictionary
3036

3037
    @param rlist: a map with node names as keys and OS objects as values
3038

3039
    @rtype: dict
3040
    @return: a dictionary with osnames as keys and as value another
3041
        map, with nodes as keys and tuples of (path, status, diagnose,
3042
        variants, parameters, api_versions) as values, eg::
3043

3044
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3045
                                     (/srv/..., False, "invalid api")],
3046
                           "node2": [(/srv/..., True, "", [], [])]}
3047
          }
3048

3049
    """
3050
    all_os = {}
3051
    # we build here the list of nodes that didn't fail the RPC (at RPC
3052
    # level), so that nodes with a non-responding node daemon don't
3053
    # make all OSes invalid
3054
    good_nodes = [node_name for node_name in rlist
3055
                  if not rlist[node_name].fail_msg]
3056
    for node_name, nr in rlist.items():
3057
      if nr.fail_msg or not nr.payload:
3058
        continue
3059
      for (name, path, status, diagnose, variants,
3060
           params, api_versions) in nr.payload:
3061
        if name not in all_os:
3062
          # build a list of nodes for this os containing empty lists
3063
          # for each node in node_list
3064
          all_os[name] = {}
3065
          for nname in good_nodes:
3066
            all_os[name][nname] = []
3067
        # convert params from [name, help] to (name, help)
3068
        params = [tuple(v) for v in params]
3069
        all_os[name][node_name].append((path, status, diagnose,
3070
                                        variants, params, api_versions))
3071
    return all_os
3072

    
3073
  def Exec(self, feedback_fn):
3074
    """Compute the list of OSes.
3075

3076
    """
3077
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3078
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3079
    pol = self._DiagnoseByOS(node_data)
3080
    output = []
3081

    
3082
    for os_name, os_data in pol.items():
3083
      row = []
3084
      valid = True
3085
      (variants, params, api_versions) = null_state = (set(), set(), set())
3086
      for idx, osl in enumerate(os_data.values()):
3087
        valid = bool(valid and osl and osl[0][1])
3088
        if not valid:
3089
          (variants, params, api_versions) = null_state
3090
          break
3091
        node_variants, node_params, node_api = osl[0][3:6]
3092
        if idx == 0: # first entry
3093
          variants = set(node_variants)
3094
          params = set(node_params)
3095
          api_versions = set(node_api)
3096
        else: # keep consistency
3097
          variants.intersection_update(node_variants)
3098
          params.intersection_update(node_params)
3099
          api_versions.intersection_update(node_api)
3100

    
3101
      for field in self.op.output_fields:
3102
        if field == "name":
3103
          val = os_name
3104
        elif field == "valid":
3105
          val = valid
3106
        elif field == "node_status":
3107
          # this is just a copy of the dict
3108
          val = {}
3109
          for node_name, nos_list in os_data.items():
3110
            val[node_name] = nos_list
3111
        elif field == "variants":
3112
          val = list(variants)
3113
        elif field == "parameters":
3114
          val = list(params)
3115
        elif field == "api_versions":
3116
          val = list(api_versions)
3117
        else:
3118
          raise errors.ParameterError(field)
3119
        row.append(val)
3120
      output.append(row)
3121

    
3122
    return output
3123

    
3124

    
3125
class LURemoveNode(LogicalUnit):
3126
  """Logical unit for removing a node.
3127

3128
  """
3129
  HPATH = "node-remove"
3130
  HTYPE = constants.HTYPE_NODE
3131
  _OP_PARAMS = [
3132
    _PNodeName,
3133
    ]
3134

    
3135
  def BuildHooksEnv(self):
3136
    """Build hooks env.
3137

3138
    This doesn't run on the target node in the pre phase as a failed
3139
    node would then be impossible to remove.
3140

3141
    """
3142
    env = {
3143
      "OP_TARGET": self.op.node_name,
3144
      "NODE_NAME": self.op.node_name,
3145
      }
3146
    all_nodes = self.cfg.GetNodeList()
3147
    try:
3148
      all_nodes.remove(self.op.node_name)
3149
    except ValueError:
3150
      logging.warning("Node %s which is about to be removed not found"
3151
                      " in the all nodes list", self.op.node_name)
3152
    return env, all_nodes, all_nodes
3153

    
3154
  def CheckPrereq(self):
3155
    """Check prerequisites.
3156

3157
    This checks:
3158
     - the node exists in the configuration
3159
     - it does not have primary or secondary instances
3160
     - it's not the master
3161

3162
    Any errors are signaled by raising errors.OpPrereqError.
3163

3164
    """
3165
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3166
    node = self.cfg.GetNodeInfo(self.op.node_name)
3167
    assert node is not None
3168

    
3169
    instance_list = self.cfg.GetInstanceList()
3170

    
3171
    masternode = self.cfg.GetMasterNode()
3172
    if node.name == masternode:
3173
      raise errors.OpPrereqError("Node is the master node,"
3174
                                 " you need to failover first.",
3175
                                 errors.ECODE_INVAL)
3176

    
3177
    for instance_name in instance_list:
3178
      instance = self.cfg.GetInstanceInfo(instance_name)
3179
      if node.name in instance.all_nodes:
3180
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3181
                                   " please remove first." % instance_name,
3182
                                   errors.ECODE_INVAL)
3183
    self.op.node_name = node.name
3184
    self.node = node
3185

    
3186
  def Exec(self, feedback_fn):
3187
    """Removes the node from the cluster.
3188

3189
    """
3190
    node = self.node
3191
    logging.info("Stopping the node daemon and removing configs from node %s",
3192
                 node.name)
3193

    
3194
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3195

    
3196
    # Promote nodes to master candidate as needed
3197
    _AdjustCandidatePool(self, exceptions=[node.name])
3198
    self.context.RemoveNode(node.name)
3199

    
3200
    # Run post hooks on the node before it's removed
3201
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3202
    try:
3203
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3204
    except:
3205
      # pylint: disable-msg=W0702
3206
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3207

    
3208
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3209
    msg = result.fail_msg
3210
    if msg:
3211
      self.LogWarning("Errors encountered on the remote node while leaving"
3212
                      " the cluster: %s", msg)
3213

    
3214
    # Remove node from our /etc/hosts
3215
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3216
      # FIXME: this should be done via an rpc call to node daemon
3217
      utils.RemoveHostFromEtcHosts(node.name)
3218
      _RedistributeAncillaryFiles(self)
3219

    
3220

    
3221
class LUQueryNodes(NoHooksLU):
3222
  """Logical unit for querying nodes.
3223

3224
  """
3225
  # pylint: disable-msg=W0142
3226
  _OP_PARAMS = [
3227
    _POutputFields,
3228
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3229
    ("use_locking", False, _TBool),
3230
    ]
3231
  REQ_BGL = False
3232

    
3233
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3234
                    "master_candidate", "offline", "drained"]
3235

    
3236
  _FIELDS_DYNAMIC = utils.FieldSet(
3237
    "dtotal", "dfree",
3238
    "mtotal", "mnode", "mfree",
3239
    "bootid",
3240
    "ctotal", "cnodes", "csockets",
3241
    )
3242

    
3243
  _FIELDS_STATIC = utils.FieldSet(*[
3244
    "pinst_cnt", "sinst_cnt",
3245
    "pinst_list", "sinst_list",
3246
    "pip", "sip", "tags",
3247
    "master",
3248
    "role"] + _SIMPLE_FIELDS
3249
    )
3250

    
3251
  def CheckArguments(self):
3252
    _CheckOutputFields(static=self._FIELDS_STATIC,
3253
                       dynamic=self._FIELDS_DYNAMIC,
3254
                       selected=self.op.output_fields)
3255

    
3256
  def ExpandNames(self):
3257
    self.needed_locks = {}
3258
    self.share_locks[locking.LEVEL_NODE] = 1
3259

    
3260
    if self.op.names:
3261
      self.wanted = _GetWantedNodes(self, self.op.names)
3262
    else:
3263
      self.wanted = locking.ALL_SET
3264

    
3265
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3266
    self.do_locking = self.do_node_query and self.op.use_locking
3267
    if self.do_locking:
3268
      # if we don't request only static fields, we need to lock the nodes
3269
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3270

    
3271
  def Exec(self, feedback_fn):
3272
    """Computes the list of nodes and their attributes.
3273

3274
    """
3275
    all_info = self.cfg.GetAllNodesInfo()
3276
    if self.do_locking:
3277
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3278
    elif self.wanted != locking.ALL_SET:
3279
      nodenames = self.wanted
3280
      missing = set(nodenames).difference(all_info.keys())
3281
      if missing:
3282
        raise errors.OpExecError(
3283
          "Some nodes were removed before retrieving their data: %s" % missing)
3284
    else:
3285
      nodenames = all_info.keys()
3286

    
3287
    nodenames = utils.NiceSort(nodenames)
3288
    nodelist = [all_info[name] for name in nodenames]
3289

    
3290
    # begin data gathering
3291

    
3292
    if self.do_node_query:
3293
      live_data = {}
3294
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3295
                                          self.cfg.GetHypervisorType())
3296
      for name in nodenames:
3297
        nodeinfo = node_data[name]
3298
        if not nodeinfo.fail_msg and nodeinfo.payload:
3299
          nodeinfo = nodeinfo.payload
3300
          fn = utils.TryConvert
3301
          live_data[name] = {
3302
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3303
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3304
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3305
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3306
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3307
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3308
            "bootid": nodeinfo.get('bootid', None),
3309
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3310
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3311
            }
3312
        else:
3313
          live_data[name] = {}
3314
    else:
3315
      live_data = dict.fromkeys(nodenames, {})
3316

    
3317
    node_to_primary = dict([(name, set()) for name in nodenames])
3318
    node_to_secondary = dict([(name, set()) for name in nodenames])
3319

    
3320
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3321
                             "sinst_cnt", "sinst_list"))
3322
    if inst_fields & frozenset(self.op.output_fields):
3323
      inst_data = self.cfg.GetAllInstancesInfo()
3324

    
3325
      for inst in inst_data.values():
3326
        if inst.primary_node in node_to_primary:
3327
          node_to_primary[inst.primary_node].add(inst.name)
3328
        for secnode in inst.secondary_nodes:
3329
          if secnode in node_to_secondary:
3330
            node_to_secondary[secnode].add(inst.name)
3331

    
3332
    master_node = self.cfg.GetMasterNode()
3333

    
3334
    # end data gathering
3335

    
3336
    output = []
3337
    for node in nodelist:
3338
      node_output = []
3339
      for field in self.op.output_fields:
3340
        if field in self._SIMPLE_FIELDS:
3341
          val = getattr(node, field)
3342
        elif field == "pinst_list":
3343
          val = list(node_to_primary[node.name])
3344
        elif field == "sinst_list":
3345
          val = list(node_to_secondary[node.name])
3346
        elif field == "pinst_cnt":
3347
          val = len(node_to_primary[node.name])
3348
        elif field == "sinst_cnt":
3349
          val = len(node_to_secondary[node.name])
3350
        elif field == "pip":
3351
          val = node.primary_ip
3352
        elif field == "sip":
3353
          val = node.secondary_ip
3354
        elif field == "tags":
3355
          val = list(node.GetTags())
3356
        elif field == "master":
3357
          val = node.name == master_node
3358
        elif self._FIELDS_DYNAMIC.Matches(field):
3359
          val = live_data[node.name].get(field, None)
3360
        elif field == "role":
3361
          if node.name == master_node:
3362
            val = "M"
3363
          elif node.master_candidate:
3364
            val = "C"
3365
          elif node.drained:
3366
            val = "D"
3367
          elif node.offline:
3368
            val = "O"
3369
          else:
3370
            val = "R"
3371
        else:
3372
          raise errors.ParameterError(field)
3373
        node_output.append(val)
3374
      output.append(node_output)
3375

    
3376
    return output
3377

    
3378

    
3379
class LUQueryNodeVolumes(NoHooksLU):
3380
  """Logical unit for getting volumes on node(s).
3381

3382
  """
3383
  _OP_PARAMS = [
3384
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3385
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3386
    ]
3387
  REQ_BGL = False
3388
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3389
  _FIELDS_STATIC = utils.FieldSet("node")
3390

    
3391
  def CheckArguments(self):
3392
    _CheckOutputFields(static=self._FIELDS_STATIC,
3393
                       dynamic=self._FIELDS_DYNAMIC,
3394
                       selected=self.op.output_fields)
3395

    
3396
  def ExpandNames(self):
3397
    self.needed_locks = {}
3398
    self.share_locks[locking.LEVEL_NODE] = 1
3399
    if not self.op.nodes:
3400
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3401
    else:
3402
      self.needed_locks[locking.LEVEL_NODE] = \
3403
        _GetWantedNodes(self, self.op.nodes)
3404

    
3405
  def Exec(self, feedback_fn):
3406
    """Computes the list of nodes and their attributes.
3407

3408
    """
3409
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3410
    volumes = self.rpc.call_node_volumes(nodenames)
3411

    
3412
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3413
             in self.cfg.GetInstanceList()]
3414

    
3415
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3416

    
3417
    output = []
3418
    for node in nodenames:
3419
      nresult = volumes[node]
3420
      if nresult.offline:
3421
        continue
3422
      msg = nresult.fail_msg
3423
      if msg:
3424
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3425
        continue
3426

    
3427
      node_vols = nresult.payload[:]
3428
      node_vols.sort(key=lambda vol: vol['dev'])
3429

    
3430
      for vol in node_vols:
3431
        node_output = []
3432
        for field in self.op.output_fields:
3433
          if field == "node":
3434
            val = node
3435
          elif field == "phys":
3436
            val = vol['dev']
3437
          elif field == "vg":
3438
            val = vol['vg']
3439
          elif field == "name":
3440
            val = vol['name']
3441
          elif field == "size":
3442
            val = int(float(vol['size']))
3443
          elif field == "instance":
3444
            for inst in ilist:
3445
              if node not in lv_by_node[inst]:
3446
                continue
3447
              if vol['name'] in lv_by_node[inst][node]:
3448
                val = inst.name
3449
                break
3450
            else:
3451
              val = '-'
3452
          else:
3453
            raise errors.ParameterError(field)
3454
          node_output.append(str(val))
3455

    
3456
        output.append(node_output)
3457

    
3458
    return output
3459

    
3460

    
3461
class LUQueryNodeStorage(NoHooksLU):
3462
  """Logical unit for getting information on storage units on node(s).
3463

3464
  """
3465
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3466
  _OP_PARAMS = [
3467
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3468
    ("storage_type", _NoDefault, _CheckStorageType),
3469
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3470
    ("name", None, _TMaybeString),
3471
    ]
3472
  REQ_BGL = False
3473

    
3474
  def CheckArguments(self):
3475
    _CheckOutputFields(static=self._FIELDS_STATIC,
3476
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3477
                       selected=self.op.output_fields)
3478

    
3479
  def ExpandNames(self):
3480
    self.needed_locks = {}
3481
    self.share_locks[locking.LEVEL_NODE] = 1
3482

    
3483
    if self.op.nodes:
3484
      self.needed_locks[locking.LEVEL_NODE] = \
3485
        _GetWantedNodes(self, self.op.nodes)
3486
    else:
3487
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3488

    
3489
  def Exec(self, feedback_fn):
3490
    """Computes the list of nodes and their attributes.
3491

3492
    """
3493
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3494

    
3495
    # Always get name to sort by
3496
    if constants.SF_NAME in self.op.output_fields:
3497
      fields = self.op.output_fields[:]
3498
    else:
3499
      fields = [constants.SF_NAME] + self.op.output_fields
3500

    
3501
    # Never ask for node or type as it's only known to the LU
3502
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3503
      while extra in fields:
3504
        fields.remove(extra)
3505

    
3506
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3507
    name_idx = field_idx[constants.SF_NAME]
3508

    
3509
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3510
    data = self.rpc.call_storage_list(self.nodes,
3511
                                      self.op.storage_type, st_args,
3512
                                      self.op.name, fields)
3513

    
3514
    result = []
3515

    
3516
    for node in utils.NiceSort(self.nodes):
3517
      nresult = data[node]
3518
      if nresult.offline:
3519
        continue
3520

    
3521
      msg = nresult.fail_msg
3522
      if msg:
3523
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3524
        continue
3525

    
3526
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3527

    
3528
      for name in utils.NiceSort(rows.keys()):
3529
        row = rows[name]
3530

    
3531
        out = []
3532

    
3533
        for field in self.op.output_fields:
3534
          if field == constants.SF_NODE:
3535
            val = node
3536
          elif field == constants.SF_TYPE:
3537
            val = self.op.storage_type
3538
          elif field in field_idx:
3539
            val = row[field_idx[field]]
3540
          else:
3541
            raise errors.ParameterError(field)
3542

    
3543
          out.append(val)
3544

    
3545
        result.append(out)
3546

    
3547
    return result
3548

    
3549

    
3550
class LUModifyNodeStorage(NoHooksLU):
3551
  """Logical unit for modifying a storage volume on a node.
3552

3553
  """
3554
  _OP_PARAMS = [
3555
    _PNodeName,
3556
    ("storage_type", _NoDefault, _CheckStorageType),
3557
    ("name", _NoDefault, _TNonEmptyString),
3558
    ("changes", _NoDefault, _TDict),
3559
    ]
3560
  REQ_BGL = False
3561

    
3562
  def CheckArguments(self):
3563
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3564

    
3565
    storage_type = self.op.storage_type
3566

    
3567
    try:
3568
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3569
    except KeyError:
3570
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3571
                                 " modified" % storage_type,
3572
                                 errors.ECODE_INVAL)
3573

    
3574
    diff = set(self.op.changes.keys()) - modifiable
3575
    if diff:
3576
      raise errors.OpPrereqError("The following fields can not be modified for"
3577
                                 " storage units of type '%s': %r" %
3578
                                 (storage_type, list(diff)),
3579
                                 errors.ECODE_INVAL)
3580

    
3581
  def ExpandNames(self):
3582
    self.needed_locks = {
3583
      locking.LEVEL_NODE: self.op.node_name,
3584
      }
3585

    
3586
  def Exec(self, feedback_fn):
3587
    """Computes the list of nodes and their attributes.
3588

3589
    """
3590
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3591
    result = self.rpc.call_storage_modify(self.op.node_name,
3592
                                          self.op.storage_type, st_args,
3593
                                          self.op.name, self.op.changes)
3594
    result.Raise("Failed to modify storage unit '%s' on %s" %
3595
                 (self.op.name, self.op.node_name))
3596

    
3597

    
3598
class LUAddNode(LogicalUnit):
3599
  """Logical unit for adding node to the cluster.
3600

3601
  """
3602
  HPATH = "node-add"
3603
  HTYPE = constants.HTYPE_NODE
3604
  _OP_PARAMS = [
3605
    _PNodeName,
3606
    ("primary_ip", None, _NoType),
3607
    ("secondary_ip", None, _TMaybeString),
3608
    ("readd", False, _TBool),
3609
    ]
3610

    
3611
  def CheckArguments(self):
3612
    # validate/normalize the node name
3613
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3614

    
3615
  def BuildHooksEnv(self):
3616
    """Build hooks env.
3617

3618
    This will run on all nodes before, and on all nodes + the new node after.
3619

3620
    """
3621
    env = {
3622
      "OP_TARGET": self.op.node_name,
3623
      "NODE_NAME": self.op.node_name,
3624
      "NODE_PIP": self.op.primary_ip,
3625
      "NODE_SIP": self.op.secondary_ip,
3626
      }
3627
    nodes_0 = self.cfg.GetNodeList()
3628
    nodes_1 = nodes_0 + [self.op.node_name, ]
3629
    return env, nodes_0, nodes_1
3630

    
3631
  def CheckPrereq(self):
3632
    """Check prerequisites.
3633

3634
    This checks:
3635
     - the new node is not already in the config
3636
     - it is resolvable
3637
     - its parameters (single/dual homed) matches the cluster
3638

3639
    Any errors are signaled by raising errors.OpPrereqError.
3640

3641
    """
3642
    node_name = self.op.node_name
3643
    cfg = self.cfg
3644

    
3645
    dns_data = utils.GetHostInfo(node_name)
3646

    
3647
    node = dns_data.name
3648
    primary_ip = self.op.primary_ip = dns_data.ip
3649
    if self.op.secondary_ip is None:
3650
      self.op.secondary_ip = primary_ip
3651
    if not utils.IsValidIP4(self.op.secondary_ip):
3652
      raise errors.OpPrereqError("Invalid secondary IP given",
3653
                                 errors.ECODE_INVAL)
3654
    secondary_ip = self.op.secondary_ip
3655

    
3656
    node_list = cfg.GetNodeList()
3657
    if not self.op.readd and node in node_list:
3658
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3659
                                 node, errors.ECODE_EXISTS)
3660
    elif self.op.readd and node not in node_list:
3661
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3662
                                 errors.ECODE_NOENT)
3663

    
3664
    self.changed_primary_ip = False
3665

    
3666
    for existing_node_name in node_list:
3667
      existing_node = cfg.GetNodeInfo(existing_node_name)
3668

    
3669
      if self.op.readd and node == existing_node_name:
3670
        if existing_node.secondary_ip != secondary_ip:
3671
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3672
                                     " address configuration as before",
3673
                                     errors.ECODE_INVAL)
3674
        if existing_node.primary_ip != primary_ip:
3675
          self.changed_primary_ip = True
3676

    
3677
        continue
3678

    
3679
      if (existing_node.primary_ip == primary_ip or
3680
          existing_node.secondary_ip == primary_ip or
3681
          existing_node.primary_ip == secondary_ip or
3682
          existing_node.secondary_ip == secondary_ip):
3683
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3684
                                   " existing node %s" % existing_node.name,
3685
                                   errors.ECODE_NOTUNIQUE)
3686

    
3687
    # check that the type of the node (single versus dual homed) is the
3688
    # same as for the master
3689
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3690
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3691
    newbie_singlehomed = secondary_ip == primary_ip
3692
    if master_singlehomed != newbie_singlehomed:
3693
      if master_singlehomed:
3694
        raise errors.OpPrereqError("The master has no private ip but the"
3695
                                   " new node has one",
3696
                                   errors.ECODE_INVAL)
3697
      else:
3698
        raise errors.OpPrereqError("The master has a private ip but the"
3699
                                   " new node doesn't have one",
3700
                                   errors.ECODE_INVAL)
3701

    
3702
    # checks reachability
3703
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3704
      raise errors.OpPrereqError("Node not reachable by ping",
3705
                                 errors.ECODE_ENVIRON)
3706

    
3707
    if not newbie_singlehomed:
3708
      # check reachability from my secondary ip to newbie's secondary ip
3709
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3710
                           source=myself.secondary_ip):
3711
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3712
                                   " based ping to noded port",
3713
                                   errors.ECODE_ENVIRON)
3714

    
3715
    if self.op.readd:
3716
      exceptions = [node]
3717
    else:
3718
      exceptions = []
3719

    
3720
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3721

    
3722
    if self.op.readd:
3723
      self.new_node = self.cfg.GetNodeInfo(node)
3724
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3725
    else:
3726
      self.new_node = objects.Node(name=node,
3727
                                   primary_ip=primary_ip,
3728
                                   secondary_ip=secondary_ip,
3729
                                   master_candidate=self.master_candidate,
3730
                                   offline=False, drained=False)
3731

    
3732
  def Exec(self, feedback_fn):
3733
    """Adds the new node to the cluster.
3734

3735
    """
3736
    new_node = self.new_node
3737
    node = new_node.name
3738

    
3739
    # for re-adds, reset the offline/drained/master-candidate flags;
3740
    # we need to reset here, otherwise offline would prevent RPC calls
3741
    # later in the procedure; this also means that if the re-add
3742
    # fails, we are left with a non-offlined, broken node
3743
    if self.op.readd:
3744
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3745
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3746
      # if we demote the node, we do cleanup later in the procedure
3747
      new_node.master_candidate = self.master_candidate
3748
      if self.changed_primary_ip:
3749
        new_node.primary_ip = self.op.primary_ip
3750

    
3751
    # notify the user about any possible mc promotion
3752
    if new_node.master_candidate:
3753
      self.LogInfo("Node will be a master candidate")
3754

    
3755
    # check connectivity
3756
    result = self.rpc.call_version([node])[node]
3757
    result.Raise("Can't get version information from node %s" % node)
3758
    if constants.PROTOCOL_VERSION == result.payload:
3759
      logging.info("Communication to node %s fine, sw version %s match",
3760
                   node, result.payload)
3761
    else:
3762
      raise errors.OpExecError("Version mismatch master version %s,"
3763
                               " node version %s" %
3764
                               (constants.PROTOCOL_VERSION, result.payload))
3765

    
3766
    # setup ssh on node
3767
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3768
      logging.info("Copy ssh key to node %s", node)
3769
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3770
      keyarray = []
3771
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3772
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3773
                  priv_key, pub_key]
3774

    
3775
      for i in keyfiles:
3776
        keyarray.append(utils.ReadFile(i))
3777

    
3778
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3779
                                      keyarray[2], keyarray[3], keyarray[4],
3780
                                      keyarray[5])
3781
      result.Raise("Cannot transfer ssh keys to the new node")
3782

    
3783
    # Add node to our /etc/hosts, and add key to known_hosts
3784
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3785
      # FIXME: this should be done via an rpc call to node daemon
3786
      utils.AddHostToEtcHosts(new_node.name)
3787

    
3788
    if new_node.secondary_ip != new_node.primary_ip:
3789
      result = self.rpc.call_node_has_ip_address(new_node.name,
3790
                                                 new_node.secondary_ip)
3791
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3792
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3793
      if not result.payload:
3794
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3795
                                 " you gave (%s). Please fix and re-run this"
3796
                                 " command." % new_node.secondary_ip)
3797

    
3798
    node_verify_list = [self.cfg.GetMasterNode()]
3799
    node_verify_param = {
3800
      constants.NV_NODELIST: [node],
3801
      # TODO: do a node-net-test as well?
3802
    }
3803

    
3804
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3805
                                       self.cfg.GetClusterName())
3806
    for verifier in node_verify_list:
3807
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3808
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3809
      if nl_payload:
3810
        for failed in nl_payload:
3811
          feedback_fn("ssh/hostname verification failed"
3812
                      " (checking from %s): %s" %
3813
                      (verifier, nl_payload[failed]))
3814
        raise errors.OpExecError("ssh/hostname verification failed.")
3815

    
3816
    if self.op.readd:
3817
      _RedistributeAncillaryFiles(self)
3818
      self.context.ReaddNode(new_node)
3819
      # make sure we redistribute the config
3820
      self.cfg.Update(new_node, feedback_fn)
3821
      # and make sure the new node will not have old files around
3822
      if not new_node.master_candidate:
3823
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3824
        msg = result.fail_msg
3825
        if msg:
3826
          self.LogWarning("Node failed to demote itself from master"
3827
                          " candidate status: %s" % msg)
3828
    else:
3829
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3830
      self.context.AddNode(new_node, self.proc.GetECId())
3831

    
3832

    
3833
class LUSetNodeParams(LogicalUnit):
3834
  """Modifies the parameters of a node.
3835

3836
  """
3837
  HPATH = "node-modify"
3838
  HTYPE = constants.HTYPE_NODE
3839
  _OP_PARAMS = [
3840
    _PNodeName,
3841
    ("master_candidate", None, _TMaybeBool),
3842
    ("offline", None, _TMaybeBool),
3843
    ("drained", None, _TMaybeBool),
3844
    ("auto_promote", False, _TBool),
3845
    _PForce,
3846
    ]
3847
  REQ_BGL = False
3848

    
3849
  def CheckArguments(self):
3850
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3851
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3852
    if all_mods.count(None) == 3:
3853
      raise errors.OpPrereqError("Please pass at least one modification",
3854
                                 errors.ECODE_INVAL)
3855
    if all_mods.count(True) > 1:
3856
      raise errors.OpPrereqError("Can't set the node into more than one"
3857
                                 " state at the same time",
3858
                                 errors.ECODE_INVAL)
3859

    
3860
    # Boolean value that tells us whether we're offlining or draining the node
3861
    self.offline_or_drain = (self.op.offline == True or
3862
                             self.op.drained == True)
3863
    self.deoffline_or_drain = (self.op.offline == False or
3864
                               self.op.drained == False)
3865
    self.might_demote = (self.op.master_candidate == False or
3866
                         self.offline_or_drain)
3867

    
3868
    self.lock_all = self.op.auto_promote and self.might_demote
3869

    
3870

    
3871
  def ExpandNames(self):
3872
    if self.lock_all:
3873
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3874
    else:
3875
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3876

    
3877
  def BuildHooksEnv(self):
3878
    """Build hooks env.
3879

3880
    This runs on the master node.
3881

3882
    """
3883
    env = {
3884
      "OP_TARGET": self.op.node_name,
3885
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3886
      "OFFLINE": str(self.op.offline),
3887
      "DRAINED": str(self.op.drained),
3888
      }
3889
    nl = [self.cfg.GetMasterNode(),
3890
          self.op.node_name]
3891
    return env, nl, nl
3892

    
3893
  def CheckPrereq(self):
3894
    """Check prerequisites.
3895

3896
    This only checks the instance list against the existing names.
3897

3898
    """
3899
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3900

    
3901
    if (self.op.master_candidate is not None or
3902
        self.op.drained is not None or
3903
        self.op.offline is not None):
3904
      # we can't change the master's node flags
3905
      if self.op.node_name == self.cfg.GetMasterNode():
3906
        raise errors.OpPrereqError("The master role can be changed"
3907
                                   " only via masterfailover",
3908
                                   errors.ECODE_INVAL)
3909

    
3910

    
3911
    if node.master_candidate and self.might_demote and not self.lock_all:
3912
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3913
      # check if after removing the current node, we're missing master
3914
      # candidates
3915
      (mc_remaining, mc_should, _) = \
3916
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3917
      if mc_remaining < mc_should:
3918
        raise errors.OpPrereqError("Not enough master candidates, please"
3919
                                   " pass auto_promote to allow promotion",
3920
                                   errors.ECODE_INVAL)
3921

    
3922
    if (self.op.master_candidate == True and
3923
        ((node.offline and not self.op.offline == False) or
3924
         (node.drained and not self.op.drained == False))):
3925
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3926
                                 " to master_candidate" % node.name,
3927
                                 errors.ECODE_INVAL)
3928

    
3929
    # If we're being deofflined/drained, we'll MC ourself if needed
3930
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3931
        self.op.master_candidate == True and not node.master_candidate):
3932
      self.op.master_candidate = _DecideSelfPromotion(self)
3933
      if self.op.master_candidate:
3934
        self.LogInfo("Autopromoting node to master candidate")
3935

    
3936
    return
3937

    
3938
  def Exec(self, feedback_fn):
3939
    """Modifies a node.
3940

3941
    """
3942
    node = self.node
3943

    
3944
    result = []
3945
    changed_mc = False
3946

    
3947
    if self.op.offline is not None:
3948
      node.offline = self.op.offline
3949
      result.append(("offline", str(self.op.offline)))
3950
      if self.op.offline == True:
3951
        if node.master_candidate:
3952
          node.master_candidate = False
3953
          changed_mc = True
3954
          result.append(("master_candidate", "auto-demotion due to offline"))
3955
        if node.drained:
3956
          node.drained = False
3957
          result.append(("drained", "clear drained status due to offline"))
3958

    
3959
    if self.op.master_candidate is not None:
3960
      node.master_candidate = self.op.master_candidate
3961
      changed_mc = True
3962
      result.append(("master_candidate", str(self.op.master_candidate)))
3963
      if self.op.master_candidate == False:
3964
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3965
        msg = rrc.fail_msg
3966
        if msg:
3967
          self.LogWarning("Node failed to demote itself: %s" % msg)
3968

    
3969
    if self.op.drained is not None:
3970
      node.drained = self.op.drained
3971
      result.append(("drained", str(self.op.drained)))
3972
      if self.op.drained == True:
3973
        if node.master_candidate:
3974
          node.master_candidate = False
3975
          changed_mc = True
3976
          result.append(("master_candidate", "auto-demotion due to drain"))
3977
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3978
          msg = rrc.fail_msg
3979
          if msg:
3980
            self.LogWarning("Node failed to demote itself: %s" % msg)
3981
        if node.offline:
3982
          node.offline = False
3983
          result.append(("offline", "clear offline status due to drain"))
3984

    
3985
    # we locked all nodes, we adjust the CP before updating this node
3986
    if self.lock_all:
3987
      _AdjustCandidatePool(self, [node.name])
3988

    
3989
    # this will trigger configuration file update, if needed
3990
    self.cfg.Update(node, feedback_fn)
3991

    
3992
    # this will trigger job queue propagation or cleanup
3993
    if changed_mc:
3994
      self.context.ReaddNode(node)
3995

    
3996
    return result
3997

    
3998

    
3999
class LUPowercycleNode(NoHooksLU):
4000
  """Powercycles a node.
4001

4002
  """
4003
  _OP_PARAMS = [
4004
    _PNodeName,
4005
    _PForce,
4006
    ]
4007
  REQ_BGL = False
4008

    
4009
  def CheckArguments(self):
4010
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4011
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4012
      raise errors.OpPrereqError("The node is the master and the force"
4013
                                 " parameter was not set",
4014
                                 errors.ECODE_INVAL)
4015

    
4016
  def ExpandNames(self):
4017
    """Locking for PowercycleNode.
4018

4019
    This is a last-resort option and shouldn't block on other
4020
    jobs. Therefore, we grab no locks.
4021

4022
    """
4023
    self.needed_locks = {}
4024

    
4025
  def Exec(self, feedback_fn):
4026
    """Reboots a node.
4027

4028
    """
4029
    result = self.rpc.call_node_powercycle(self.op.node_name,
4030
                                           self.cfg.GetHypervisorType())
4031
    result.Raise("Failed to schedule the reboot")
4032
    return result.payload
4033

    
4034

    
4035
class LUQueryClusterInfo(NoHooksLU):
4036
  """Query cluster configuration.
4037

4038
  """
4039
  REQ_BGL = False
4040

    
4041
  def ExpandNames(self):
4042
    self.needed_locks = {}
4043

    
4044
  def Exec(self, feedback_fn):
4045
    """Return cluster config.
4046

4047
    """
4048
    cluster = self.cfg.GetClusterInfo()
4049
    os_hvp = {}
4050

    
4051
    # Filter just for enabled hypervisors
4052
    for os_name, hv_dict in cluster.os_hvp.items():
4053
      os_hvp[os_name] = {}
4054
      for hv_name, hv_params in hv_dict.items():
4055
        if hv_name in cluster.enabled_hypervisors:
4056
          os_hvp[os_name][hv_name] = hv_params
4057

    
4058
    result = {
4059
      "software_version": constants.RELEASE_VERSION,
4060
      "protocol_version": constants.PROTOCOL_VERSION,
4061
      "config_version": constants.CONFIG_VERSION,
4062
      "os_api_version": max(constants.OS_API_VERSIONS),
4063
      "export_version": constants.EXPORT_VERSION,
4064
      "architecture": (platform.architecture()[0], platform.machine()),
4065
      "name": cluster.cluster_name,
4066
      "master": cluster.master_node,
4067
      "default_hypervisor": cluster.enabled_hypervisors[0],
4068
      "enabled_hypervisors": cluster.enabled_hypervisors,
4069
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4070
                        for hypervisor_name in cluster.enabled_hypervisors]),
4071
      "os_hvp": os_hvp,
4072
      "beparams": cluster.beparams,
4073
      "osparams": cluster.osparams,
4074
      "nicparams": cluster.nicparams,
4075
      "candidate_pool_size": cluster.candidate_pool_size,
4076
      "master_netdev": cluster.master_netdev,
4077
      "volume_group_name": cluster.volume_group_name,
4078
      "file_storage_dir": cluster.file_storage_dir,
4079
      "maintain_node_health": cluster.maintain_node_health,
4080
      "ctime": cluster.ctime,
4081
      "mtime": cluster.mtime,
4082
      "uuid": cluster.uuid,
4083
      "tags": list(cluster.GetTags()),
4084
      "uid_pool": cluster.uid_pool,
4085
      }
4086

    
4087
    return result
4088

    
4089

    
4090
class LUQueryConfigValues(NoHooksLU):
4091
  """Return configuration values.
4092

4093
  """
4094
  _OP_PARAMS = [_POutputFields]
4095
  REQ_BGL = False
4096
  _FIELDS_DYNAMIC = utils.FieldSet()
4097
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4098
                                  "watcher_pause")
4099

    
4100
  def CheckArguments(self):
4101
    _CheckOutputFields(static=self._FIELDS_STATIC,
4102
                       dynamic=self._FIELDS_DYNAMIC,
4103
                       selected=self.op.output_fields)
4104

    
4105
  def ExpandNames(self):
4106
    self.needed_locks = {}
4107

    
4108
  def Exec(self, feedback_fn):
4109
    """Dump a representation of the cluster config to the standard output.
4110

4111
    """
4112
    values = []
4113
    for field in self.op.output_fields:
4114
      if field == "cluster_name":
4115
        entry = self.cfg.GetClusterName()
4116
      elif field == "master_node":
4117
        entry = self.cfg.GetMasterNode()
4118
      elif field == "drain_flag":
4119
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4120
      elif field == "watcher_pause":
4121
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4122
      else:
4123
        raise errors.ParameterError(field)
4124
      values.append(entry)
4125
    return values
4126

    
4127

    
4128
class LUActivateInstanceDisks(NoHooksLU):
4129
  """Bring up an instance's disks.
4130

4131
  """
4132
  _OP_PARAMS = [
4133
    _PInstanceName,
4134
    ("ignore_size", False, _TBool),
4135
    ]
4136
  REQ_BGL = False
4137

    
4138
  def ExpandNames(self):
4139
    self._ExpandAndLockInstance()
4140
    self.needed_locks[locking.LEVEL_NODE] = []
4141
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4142

    
4143
  def DeclareLocks(self, level):
4144
    if level == locking.LEVEL_NODE:
4145
      self._LockInstancesNodes()
4146

    
4147
  def CheckPrereq(self):
4148
    """Check prerequisites.
4149

4150
    This checks that the instance is in the cluster.
4151

4152
    """
4153
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4154
    assert self.instance is not None, \
4155
      "Cannot retrieve locked instance %s" % self.op.instance_name
4156
    _CheckNodeOnline(self, self.instance.primary_node)
4157

    
4158
  def Exec(self, feedback_fn):
4159
    """Activate the disks.
4160

4161
    """
4162
    disks_ok, disks_info = \
4163
              _AssembleInstanceDisks(self, self.instance,
4164
                                     ignore_size=self.op.ignore_size)
4165
    if not disks_ok:
4166
      raise errors.OpExecError("Cannot activate block devices")
4167

    
4168
    return disks_info
4169

    
4170

    
4171
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4172
                           ignore_size=False):
4173
  """Prepare the block devices for an instance.
4174

4175
  This sets up the block devices on all nodes.
4176

4177
  @type lu: L{LogicalUnit}
4178
  @param lu: the logical unit on whose behalf we execute
4179
  @type instance: L{objects.Instance}
4180
  @param instance: the instance for whose disks we assemble
4181
  @type disks: list of L{objects.Disk} or None
4182
  @param disks: which disks to assemble (or all, if None)
4183
  @type ignore_secondaries: boolean
4184
  @param ignore_secondaries: if true, errors on secondary nodes
4185
      won't result in an error return from the function
4186
  @type ignore_size: boolean
4187
  @param ignore_size: if true, the current known size of the disk
4188
      will not be used during the disk activation, useful for cases
4189
      when the size is wrong
4190
  @return: False if the operation failed, otherwise a list of
4191
      (host, instance_visible_name, node_visible_name)
4192
      with the mapping from node devices to instance devices
4193

4194
  """
4195
  device_info = []
4196
  disks_ok = True
4197
  iname = instance.name
4198
  disks = _ExpandCheckDisks(instance, disks)
4199

    
4200
  # With the two passes mechanism we try to reduce the window of
4201
  # opportunity for the race condition of switching DRBD to primary
4202
  # before handshaking occured, but we do not eliminate it
4203

    
4204
  # The proper fix would be to wait (with some limits) until the
4205
  # connection has been made and drbd transitions from WFConnection
4206
  # into any other network-connected state (Connected, SyncTarget,
4207
  # SyncSource, etc.)
4208

    
4209
  # 1st pass, assemble on all nodes in secondary mode
4210
  for inst_disk in disks:
4211
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4212
      if ignore_size:
4213
        node_disk = node_disk.Copy()
4214
        node_disk.UnsetSize()
4215
      lu.cfg.SetDiskID(node_disk, node)
4216
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4217
      msg = result.fail_msg
4218
      if msg:
4219
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4220
                           " (is_primary=False, pass=1): %s",
4221
                           inst_disk.iv_name, node, msg)
4222
        if not ignore_secondaries:
4223
          disks_ok = False
4224

    
4225
  # FIXME: race condition on drbd migration to primary
4226

    
4227
  # 2nd pass, do only the primary node
4228
  for inst_disk in disks:
4229
    dev_path = None
4230

    
4231
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4232
      if node != instance.primary_node:
4233
        continue
4234
      if ignore_size:
4235
        node_disk = node_disk.Copy()
4236
        node_disk.UnsetSize()
4237
      lu.cfg.SetDiskID(node_disk, node)
4238
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4239
      msg = result.fail_msg
4240
      if msg:
4241
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4242
                           " (is_primary=True, pass=2): %s",
4243
                           inst_disk.iv_name, node, msg)
4244
        disks_ok = False
4245
      else:
4246
        dev_path = result.payload
4247

    
4248
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4249

    
4250
  # leave the disks configured for the primary node
4251
  # this is a workaround that would be fixed better by
4252
  # improving the logical/physical id handling
4253
  for disk in disks:
4254
    lu.cfg.SetDiskID(disk, instance.primary_node)
4255

    
4256
  return disks_ok, device_info
4257

    
4258

    
4259
def _StartInstanceDisks(lu, instance, force):
4260
  """Start the disks of an instance.
4261

4262
  """
4263
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4264
                                           ignore_secondaries=force)
4265
  if not disks_ok:
4266
    _ShutdownInstanceDisks(lu, instance)
4267
    if force is not None and not force:
4268
      lu.proc.LogWarning("", hint="If the message above refers to a"
4269
                         " secondary node,"
4270
                         " you can retry the operation using '--force'.")
4271
    raise errors.OpExecError("Disk consistency error")
4272

    
4273

    
4274
class LUDeactivateInstanceDisks(NoHooksLU):
4275
  """Shutdown an instance's disks.
4276

4277
  """
4278
  _OP_PARAMS = [
4279
    _PInstanceName,
4280
    ]
4281
  REQ_BGL = False
4282

    
4283
  def ExpandNames(self):
4284
    self._ExpandAndLockInstance()
4285
    self.needed_locks[locking.LEVEL_NODE] = []
4286
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4287

    
4288
  def DeclareLocks(self, level):
4289
    if level == locking.LEVEL_NODE:
4290
      self._LockInstancesNodes()
4291

    
4292
  def CheckPrereq(self):
4293
    """Check prerequisites.
4294

4295
    This checks that the instance is in the cluster.
4296

4297
    """
4298
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4299
    assert self.instance is not None, \
4300
      "Cannot retrieve locked instance %s" % self.op.instance_name
4301

    
4302
  def Exec(self, feedback_fn):
4303
    """Deactivate the disks
4304

4305
    """
4306
    instance = self.instance
4307
    _SafeShutdownInstanceDisks(self, instance)
4308

    
4309

    
4310
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4311
  """Shutdown block devices of an instance.
4312

4313
  This function checks if an instance is running, before calling
4314
  _ShutdownInstanceDisks.
4315

4316
  """
4317
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4318
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4319

    
4320

    
4321
def _ExpandCheckDisks(instance, disks):
4322
  """Return the instance disks selected by the disks list
4323

4324
  @type disks: list of L{objects.Disk} or None
4325
  @param disks: selected disks
4326
  @rtype: list of L{objects.Disk}
4327
  @return: selected instance disks to act on
4328

4329
  """
4330
  if disks is None:
4331
    return instance.disks
4332
  else:
4333
    if not set(disks).issubset(instance.disks):
4334
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4335
                                   " target instance")
4336
    return disks
4337

    
4338

    
4339
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4340
  """Shutdown block devices of an instance.
4341

4342
  This does the shutdown on all nodes of the instance.
4343

4344
  If the ignore_primary is false, errors on the primary node are
4345
  ignored.
4346

4347
  """
4348
  all_result = True
4349
  disks = _ExpandCheckDisks(instance, disks)
4350

    
4351
  for disk in disks:
4352
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4353
      lu.cfg.SetDiskID(top_disk, node)
4354
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4355
      msg = result.fail_msg
4356
      if msg:
4357
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4358
                      disk.iv_name, node, msg)
4359
        if not ignore_primary or node != instance.primary_node:
4360
          all_result = False
4361
  return all_result
4362

    
4363

    
4364
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4365
  """Checks if a node has enough free memory.
4366

4367
  This function check if a given node has the needed amount of free
4368
  memory. In case the node has less memory or we cannot get the
4369
  information from the node, this function raise an OpPrereqError
4370
  exception.
4371

4372
  @type lu: C{LogicalUnit}
4373
  @param lu: a logical unit from which we get configuration data
4374
  @type node: C{str}
4375
  @param node: the node to check
4376
  @type reason: C{str}
4377
  @param reason: string to use in the error message
4378
  @type requested: C{int}
4379
  @param requested: the amount of memory in MiB to check for
4380
  @type hypervisor_name: C{str}
4381
  @param hypervisor_name: the hypervisor to ask for memory stats
4382
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4383
      we cannot check the node
4384

4385
  """
4386
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4387
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4388
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4389
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4390
  if not isinstance(free_mem, int):
4391
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4392
                               " was '%s'" % (node, free_mem),
4393
                               errors.ECODE_ENVIRON)
4394
  if requested > free_mem:
4395
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4396
                               " needed %s MiB, available %s MiB" %
4397
                               (node, reason, requested, free_mem),
4398
                               errors.ECODE_NORES)
4399

    
4400

    
4401
def _CheckNodesFreeDisk(lu, nodenames, requested):
4402
  """Checks if nodes have enough free disk space in the default VG.
4403

4404
  This function check if all given nodes have the needed amount of
4405
  free disk. In case any node has less disk or we cannot get the
4406
  information from the node, this function raise an OpPrereqError
4407
  exception.
4408

4409
  @type lu: C{LogicalUnit}
4410
  @param lu: a logical unit from which we get configuration data
4411
  @type nodenames: C{list}
4412
  @param nodenames: the list of node names to check
4413
  @type requested: C{int}
4414
  @param requested: the amount of disk in MiB to check for
4415
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4416
      we cannot check the node
4417

4418
  """
4419
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4420
                                   lu.cfg.GetHypervisorType())
4421
  for node in nodenames:
4422
    info = nodeinfo[node]
4423
    info.Raise("Cannot get current information from node %s" % node,
4424
               prereq=True, ecode=errors.ECODE_ENVIRON)
4425
    vg_free = info.payload.get("vg_free", None)
4426
    if not isinstance(vg_free, int):
4427
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4428
                                 " result was '%s'" % (node, vg_free),
4429
                                 errors.ECODE_ENVIRON)
4430
    if requested > vg_free:
4431
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4432
                                 " required %d MiB, available %d MiB" %
4433
                                 (node, requested, vg_free),
4434
                                 errors.ECODE_NORES)
4435

    
4436

    
4437
class LUStartupInstance(LogicalUnit):
4438
  """Starts an instance.
4439

4440
  """
4441
  HPATH = "instance-start"
4442
  HTYPE = constants.HTYPE_INSTANCE
4443
  _OP_PARAMS = [
4444
    _PInstanceName,
4445
    _PForce,
4446
    ("hvparams", _EmptyDict, _TDict),
4447
    ("beparams", _EmptyDict, _TDict),
4448
    ]
4449
  REQ_BGL = False
4450

    
4451
  def CheckArguments(self):
4452
    # extra beparams
4453
    if self.op.beparams:
4454
      # fill the beparams dict
4455
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4456

    
4457
  def ExpandNames(self):
4458
    self._ExpandAndLockInstance()
4459

    
4460
  def BuildHooksEnv(self):
4461
    """Build hooks env.
4462

4463
    This runs on master, primary and secondary nodes of the instance.
4464

4465
    """
4466
    env = {
4467
      "FORCE": self.op.force,
4468
      }
4469
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4470
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4471
    return env, nl, nl
4472

    
4473
  def CheckPrereq(self):
4474
    """Check prerequisites.
4475

4476
    This checks that the instance is in the cluster.
4477

4478
    """
4479
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4480
    assert self.instance is not None, \
4481
      "Cannot retrieve locked instance %s" % self.op.instance_name
4482

    
4483
    # extra hvparams
4484
    if self.op.hvparams:
4485
      # check hypervisor parameter syntax (locally)
4486
      cluster = self.cfg.GetClusterInfo()
4487
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4488
      filled_hvp = cluster.FillHV(instance)
4489
      filled_hvp.update(self.op.hvparams)
4490
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4491
      hv_type.CheckParameterSyntax(filled_hvp)
4492
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4493

    
4494
    _CheckNodeOnline(self, instance.primary_node)
4495

    
4496
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4497
    # check bridges existence
4498
    _CheckInstanceBridgesExist(self, instance)
4499

    
4500
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4501
                                              instance.name,
4502
                                              instance.hypervisor)
4503
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4504
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4505
    if not remote_info.payload: # not running already
4506
      _CheckNodeFreeMemory(self, instance.primary_node,
4507
                           "starting instance %s" % instance.name,
4508
                           bep[constants.BE_MEMORY], instance.hypervisor)
4509

    
4510
  def Exec(self, feedback_fn):
4511
    """Start the instance.
4512

4513
    """
4514
    instance = self.instance
4515
    force = self.op.force
4516

    
4517
    self.cfg.MarkInstanceUp(instance.name)
4518

    
4519
    node_current = instance.primary_node
4520

    
4521
    _StartInstanceDisks(self, instance, force)
4522

    
4523
    result = self.rpc.call_instance_start(node_current, instance,
4524
                                          self.op.hvparams, self.op.beparams)
4525
    msg = result.fail_msg
4526
    if msg:
4527
      _ShutdownInstanceDisks(self, instance)
4528
      raise errors.OpExecError("Could not start instance: %s" % msg)
4529

    
4530

    
4531
class LURebootInstance(LogicalUnit):
4532
  """Reboot an instance.
4533

4534
  """
4535
  HPATH = "instance-reboot"
4536
  HTYPE = constants.HTYPE_INSTANCE
4537
  _OP_PARAMS = [
4538
    _PInstanceName,
4539
    ("ignore_secondaries", False, _TBool),
4540
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4541
    _PShutdownTimeout,
4542
    ]
4543
  REQ_BGL = False
4544

    
4545
  def ExpandNames(self):
4546
    self._ExpandAndLockInstance()
4547

    
4548
  def BuildHooksEnv(self):
4549
    """Build hooks env.
4550

4551
    This runs on master, primary and secondary nodes of the instance.
4552

4553
    """
4554
    env = {
4555
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4556
      "REBOOT_TYPE": self.op.reboot_type,
4557
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4558
      }
4559
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4560
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4561
    return env, nl, nl
4562

    
4563
  def CheckPrereq(self):
4564
    """Check prerequisites.
4565

4566
    This checks that the instance is in the cluster.
4567

4568
    """
4569
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4570
    assert self.instance is not None, \
4571
      "Cannot retrieve locked instance %s" % self.op.instance_name
4572

    
4573
    _CheckNodeOnline(self, instance.primary_node)
4574

    
4575
    # check bridges existence
4576
    _CheckInstanceBridgesExist(self, instance)
4577

    
4578
  def Exec(self, feedback_fn):
4579
    """Reboot the instance.
4580

4581
    """
4582
    instance = self.instance
4583
    ignore_secondaries = self.op.ignore_secondaries
4584
    reboot_type = self.op.reboot_type
4585

    
4586
    node_current = instance.primary_node
4587

    
4588
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4589
                       constants.INSTANCE_REBOOT_HARD]:
4590
      for disk in instance.disks:
4591
        self.cfg.SetDiskID(disk, node_current)
4592
      result = self.rpc.call_instance_reboot(node_current, instance,
4593
                                             reboot_type,
4594
                                             self.op.shutdown_timeout)
4595
      result.Raise("Could not reboot instance")
4596
    else:
4597
      result = self.rpc.call_instance_shutdown(node_current, instance,
4598
                                               self.op.shutdown_timeout)
4599
      result.Raise("Could not shutdown instance for full reboot")
4600
      _ShutdownInstanceDisks(self, instance)
4601
      _StartInstanceDisks(self, instance, ignore_secondaries)
4602
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4603
      msg = result.fail_msg
4604
      if msg:
4605
        _ShutdownInstanceDisks(self, instance)
4606
        raise errors.OpExecError("Could not start instance for"
4607
                                 " full reboot: %s" % msg)
4608

    
4609
    self.cfg.MarkInstanceUp(instance.name)
4610

    
4611

    
4612
class LUShutdownInstance(LogicalUnit):
4613
  """Shutdown an instance.
4614

4615
  """
4616
  HPATH = "instance-stop"
4617
  HTYPE = constants.HTYPE_INSTANCE
4618
  _OP_PARAMS = [
4619
    _PInstanceName,
4620
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4621
    ]
4622
  REQ_BGL = False
4623

    
4624
  def ExpandNames(self):
4625
    self._ExpandAndLockInstance()
4626

    
4627
  def BuildHooksEnv(self):
4628
    """Build hooks env.
4629

4630
    This runs on master, primary and secondary nodes of the instance.
4631

4632
    """
4633
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4634
    env["TIMEOUT"] = self.op.timeout
4635
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4636
    return env, nl, nl
4637

    
4638
  def CheckPrereq(self):
4639
    """Check prerequisites.
4640

4641
    This checks that the instance is in the cluster.
4642

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

    
4649
  def Exec(self, feedback_fn):
4650
    """Shutdown the instance.
4651

4652
    """
4653
    instance = self.instance
4654
    node_current = instance.primary_node
4655
    timeout = self.op.timeout
4656
    self.cfg.MarkInstanceDown(instance.name)
4657
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4658
    msg = result.fail_msg
4659
    if msg:
4660
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4661

    
4662
    _ShutdownInstanceDisks(self, instance)
4663

    
4664

    
4665
class LUReinstallInstance(LogicalUnit):
4666
  """Reinstall an instance.
4667

4668
  """
4669
  HPATH = "instance-reinstall"
4670
  HTYPE = constants.HTYPE_INSTANCE
4671
  _OP_PARAMS = [
4672
    _PInstanceName,
4673
    ("os_type", None, _TMaybeString),
4674
    ("force_variant", False, _TBool),
4675
    ]
4676
  REQ_BGL = False
4677

    
4678
  def ExpandNames(self):
4679
    self._ExpandAndLockInstance()
4680

    
4681
  def BuildHooksEnv(self):
4682
    """Build hooks env.
4683

4684
    This runs on master, primary and secondary nodes of the instance.
4685

4686
    """
4687
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4688
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4689
    return env, nl, nl
4690

    
4691
  def CheckPrereq(self):
4692
    """Check prerequisites.
4693

4694
    This checks that the instance is in the cluster and is not running.
4695

4696
    """
4697
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4698
    assert instance is not None, \
4699
      "Cannot retrieve locked instance %s" % self.op.instance_name
4700
    _CheckNodeOnline(self, instance.primary_node)
4701

    
4702
    if instance.disk_template == constants.DT_DISKLESS:
4703
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4704
                                 self.op.instance_name,
4705
                                 errors.ECODE_INVAL)
4706
    _CheckInstanceDown(self, instance, "cannot reinstall")
4707

    
4708
    if self.op.os_type is not None:
4709
      # OS verification
4710
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4711
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4712

    
4713
    self.instance = instance
4714

    
4715
  def Exec(self, feedback_fn):
4716
    """Reinstall the instance.
4717

4718
    """
4719
    inst = self.instance
4720

    
4721
    if self.op.os_type is not None:
4722
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4723
      inst.os = self.op.os_type
4724
      self.cfg.Update(inst, feedback_fn)
4725

    
4726
    _StartInstanceDisks(self, inst, None)
4727
    try:
4728
      feedback_fn("Running the instance OS create scripts...")
4729
      # FIXME: pass debug option from opcode to backend
4730
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4731
                                             self.op.debug_level)
4732
      result.Raise("Could not install OS for instance %s on node %s" %
4733
                   (inst.name, inst.primary_node))
4734
    finally:
4735
      _ShutdownInstanceDisks(self, inst)
4736

    
4737

    
4738
class LURecreateInstanceDisks(LogicalUnit):
4739
  """Recreate an instance's missing disks.
4740

4741
  """
4742
  HPATH = "instance-recreate-disks"
4743
  HTYPE = constants.HTYPE_INSTANCE
4744
  _OP_PARAMS = [
4745
    _PInstanceName,
4746
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4747
    ]
4748
  REQ_BGL = False
4749

    
4750
  def ExpandNames(self):
4751
    self._ExpandAndLockInstance()
4752

    
4753
  def BuildHooksEnv(self):
4754
    """Build hooks env.
4755

4756
    This runs on master, primary and secondary nodes of the instance.
4757

4758
    """
4759
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4760
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4761
    return env, nl, nl
4762

    
4763
  def CheckPrereq(self):
4764
    """Check prerequisites.
4765

4766
    This checks that the instance is in the cluster and is not running.
4767

4768
    """
4769
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4770
    assert instance is not None, \
4771
      "Cannot retrieve locked instance %s" % self.op.instance_name
4772
    _CheckNodeOnline(self, instance.primary_node)
4773

    
4774
    if instance.disk_template == constants.DT_DISKLESS:
4775
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4776
                                 self.op.instance_name, errors.ECODE_INVAL)
4777
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4778

    
4779
    if not self.op.disks:
4780
      self.op.disks = range(len(instance.disks))
4781
    else:
4782
      for idx in self.op.disks:
4783
        if idx >= len(instance.disks):
4784
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4785
                                     errors.ECODE_INVAL)
4786

    
4787
    self.instance = instance
4788

    
4789
  def Exec(self, feedback_fn):
4790
    """Recreate the disks.
4791

4792
    """
4793
    to_skip = []
4794
    for idx, _ in enumerate(self.instance.disks):
4795
      if idx not in self.op.disks: # disk idx has not been passed in
4796
        to_skip.append(idx)
4797
        continue
4798

    
4799
    _CreateDisks(self, self.instance, to_skip=to_skip)
4800

    
4801

    
4802
class LURenameInstance(LogicalUnit):
4803
  """Rename an instance.
4804

4805
  """
4806
  HPATH = "instance-rename"
4807
  HTYPE = constants.HTYPE_INSTANCE
4808
  _OP_PARAMS = [
4809
    _PInstanceName,
4810
    ("new_name", _NoDefault, _TNonEmptyString),
4811
    ("ignore_ip", False, _TBool),
4812
    ("check_name", True, _TBool),
4813
    ]
4814

    
4815
  def BuildHooksEnv(self):
4816
    """Build hooks env.
4817

4818
    This runs on master, primary and secondary nodes of the instance.
4819

4820
    """
4821
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4822
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4823
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4824
    return env, nl, nl
4825

    
4826
  def CheckPrereq(self):
4827
    """Check prerequisites.
4828

4829
    This checks that the instance is in the cluster and is not running.
4830

4831
    """
4832
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4833
                                                self.op.instance_name)
4834
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4835
    assert instance is not None
4836
    _CheckNodeOnline(self, instance.primary_node)
4837
    _CheckInstanceDown(self, instance, "cannot rename")
4838
    self.instance = instance
4839

    
4840
    # new name verification
4841
    if self.op.check_name:
4842
      name_info = utils.GetHostInfo(self.op.new_name)
4843
      self.op.new_name = name_info.name
4844

    
4845
    new_name = self.op.new_name
4846

    
4847
    instance_list = self.cfg.GetInstanceList()
4848
    if new_name in instance_list:
4849
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4850
                                 new_name, errors.ECODE_EXISTS)
4851

    
4852
    if not self.op.ignore_ip:
4853
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4854
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4855
                                   (name_info.ip, new_name),
4856
                                   errors.ECODE_NOTUNIQUE)
4857

    
4858
  def Exec(self, feedback_fn):
4859
    """Reinstall the instance.
4860

4861
    """
4862
    inst = self.instance
4863
    old_name = inst.name
4864

    
4865
    if inst.disk_template == constants.DT_FILE:
4866
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4867

    
4868
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4869
    # Change the instance lock. This is definitely safe while we hold the BGL
4870
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4871
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4872

    
4873
    # re-read the instance from the configuration after rename
4874
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4875

    
4876
    if inst.disk_template == constants.DT_FILE:
4877
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4878
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4879
                                                     old_file_storage_dir,
4880
                                                     new_file_storage_dir)
4881
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4882
                   " (but the instance has been renamed in Ganeti)" %
4883
                   (inst.primary_node, old_file_storage_dir,
4884
                    new_file_storage_dir))
4885

    
4886
    _StartInstanceDisks(self, inst, None)
4887
    try:
4888
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4889
                                                 old_name, self.op.debug_level)
4890
      msg = result.fail_msg
4891
      if msg:
4892
        msg = ("Could not run OS rename script for instance %s on node %s"
4893
               " (but the instance has been renamed in Ganeti): %s" %
4894
               (inst.name, inst.primary_node, msg))
4895
        self.proc.LogWarning(msg)
4896
    finally:
4897
      _ShutdownInstanceDisks(self, inst)
4898

    
4899

    
4900
class LURemoveInstance(LogicalUnit):
4901
  """Remove an instance.
4902

4903
  """
4904
  HPATH = "instance-remove"
4905
  HTYPE = constants.HTYPE_INSTANCE
4906
  _OP_PARAMS = [
4907
    _PInstanceName,
4908
    ("ignore_failures", False, _TBool),
4909
    _PShutdownTimeout,
4910
    ]
4911
  REQ_BGL = False
4912

    
4913
  def ExpandNames(self):
4914
    self._ExpandAndLockInstance()
4915
    self.needed_locks[locking.LEVEL_NODE] = []
4916
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4917

    
4918
  def DeclareLocks(self, level):
4919
    if level == locking.LEVEL_NODE:
4920
      self._LockInstancesNodes()
4921

    
4922
  def BuildHooksEnv(self):
4923
    """Build hooks env.
4924

4925
    This runs on master, primary and secondary nodes of the instance.
4926

4927
    """
4928
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4929
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4930
    nl = [self.cfg.GetMasterNode()]
4931
    nl_post = list(self.instance.all_nodes) + nl
4932
    return env, nl, nl_post
4933

    
4934
  def CheckPrereq(self):
4935
    """Check prerequisites.
4936

4937
    This checks that the instance is in the cluster.
4938

4939
    """
4940
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4941
    assert self.instance is not None, \
4942
      "Cannot retrieve locked instance %s" % self.op.instance_name
4943

    
4944
  def Exec(self, feedback_fn):
4945
    """Remove the instance.
4946

4947
    """
4948
    instance = self.instance
4949
    logging.info("Shutting down instance %s on node %s",
4950
                 instance.name, instance.primary_node)
4951

    
4952
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4953
                                             self.op.shutdown_timeout)
4954
    msg = result.fail_msg
4955
    if msg:
4956
      if self.op.ignore_failures:
4957
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4958
      else:
4959
        raise errors.OpExecError("Could not shutdown instance %s on"
4960
                                 " node %s: %s" %
4961
                                 (instance.name, instance.primary_node, msg))
4962

    
4963
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4964

    
4965

    
4966
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4967
  """Utility function to remove an instance.
4968

4969
  """
4970
  logging.info("Removing block devices for instance %s", instance.name)
4971

    
4972
  if not _RemoveDisks(lu, instance):
4973
    if not ignore_failures:
4974
      raise errors.OpExecError("Can't remove instance's disks")
4975
    feedback_fn("Warning: can't remove instance's disks")
4976

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

    
4979
  lu.cfg.RemoveInstance(instance.name)
4980

    
4981
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4982
    "Instance lock removal conflict"
4983

    
4984
  # Remove lock for the instance
4985
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4986

    
4987

    
4988
class LUQueryInstances(NoHooksLU):
4989
  """Logical unit for querying instances.
4990

4991
  """
4992
  # pylint: disable-msg=W0142
4993
  _OP_PARAMS = [
4994
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
4995
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
4996
    ("use_locking", False, _TBool),
4997
    ]
4998
  REQ_BGL = False
4999
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5000
                    "serial_no", "ctime", "mtime", "uuid"]
5001
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5002
                                    "admin_state",
5003
                                    "disk_template", "ip", "mac", "bridge",
5004
                                    "nic_mode", "nic_link",
5005
                                    "sda_size", "sdb_size", "vcpus", "tags",
5006
                                    "network_port", "beparams",
5007
                                    r"(disk)\.(size)/([0-9]+)",
5008
                                    r"(disk)\.(sizes)", "disk_usage",
5009
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5010
                                    r"(nic)\.(bridge)/([0-9]+)",
5011
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5012
                                    r"(disk|nic)\.(count)",
5013
                                    "hvparams",
5014
                                    ] + _SIMPLE_FIELDS +
5015
                                  ["hv/%s" % name
5016
                                   for name in constants.HVS_PARAMETERS
5017
                                   if name not in constants.HVC_GLOBALS] +
5018
                                  ["be/%s" % name
5019
                                   for name in constants.BES_PARAMETERS])
5020
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
5021

    
5022

    
5023
  def CheckArguments(self):
5024
    _CheckOutputFields(static=self._FIELDS_STATIC,
5025
                       dynamic=self._FIELDS_DYNAMIC,
5026
                       selected=self.op.output_fields)
5027

    
5028
  def ExpandNames(self):
5029
    self.needed_locks = {}
5030
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5031
    self.share_locks[locking.LEVEL_NODE] = 1
5032

    
5033
    if self.op.names:
5034
      self.wanted = _GetWantedInstances(self, self.op.names)
5035
    else:
5036
      self.wanted = locking.ALL_SET
5037

    
5038
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5039
    self.do_locking = self.do_node_query and self.op.use_locking
5040
    if self.do_locking:
5041
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5042
      self.needed_locks[locking.LEVEL_NODE] = []
5043
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5044

    
5045
  def DeclareLocks(self, level):
5046
    if level == locking.LEVEL_NODE and self.do_locking:
5047
      self._LockInstancesNodes()
5048

    
5049
  def Exec(self, feedback_fn):
5050
    """Computes the list of nodes and their attributes.
5051

5052
    """
5053
    # pylint: disable-msg=R0912
5054
    # way too many branches here
5055
    all_info = self.cfg.GetAllInstancesInfo()
5056
    if self.wanted == locking.ALL_SET:
5057
      # caller didn't specify instance names, so ordering is not important
5058
      if self.do_locking:
5059
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5060
      else:
5061
        instance_names = all_info.keys()
5062
      instance_names = utils.NiceSort(instance_names)
5063
    else:
5064
      # caller did specify names, so we must keep the ordering
5065
      if self.do_locking:
5066
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5067
      else:
5068
        tgt_set = all_info.keys()
5069
      missing = set(self.wanted).difference(tgt_set)
5070
      if missing:
5071
        raise errors.OpExecError("Some instances were removed before"
5072
                                 " retrieving their data: %s" % missing)
5073
      instance_names = self.wanted
5074

    
5075
    instance_list = [all_info[iname] for iname in instance_names]
5076

    
5077
    # begin data gathering
5078

    
5079
    nodes = frozenset([inst.primary_node for inst in instance_list])
5080
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5081

    
5082
    bad_nodes = []
5083
    off_nodes = []
5084
    if self.do_node_query:
5085
      live_data = {}
5086
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5087
      for name in nodes:
5088
        result = node_data[name]
5089
        if result.offline:
5090
          # offline nodes will be in both lists
5091
          off_nodes.append(name)
5092
        if result.fail_msg:
5093
          bad_nodes.append(name)
5094
        else:
5095
          if result.payload:
5096
            live_data.update(result.payload)
5097
          # else no instance is alive
5098
    else:
5099
      live_data = dict([(name, {}) for name in instance_names])
5100

    
5101
    # end data gathering
5102

    
5103
    HVPREFIX = "hv/"
5104
    BEPREFIX = "be/"
5105
    output = []
5106
    cluster = self.cfg.GetClusterInfo()
5107
    for instance in instance_list:
5108
      iout = []
5109
      i_hv = cluster.FillHV(instance, skip_globals=True)
5110
      i_be = cluster.FillBE(instance)
5111
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5112
      for field in self.op.output_fields:
5113
        st_match = self._FIELDS_STATIC.Matches(field)
5114
        if field in self._SIMPLE_FIELDS:
5115
          val = getattr(instance, field)
5116
        elif field == "pnode":
5117
          val = instance.primary_node
5118
        elif field == "snodes":
5119
          val = list(instance.secondary_nodes)
5120
        elif field == "admin_state":
5121
          val = instance.admin_up
5122
        elif field == "oper_state":
5123
          if instance.primary_node in bad_nodes:
5124
            val = None
5125
          else:
5126
            val = bool(live_data.get(instance.name))
5127
        elif field == "status":
5128
          if instance.primary_node in off_nodes:
5129
            val = "ERROR_nodeoffline"
5130
          elif instance.primary_node in bad_nodes:
5131
            val = "ERROR_nodedown"
5132
          else:
5133
            running = bool(live_data.get(instance.name))
5134
            if running:
5135
              if instance.admin_up:
5136
                val = "running"
5137
              else:
5138
                val = "ERROR_up"
5139
            else:
5140
              if instance.admin_up:
5141
                val = "ERROR_down"
5142
              else:
5143
                val = "ADMIN_down"
5144
        elif field == "oper_ram":
5145
          if instance.primary_node in bad_nodes:
5146
            val = None
5147
          elif instance.name in live_data:
5148
            val = live_data[instance.name].get("memory", "?")
5149
          else:
5150
            val = "-"
5151
        elif field == "vcpus":
5152
          val = i_be[constants.BE_VCPUS]
5153
        elif field == "disk_template":
5154
          val = instance.disk_template
5155
        elif field == "ip":
5156
          if instance.nics:
5157
            val = instance.nics[0].ip
5158
          else:
5159
            val = None
5160
        elif field == "nic_mode":
5161
          if instance.nics:
5162
            val = i_nicp[0][constants.NIC_MODE]
5163
          else:
5164
            val = None
5165
        elif field == "nic_link":
5166
          if instance.nics:
5167
            val = i_nicp[0][constants.NIC_LINK]
5168
          else:
5169
            val = None
5170
        elif field == "bridge":
5171
          if (instance.nics and
5172
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5173
            val = i_nicp[0][constants.NIC_LINK]
5174
          else:
5175
            val = None
5176
        elif field == "mac":
5177
          if instance.nics:
5178
            val = instance.nics[0].mac
5179
          else:
5180
            val = None
5181
        elif field == "sda_size" or field == "sdb_size":
5182
          idx = ord(field[2]) - ord('a')
5183
          try:
5184
            val = instance.FindDisk(idx).size
5185
          except errors.OpPrereqError:
5186
            val = None
5187
        elif field == "disk_usage": # total disk usage per node
5188
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5189
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5190
        elif field == "tags":
5191
          val = list(instance.GetTags())
5192
        elif field == "hvparams":
5193
          val = i_hv
5194
        elif (field.startswith(HVPREFIX) and
5195
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5196
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5197
          val = i_hv.get(field[len(HVPREFIX):], None)
5198
        elif field == "beparams":
5199
          val = i_be
5200
        elif (field.startswith(BEPREFIX) and
5201
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5202
          val = i_be.get(field[len(BEPREFIX):], None)
5203
        elif st_match and st_match.groups():
5204
          # matches a variable list
5205
          st_groups = st_match.groups()
5206
          if st_groups and st_groups[0] == "disk":
5207
            if st_groups[1] == "count":
5208
              val = len(instance.disks)
5209
            elif st_groups[1] == "sizes":
5210
              val = [disk.size for disk in instance.disks]
5211
            elif st_groups[1] == "size":
5212
              try:
5213
                val = instance.FindDisk(st_groups[2]).size
5214
              except errors.OpPrereqError:
5215
                val = None
5216
            else:
5217
              assert False, "Unhandled disk parameter"
5218
          elif st_groups[0] == "nic":
5219
            if st_groups[1] == "count":
5220
              val = len(instance.nics)
5221
            elif st_groups[1] == "macs":
5222
              val = [nic.mac for nic in instance.nics]
5223
            elif st_groups[1] == "ips":
5224
              val = [nic.ip for nic in instance.nics]
5225
            elif st_groups[1] == "modes":
5226
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5227
            elif st_groups[1] == "links":
5228
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5229
            elif st_groups[1] == "bridges":
5230
              val = []
5231
              for nicp in i_nicp:
5232
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5233
                  val.append(nicp[constants.NIC_LINK])
5234
                else:
5235
                  val.append(None)
5236
            else:
5237
              # index-based item
5238
              nic_idx = int(st_groups[2])
5239
              if nic_idx >= len(instance.nics):
5240
                val = None
5241
              else:
5242
                if st_groups[1] == "mac":
5243
                  val = instance.nics[nic_idx].mac
5244
                elif st_groups[1] == "ip":
5245
                  val = instance.nics[nic_idx].ip
5246
                elif st_groups[1] == "mode":
5247
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5248
                elif st_groups[1] == "link":
5249
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5250
                elif st_groups[1] == "bridge":
5251
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5252
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5253
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5254
                  else:
5255
                    val = None
5256
                else:
5257
                  assert False, "Unhandled NIC parameter"
5258
          else:
5259
            assert False, ("Declared but unhandled variable parameter '%s'" %
5260
                           field)
5261
        else:
5262
          assert False, "Declared but unhandled parameter '%s'" % field
5263
        iout.append(val)
5264
      output.append(iout)
5265

    
5266
    return output
5267

    
5268

    
5269
class LUFailoverInstance(LogicalUnit):
5270
  """Failover an instance.
5271

5272
  """
5273
  HPATH = "instance-failover"
5274
  HTYPE = constants.HTYPE_INSTANCE
5275
  _OP_PARAMS = [
5276
    _PInstanceName,
5277
    ("ignore_consistency", False, _TBool),
5278
    _PShutdownTimeout,
5279
    ]
5280
  REQ_BGL = False
5281

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

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

    
5291
  def BuildHooksEnv(self):
5292
    """Build hooks env.
5293

5294
    This runs on master, primary and secondary nodes of the instance.
5295

5296
    """
5297
    instance = self.instance
5298
    source_node = instance.primary_node
5299
    target_node = instance.secondary_nodes[0]
5300
    env = {
5301
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5302
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5303
      "OLD_PRIMARY": source_node,
5304
      "OLD_SECONDARY": target_node,
5305
      "NEW_PRIMARY": target_node,
5306
      "NEW_SECONDARY": source_node,
5307
      }
5308
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5309
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5310
    nl_post = list(nl)
5311
    nl_post.append(source_node)
5312
    return env, nl, nl_post
5313

    
5314
  def CheckPrereq(self):
5315
    """Check prerequisites.
5316

5317
    This checks that the instance is in the cluster.
5318

5319
    """
5320
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5321
    assert self.instance is not None, \
5322
      "Cannot retrieve locked instance %s" % self.op.instance_name
5323

    
5324
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5325
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5326
      raise errors.OpPrereqError("Instance's disk layout is not"
5327
                                 " network mirrored, cannot failover.",
5328
                                 errors.ECODE_STATE)
5329

    
5330
    secondary_nodes = instance.secondary_nodes
5331
    if not secondary_nodes:
5332
      raise errors.ProgrammerError("no secondary node but using "
5333
                                   "a mirrored disk template")
5334

    
5335
    target_node = secondary_nodes[0]
5336
    _CheckNodeOnline(self, target_node)
5337
    _CheckNodeNotDrained(self, target_node)
5338
    if instance.admin_up:
5339
      # check memory requirements on the secondary node
5340
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5341
                           instance.name, bep[constants.BE_MEMORY],
5342
                           instance.hypervisor)
5343
    else:
5344
      self.LogInfo("Not checking memory on the secondary node as"
5345
                   " instance will not be started")
5346

    
5347
    # check bridge existance
5348
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5349

    
5350
  def Exec(self, feedback_fn):
5351
    """Failover an instance.
5352

5353
    The failover is done by shutting it down on its present node and
5354
    starting it on the secondary.
5355

5356
    """
5357
    instance = self.instance
5358

    
5359
    source_node = instance.primary_node
5360
    target_node = instance.secondary_nodes[0]
5361

    
5362
    if instance.admin_up:
5363
      feedback_fn("* checking disk consistency between source and target")
5364
      for dev in instance.disks:
5365
        # for drbd, these are drbd over lvm
5366
        if not _CheckDiskConsistency(self, dev, target_node, False):
5367
          if not self.op.ignore_consistency:
5368
            raise errors.OpExecError("Disk %s is degraded on target node,"
5369
                                     " aborting failover." % dev.iv_name)
5370
    else:
5371
      feedback_fn("* not checking disk consistency as instance is not running")
5372

    
5373
    feedback_fn("* shutting down instance on source node")
5374
    logging.info("Shutting down instance %s on node %s",
5375
                 instance.name, source_node)
5376

    
5377
    result = self.rpc.call_instance_shutdown(source_node, instance,
5378
                                             self.op.shutdown_timeout)
5379
    msg = result.fail_msg
5380
    if msg:
5381
      if self.op.ignore_consistency:
5382
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5383
                             " Proceeding anyway. Please make sure node"
5384
                             " %s is down. Error details: %s",
5385
                             instance.name, source_node, source_node, msg)
5386
      else:
5387
        raise errors.OpExecError("Could not shutdown instance %s on"
5388
                                 " node %s: %s" %
5389
                                 (instance.name, source_node, msg))
5390

    
5391
    feedback_fn("* deactivating the instance's disks on source node")
5392
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5393
      raise errors.OpExecError("Can't shut down the instance's disks.")
5394

    
5395
    instance.primary_node = target_node
5396
    # distribute new instance config to the other nodes
5397
    self.cfg.Update(instance, feedback_fn)
5398

    
5399
    # Only start the instance if it's marked as up
5400
    if instance.admin_up:
5401
      feedback_fn("* activating the instance's disks on target node")
5402
      logging.info("Starting instance %s on node %s",
5403
                   instance.name, target_node)
5404

    
5405
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5406
                                           ignore_secondaries=True)
5407
      if not disks_ok:
5408
        _ShutdownInstanceDisks(self, instance)
5409
        raise errors.OpExecError("Can't activate the instance's disks")
5410

    
5411
      feedback_fn("* starting the instance on the target node")
5412
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5413
      msg = result.fail_msg
5414
      if msg:
5415
        _ShutdownInstanceDisks(self, instance)
5416
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5417
                                 (instance.name, target_node, msg))
5418

    
5419

    
5420
class LUMigrateInstance(LogicalUnit):
5421
  """Migrate an instance.
5422

5423
  This is migration without shutting down, compared to the failover,
5424
  which is done with shutdown.
5425

5426
  """
5427
  HPATH = "instance-migrate"
5428
  HTYPE = constants.HTYPE_INSTANCE
5429
  _OP_PARAMS = [
5430
    _PInstanceName,
5431
    ("live", True, _TBool),
5432
    ("cleanup", False, _TBool),
5433
    ]
5434

    
5435
  REQ_BGL = False
5436

    
5437
  def ExpandNames(self):
5438
    self._ExpandAndLockInstance()
5439

    
5440
    self.needed_locks[locking.LEVEL_NODE] = []
5441
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5442

    
5443
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5444
                                       self.op.live, self.op.cleanup)
5445
    self.tasklets = [self._migrater]
5446

    
5447
  def DeclareLocks(self, level):
5448
    if level == locking.LEVEL_NODE:
5449
      self._LockInstancesNodes()
5450

    
5451
  def BuildHooksEnv(self):
5452
    """Build hooks env.
5453

5454
    This runs on master, primary and secondary nodes of the instance.
5455

5456
    """
5457
    instance = self._migrater.instance
5458
    source_node = instance.primary_node
5459
    target_node = instance.secondary_nodes[0]
5460
    env = _BuildInstanceHookEnvByObject(self, instance)
5461
    env["MIGRATE_LIVE"] = self.op.live
5462
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5463
    env.update({
5464
        "OLD_PRIMARY": source_node,
5465
        "OLD_SECONDARY": target_node,
5466
        "NEW_PRIMARY": target_node,
5467
        "NEW_SECONDARY": source_node,
5468
        })
5469
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5470
    nl_post = list(nl)
5471
    nl_post.append(source_node)
5472
    return env, nl, nl_post
5473

    
5474

    
5475
class LUMoveInstance(LogicalUnit):
5476
  """Move an instance by data-copying.
5477

5478
  """
5479
  HPATH = "instance-move"
5480
  HTYPE = constants.HTYPE_INSTANCE
5481
  _OP_PARAMS = [
5482
    _PInstanceName,
5483
    ("target_node", _NoDefault, _TNonEmptyString),
5484
    _PShutdownTimeout,
5485
    ]
5486
  REQ_BGL = False
5487

    
5488
  def ExpandNames(self):
5489
    self._ExpandAndLockInstance()
5490
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5491
    self.op.target_node = target_node
5492
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5493
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5494

    
5495
  def DeclareLocks(self, level):
5496
    if level == locking.LEVEL_NODE:
5497
      self._LockInstancesNodes(primary_only=True)
5498

    
5499
  def BuildHooksEnv(self):
5500
    """Build hooks env.
5501

5502
    This runs on master, primary and secondary nodes of the instance.
5503

5504
    """
5505
    env = {
5506
      "TARGET_NODE": self.op.target_node,
5507
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5508
      }
5509
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5510
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5511
                                       self.op.target_node]
5512
    return env, nl, nl
5513

    
5514
  def CheckPrereq(self):
5515
    """Check prerequisites.
5516

5517
    This checks that the instance is in the cluster.
5518

5519
    """
5520
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5521
    assert self.instance is not None, \
5522
      "Cannot retrieve locked instance %s" % self.op.instance_name
5523

    
5524
    node = self.cfg.GetNodeInfo(self.op.target_node)
5525
    assert node is not None, \
5526
      "Cannot retrieve locked node %s" % self.op.target_node
5527

    
5528
    self.target_node = target_node = node.name
5529

    
5530
    if target_node == instance.primary_node:
5531
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5532
                                 (instance.name, target_node),
5533
                                 errors.ECODE_STATE)
5534

    
5535
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5536

    
5537
    for idx, dsk in enumerate(instance.disks):
5538
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5539
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5540
                                   " cannot copy" % idx, errors.ECODE_STATE)
5541

    
5542
    _CheckNodeOnline(self, target_node)
5543
    _CheckNodeNotDrained(self, target_node)
5544

    
5545
    if instance.admin_up:
5546
      # check memory requirements on the secondary node
5547
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5548
                           instance.name, bep[constants.BE_MEMORY],
5549
                           instance.hypervisor)
5550
    else:
5551
      self.LogInfo("Not checking memory on the secondary node as"
5552
                   " instance will not be started")
5553

    
5554
    # check bridge existance
5555
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5556

    
5557
  def Exec(self, feedback_fn):
5558
    """Move an instance.
5559

5560
    The move is done by shutting it down on its present node, copying
5561
    the data over (slow) and starting it on the new node.
5562

5563
    """
5564
    instance = self.instance
5565

    
5566
    source_node = instance.primary_node
5567
    target_node = self.target_node
5568

    
5569
    self.LogInfo("Shutting down instance %s on source node %s",
5570
                 instance.name, source_node)
5571

    
5572
    result = self.rpc.call_instance_shutdown(source_node, instance,
5573
                                             self.op.shutdown_timeout)
5574
    msg = result.fail_msg
5575
    if msg:
5576
      if self.op.ignore_consistency:
5577
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5578
                             " Proceeding anyway. Please make sure node"
5579
                             " %s is down. Error details: %s",
5580
                             instance.name, source_node, source_node, msg)
5581
      else:
5582
        raise errors.OpExecError("Could not shutdown instance %s on"
5583
                                 " node %s: %s" %
5584
                                 (instance.name, source_node, msg))
5585

    
5586
    # create the target disks
5587
    try:
5588
      _CreateDisks(self, instance, target_node=target_node)
5589
    except errors.OpExecError:
5590
      self.LogWarning("Device creation failed, reverting...")
5591
      try:
5592
        _RemoveDisks(self, instance, target_node=target_node)
5593
      finally:
5594
        self.cfg.ReleaseDRBDMinors(instance.name)
5595
        raise
5596

    
5597
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5598

    
5599
    errs = []
5600
    # activate, get path, copy the data over
5601
    for idx, disk in enumerate(instance.disks):
5602
      self.LogInfo("Copying data for disk %d", idx)
5603
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5604
                                               instance.name, True)
5605
      if result.fail_msg:
5606
        self.LogWarning("Can't assemble newly created disk %d: %s",
5607
                        idx, result.fail_msg)
5608
        errs.append(result.fail_msg)
5609
        break
5610
      dev_path = result.payload
5611
      result = self.rpc.call_blockdev_export(source_node, disk,
5612
                                             target_node, dev_path,
5613
                                             cluster_name)
5614
      if result.fail_msg:
5615
        self.LogWarning("Can't copy data over for disk %d: %s",
5616
                        idx, result.fail_msg)
5617
        errs.append(result.fail_msg)
5618
        break
5619

    
5620
    if errs:
5621
      self.LogWarning("Some disks failed to copy, aborting")
5622
      try:
5623
        _RemoveDisks(self, instance, target_node=target_node)
5624
      finally:
5625
        self.cfg.ReleaseDRBDMinors(instance.name)
5626
        raise errors.OpExecError("Errors during disk copy: %s" %
5627
                                 (",".join(errs),))
5628

    
5629
    instance.primary_node = target_node
5630
    self.cfg.Update(instance, feedback_fn)
5631

    
5632
    self.LogInfo("Removing the disks on the original node")
5633
    _RemoveDisks(self, instance, target_node=source_node)
5634

    
5635
    # Only start the instance if it's marked as up
5636
    if instance.admin_up:
5637
      self.LogInfo("Starting instance %s on node %s",
5638
                   instance.name, target_node)
5639

    
5640
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5641
                                           ignore_secondaries=True)
5642
      if not disks_ok:
5643
        _ShutdownInstanceDisks(self, instance)
5644
        raise errors.OpExecError("Can't activate the instance's disks")
5645

    
5646
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5647
      msg = result.fail_msg
5648
      if msg:
5649
        _ShutdownInstanceDisks(self, instance)
5650
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5651
                                 (instance.name, target_node, msg))
5652

    
5653

    
5654
class LUMigrateNode(LogicalUnit):
5655
  """Migrate all instances from a node.
5656

5657
  """
5658
  HPATH = "node-migrate"
5659
  HTYPE = constants.HTYPE_NODE
5660
  _OP_PARAMS = [
5661
    _PNodeName,
5662
    ("live", False, _TBool),
5663
    ]
5664
  REQ_BGL = False
5665

    
5666
  def ExpandNames(self):
5667
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5668

    
5669
    self.needed_locks = {
5670
      locking.LEVEL_NODE: [self.op.node_name],
5671
      }
5672

    
5673
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5674

    
5675
    # Create tasklets for migrating instances for all instances on this node
5676
    names = []
5677
    tasklets = []
5678

    
5679
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5680
      logging.debug("Migrating instance %s", inst.name)
5681
      names.append(inst.name)
5682

    
5683
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5684

    
5685
    self.tasklets = tasklets
5686

    
5687
    # Declare instance locks
5688
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5689

    
5690
  def DeclareLocks(self, level):
5691
    if level == locking.LEVEL_NODE:
5692
      self._LockInstancesNodes()
5693

    
5694
  def BuildHooksEnv(self):
5695
    """Build hooks env.
5696

5697
    This runs on the master, the primary and all the secondaries.
5698

5699
    """
5700
    env = {
5701
      "NODE_NAME": self.op.node_name,
5702
      }
5703

    
5704
    nl = [self.cfg.GetMasterNode()]
5705

    
5706
    return (env, nl, nl)
5707

    
5708

    
5709
class TLMigrateInstance(Tasklet):
5710
  def __init__(self, lu, instance_name, live, cleanup):
5711
    """Initializes this class.
5712

5713
    """
5714
    Tasklet.__init__(self, lu)
5715

    
5716
    # Parameters
5717
    self.instance_name = instance_name
5718
    self.live = live
5719
    self.cleanup = cleanup
5720

    
5721
  def CheckPrereq(self):
5722
    """Check prerequisites.
5723

5724
    This checks that the instance is in the cluster.
5725

5726
    """
5727
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5728
    instance = self.cfg.GetInstanceInfo(instance_name)
5729
    assert instance is not None
5730

    
5731
    if instance.disk_template != constants.DT_DRBD8:
5732
      raise errors.OpPrereqError("Instance's disk layout is not"
5733
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5734

    
5735
    secondary_nodes = instance.secondary_nodes
5736
    if not secondary_nodes:
5737
      raise errors.ConfigurationError("No secondary node but using"
5738
                                      " drbd8 disk template")
5739

    
5740
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5741

    
5742
    target_node = secondary_nodes[0]
5743
    # check memory requirements on the secondary node
5744
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5745
                         instance.name, i_be[constants.BE_MEMORY],
5746
                         instance.hypervisor)
5747

    
5748
    # check bridge existance
5749
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5750

    
5751
    if not self.cleanup:
5752
      _CheckNodeNotDrained(self.lu, target_node)
5753
      result = self.rpc.call_instance_migratable(instance.primary_node,
5754
                                                 instance)
5755
      result.Raise("Can't migrate, please use failover",
5756
                   prereq=True, ecode=errors.ECODE_STATE)
5757

    
5758
    self.instance = instance
5759

    
5760
  def _WaitUntilSync(self):
5761
    """Poll with custom rpc for disk sync.
5762

5763
    This uses our own step-based rpc call.
5764

5765
    """
5766
    self.feedback_fn("* wait until resync is done")
5767
    all_done = False
5768
    while not all_done:
5769
      all_done = True
5770
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5771
                                            self.nodes_ip,
5772
                                            self.instance.disks)
5773
      min_percent = 100
5774
      for node, nres in result.items():
5775
        nres.Raise("Cannot resync disks on node %s" % node)
5776
        node_done, node_percent = nres.payload
5777
        all_done = all_done and node_done
5778
        if node_percent is not None:
5779
          min_percent = min(min_percent, node_percent)
5780
      if not all_done:
5781
        if min_percent < 100:
5782
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5783
        time.sleep(2)
5784

    
5785
  def _EnsureSecondary(self, node):
5786
    """Demote a node to secondary.
5787

5788
    """
5789
    self.feedback_fn("* switching node %s to secondary mode" % node)
5790

    
5791
    for dev in self.instance.disks:
5792
      self.cfg.SetDiskID(dev, node)
5793

    
5794
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5795
                                          self.instance.disks)
5796
    result.Raise("Cannot change disk to secondary on node %s" % node)
5797

    
5798
  def _GoStandalone(self):
5799
    """Disconnect from the network.
5800

5801
    """
5802
    self.feedback_fn("* changing into standalone mode")
5803
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5804
                                               self.instance.disks)
5805
    for node, nres in result.items():
5806
      nres.Raise("Cannot disconnect disks node %s" % node)
5807

    
5808
  def _GoReconnect(self, multimaster):
5809
    """Reconnect to the network.
5810

5811
    """
5812
    if multimaster:
5813
      msg = "dual-master"
5814
    else:
5815
      msg = "single-master"
5816
    self.feedback_fn("* changing disks into %s mode" % msg)
5817
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5818
                                           self.instance.disks,
5819
                                           self.instance.name, multimaster)
5820
    for node, nres in result.items():
5821
      nres.Raise("Cannot change disks config on node %s" % node)
5822

    
5823
  def _ExecCleanup(self):
5824
    """Try to cleanup after a failed migration.
5825

5826
    The cleanup is done by:
5827
      - check that the instance is running only on one node
5828
        (and update the config if needed)
5829
      - change disks on its secondary node to secondary
5830
      - wait until disks are fully synchronized
5831
      - disconnect from the network
5832
      - change disks into single-master mode
5833
      - wait again until disks are fully synchronized
5834

5835
    """
5836
    instance = self.instance
5837
    target_node = self.target_node
5838
    source_node = self.source_node
5839

    
5840
    # check running on only one node
5841
    self.feedback_fn("* checking where the instance actually runs"
5842
                     " (if this hangs, the hypervisor might be in"
5843
                     " a bad state)")
5844
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5845
    for node, result in ins_l.items():
5846
      result.Raise("Can't contact node %s" % node)
5847

    
5848
    runningon_source = instance.name in ins_l[source_node].payload
5849
    runningon_target = instance.name in ins_l[target_node].payload
5850

    
5851
    if runningon_source and runningon_target:
5852
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5853
                               " or the hypervisor is confused. You will have"
5854
                               " to ensure manually that it runs only on one"
5855
                               " and restart this operation.")
5856

    
5857
    if not (runningon_source or runningon_target):
5858
      raise errors.OpExecError("Instance does not seem to be running at all."
5859
                               " In this case, it's safer to repair by"
5860
                               " running 'gnt-instance stop' to ensure disk"
5861
                               " shutdown, and then restarting it.")
5862

    
5863
    if runningon_target:
5864
      # the migration has actually succeeded, we need to update the config
5865
      self.feedback_fn("* instance running on secondary node (%s),"
5866
                       " updating config" % target_node)
5867
      instance.primary_node = target_node
5868
      self.cfg.Update(instance, self.feedback_fn)
5869
      demoted_node = source_node
5870
    else:
5871
      self.feedback_fn("* instance confirmed to be running on its"
5872
                       " primary node (%s)" % source_node)
5873
      demoted_node = target_node
5874

    
5875
    self._EnsureSecondary(demoted_node)
5876
    try:
5877
      self._WaitUntilSync()
5878
    except errors.OpExecError:
5879
      # we ignore here errors, since if the device is standalone, it
5880
      # won't be able to sync
5881
      pass
5882
    self._GoStandalone()
5883
    self._GoReconnect(False)
5884
    self._WaitUntilSync()
5885

    
5886
    self.feedback_fn("* done")
5887

    
5888
  def _RevertDiskStatus(self):
5889
    """Try to revert the disk status after a failed migration.
5890

5891
    """
5892
    target_node = self.target_node
5893
    try:
5894
      self._EnsureSecondary(target_node)
5895
      self._GoStandalone()
5896
      self._GoReconnect(False)
5897
      self._WaitUntilSync()
5898
    except errors.OpExecError, err:
5899
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5900
                         " drives: error '%s'\n"
5901
                         "Please look and recover the instance status" %
5902
                         str(err))
5903

    
5904
  def _AbortMigration(self):
5905
    """Call the hypervisor code to abort a started migration.
5906

5907
    """
5908
    instance = self.instance
5909
    target_node = self.target_node
5910
    migration_info = self.migration_info
5911

    
5912
    abort_result = self.rpc.call_finalize_migration(target_node,
5913
                                                    instance,
5914
                                                    migration_info,
5915
                                                    False)
5916
    abort_msg = abort_result.fail_msg
5917
    if abort_msg:
5918
      logging.error("Aborting migration failed on target node %s: %s",
5919
                    target_node, abort_msg)
5920
      # Don't raise an exception here, as we stil have to try to revert the
5921
      # disk status, even if this step failed.
5922

    
5923
  def _ExecMigration(self):
5924
    """Migrate an instance.
5925

5926
    The migrate is done by:
5927
      - change the disks into dual-master mode
5928
      - wait until disks are fully synchronized again
5929
      - migrate the instance
5930
      - change disks on the new secondary node (the old primary) to secondary
5931
      - wait until disks are fully synchronized
5932
      - change disks into single-master mode
5933

5934
    """
5935
    instance = self.instance
5936
    target_node = self.target_node
5937
    source_node = self.source_node
5938

    
5939
    self.feedback_fn("* checking disk consistency between source and target")
5940
    for dev in instance.disks:
5941
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5942
        raise errors.OpExecError("Disk %s is degraded or not fully"
5943
                                 " synchronized on target node,"
5944
                                 " aborting migrate." % dev.iv_name)
5945

    
5946
    # First get the migration information from the remote node
5947
    result = self.rpc.call_migration_info(source_node, instance)
5948
    msg = result.fail_msg
5949
    if msg:
5950
      log_err = ("Failed fetching source migration information from %s: %s" %
5951
                 (source_node, msg))
5952
      logging.error(log_err)
5953
      raise errors.OpExecError(log_err)
5954

    
5955
    self.migration_info = migration_info = result.payload
5956

    
5957
    # Then switch the disks to master/master mode
5958
    self._EnsureSecondary(target_node)
5959
    self._GoStandalone()
5960
    self._GoReconnect(True)
5961
    self._WaitUntilSync()
5962

    
5963
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5964
    result = self.rpc.call_accept_instance(target_node,
5965
                                           instance,
5966
                                           migration_info,
5967
                                           self.nodes_ip[target_node])
5968

    
5969
    msg = result.fail_msg
5970
    if msg:
5971
      logging.error("Instance pre-migration failed, trying to revert"
5972
                    " disk status: %s", msg)
5973
      self.feedback_fn("Pre-migration failed, aborting")
5974
      self._AbortMigration()
5975
      self._RevertDiskStatus()
5976
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5977
                               (instance.name, msg))
5978

    
5979
    self.feedback_fn("* migrating instance to %s" % target_node)
5980
    time.sleep(10)
5981
    result = self.rpc.call_instance_migrate(source_node, instance,
5982
                                            self.nodes_ip[target_node],
5983
                                            self.live)
5984
    msg = result.fail_msg
5985
    if msg:
5986
      logging.error("Instance migration failed, trying to revert"
5987
                    " disk status: %s", msg)
5988
      self.feedback_fn("Migration failed, aborting")
5989
      self._AbortMigration()
5990
      self._RevertDiskStatus()
5991
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5992
                               (instance.name, msg))
5993
    time.sleep(10)
5994

    
5995
    instance.primary_node = target_node
5996
    # distribute new instance config to the other nodes
5997
    self.cfg.Update(instance, self.feedback_fn)
5998

    
5999
    result = self.rpc.call_finalize_migration(target_node,
6000
                                              instance,
6001
                                              migration_info,
6002
                                              True)
6003
    msg = result.fail_msg
6004
    if msg:
6005
      logging.error("Instance migration succeeded, but finalization failed:"
6006
                    " %s", msg)
6007
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6008
                               msg)
6009

    
6010
    self._EnsureSecondary(source_node)
6011
    self._WaitUntilSync()
6012
    self._GoStandalone()
6013
    self._GoReconnect(False)
6014
    self._WaitUntilSync()
6015

    
6016
    self.feedback_fn("* done")
6017

    
6018
  def Exec(self, feedback_fn):
6019
    """Perform the migration.
6020

6021
    """
6022
    feedback_fn("Migrating instance %s" % self.instance.name)
6023

    
6024
    self.feedback_fn = feedback_fn
6025

    
6026
    self.source_node = self.instance.primary_node
6027
    self.target_node = self.instance.secondary_nodes[0]
6028
    self.all_nodes = [self.source_node, self.target_node]
6029
    self.nodes_ip = {
6030
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6031
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6032
      }
6033

    
6034
    if self.cleanup:
6035
      return self._ExecCleanup()
6036
    else:
6037
      return self._ExecMigration()
6038

    
6039

    
6040
def _CreateBlockDev(lu, node, instance, device, force_create,
6041
                    info, force_open):
6042
  """Create a tree of block devices on a given node.
6043

6044
  If this device type has to be created on secondaries, create it and
6045
  all its children.
6046

6047
  If not, just recurse to children keeping the same 'force' value.
6048

6049
  @param lu: the lu on whose behalf we execute
6050
  @param node: the node on which to create the device
6051
  @type instance: L{objects.Instance}
6052
  @param instance: the instance which owns the device
6053
  @type device: L{objects.Disk}
6054
  @param device: the device to create
6055
  @type force_create: boolean
6056
  @param force_create: whether to force creation of this device; this
6057
      will be change to True whenever we find a device which has
6058
      CreateOnSecondary() attribute
6059
  @param info: the extra 'metadata' we should attach to the device
6060
      (this will be represented as a LVM tag)
6061
  @type force_open: boolean
6062
  @param force_open: this parameter will be passes to the
6063
      L{backend.BlockdevCreate} function where it specifies
6064
      whether we run on primary or not, and it affects both
6065
      the child assembly and the device own Open() execution
6066

6067
  """
6068
  if device.CreateOnSecondary():
6069
    force_create = True
6070

    
6071
  if device.children:
6072
    for child in device.children:
6073
      _CreateBlockDev(lu, node, instance, child, force_create,
6074
                      info, force_open)
6075

    
6076
  if not force_create:
6077
    return
6078

    
6079
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6080

    
6081

    
6082
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6083
  """Create a single block device on a given node.
6084

6085
  This will not recurse over children of the device, so they must be
6086
  created in advance.
6087

6088
  @param lu: the lu on whose behalf we execute
6089
  @param node: the node on which to create the device
6090
  @type instance: L{objects.Instance}
6091
  @param instance: the instance which owns the device
6092
  @type device: L{objects.Disk}
6093
  @param device: the device to create
6094
  @param info: the extra 'metadata' we should attach to the device
6095
      (this will be represented as a LVM tag)
6096
  @type force_open: boolean
6097
  @param force_open: this parameter will be passes to the
6098
      L{backend.BlockdevCreate} function where it specifies
6099
      whether we run on primary or not, and it affects both
6100
      the child assembly and the device own Open() execution
6101

6102
  """
6103
  lu.cfg.SetDiskID(device, node)
6104
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6105
                                       instance.name, force_open, info)
6106
  result.Raise("Can't create block device %s on"
6107
               " node %s for instance %s" % (device, node, instance.name))
6108
  if device.physical_id is None:
6109
    device.physical_id = result.payload
6110

    
6111

    
6112
def _GenerateUniqueNames(lu, exts):
6113
  """Generate a suitable LV name.
6114

6115
  This will generate a logical volume name for the given instance.
6116

6117
  """
6118
  results = []
6119
  for val in exts:
6120
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6121
    results.append("%s%s" % (new_id, val))
6122
  return results
6123

    
6124

    
6125
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6126
                         p_minor, s_minor):
6127
  """Generate a drbd8 device complete with its children.
6128

6129
  """
6130
  port = lu.cfg.AllocatePort()
6131
  vgname = lu.cfg.GetVGName()
6132
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6133
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6134
                          logical_id=(vgname, names[0]))
6135
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6136
                          logical_id=(vgname, names[1]))
6137
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6138
                          logical_id=(primary, secondary, port,
6139
                                      p_minor, s_minor,
6140
                                      shared_secret),
6141
                          children=[dev_data, dev_meta],
6142
                          iv_name=iv_name)
6143
  return drbd_dev
6144

    
6145

    
6146
def _GenerateDiskTemplate(lu, template_name,
6147
                          instance_name, primary_node,
6148
                          secondary_nodes, disk_info,
6149
                          file_storage_dir, file_driver,
6150
                          base_index):
6151
  """Generate the entire disk layout for a given template type.
6152

6153
  """
6154
  #TODO: compute space requirements
6155

    
6156
  vgname = lu.cfg.GetVGName()
6157
  disk_count = len(disk_info)
6158
  disks = []
6159
  if template_name == constants.DT_DISKLESS:
6160
    pass
6161
  elif template_name == constants.DT_PLAIN:
6162
    if len(secondary_nodes) != 0:
6163
      raise errors.ProgrammerError("Wrong template configuration")
6164

    
6165
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6166
                                      for i in range(disk_count)])
6167
    for idx, disk in enumerate(disk_info):
6168
      disk_index = idx + base_index
6169
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6170
                              logical_id=(vgname, names[idx]),
6171
                              iv_name="disk/%d" % disk_index,
6172
                              mode=disk["mode"])
6173
      disks.append(disk_dev)
6174
  elif template_name == constants.DT_DRBD8:
6175
    if len(secondary_nodes) != 1:
6176
      raise errors.ProgrammerError("Wrong template configuration")
6177
    remote_node = secondary_nodes[0]
6178
    minors = lu.cfg.AllocateDRBDMinor(
6179
      [primary_node, remote_node] * len(disk_info), instance_name)
6180

    
6181
    names = []
6182
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6183
                                               for i in range(disk_count)]):
6184
      names.append(lv_prefix + "_data")
6185
      names.append(lv_prefix + "_meta")
6186
    for idx, disk in enumerate(disk_info):
6187
      disk_index = idx + base_index
6188
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6189
                                      disk["size"], names[idx*2:idx*2+2],
6190
                                      "disk/%d" % disk_index,
6191
                                      minors[idx*2], minors[idx*2+1])
6192
      disk_dev.mode = disk["mode"]
6193
      disks.append(disk_dev)
6194
  elif template_name == constants.DT_FILE:
6195
    if len(secondary_nodes) != 0:
6196
      raise errors.ProgrammerError("Wrong template configuration")
6197

    
6198
    _RequireFileStorage()
6199

    
6200
    for idx, disk in enumerate(disk_info):
6201
      disk_index = idx + base_index
6202
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6203
                              iv_name="disk/%d" % disk_index,
6204
                              logical_id=(file_driver,
6205
                                          "%s/disk%d" % (file_storage_dir,
6206
                                                         disk_index)),
6207
                              mode=disk["mode"])
6208
      disks.append(disk_dev)
6209
  else:
6210
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6211
  return disks
6212

    
6213

    
6214
def _GetInstanceInfoText(instance):
6215
  """Compute that text that should be added to the disk's metadata.
6216

6217
  """
6218
  return "originstname+%s" % instance.name
6219

    
6220

    
6221
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6222
  """Create all disks for an instance.
6223

6224
  This abstracts away some work from AddInstance.
6225

6226
  @type lu: L{LogicalUnit}
6227
  @param lu: the logical unit on whose behalf we execute
6228
  @type instance: L{objects.Instance}
6229
  @param instance: the instance whose disks we should create
6230
  @type to_skip: list
6231
  @param to_skip: list of indices to skip
6232
  @type target_node: string
6233
  @param target_node: if passed, overrides the target node for creation
6234
  @rtype: boolean
6235
  @return: the success of the creation
6236

6237
  """
6238
  info = _GetInstanceInfoText(instance)
6239
  if target_node is None:
6240
    pnode = instance.primary_node
6241
    all_nodes = instance.all_nodes
6242
  else:
6243
    pnode = target_node
6244
    all_nodes = [pnode]
6245

    
6246
  if instance.disk_template == constants.DT_FILE:
6247
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6248
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6249

    
6250
    result.Raise("Failed to create directory '%s' on"
6251
                 " node %s" % (file_storage_dir, pnode))
6252

    
6253
  # Note: this needs to be kept in sync with adding of disks in
6254
  # LUSetInstanceParams
6255
  for idx, device in enumerate(instance.disks):
6256
    if to_skip and idx in to_skip:
6257
      continue
6258
    logging.info("Creating volume %s for instance %s",
6259
                 device.iv_name, instance.name)
6260
    #HARDCODE
6261
    for node in all_nodes:
6262
      f_create = node == pnode
6263
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6264

    
6265

    
6266
def _RemoveDisks(lu, instance, target_node=None):
6267
  """Remove all disks for an instance.
6268

6269
  This abstracts away some work from `AddInstance()` and
6270
  `RemoveInstance()`. Note that in case some of the devices couldn't
6271
  be removed, the removal will continue with the other ones (compare
6272
  with `_CreateDisks()`).
6273

6274
  @type lu: L{LogicalUnit}
6275
  @param lu: the logical unit on whose behalf we execute
6276
  @type instance: L{objects.Instance}
6277
  @param instance: the instance whose disks we should remove
6278
  @type target_node: string
6279
  @param target_node: used to override the node on which to remove the disks
6280
  @rtype: boolean
6281
  @return: the success of the removal
6282

6283
  """
6284
  logging.info("Removing block devices for instance %s", instance.name)
6285

    
6286
  all_result = True
6287
  for device in instance.disks:
6288
    if target_node:
6289
      edata = [(target_node, device)]
6290
    else:
6291
      edata = device.ComputeNodeTree(instance.primary_node)
6292
    for node, disk in edata:
6293
      lu.cfg.SetDiskID(disk, node)
6294
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6295
      if msg:
6296
        lu.LogWarning("Could not remove block device %s on node %s,"
6297
                      " continuing anyway: %s", device.iv_name, node, msg)
6298
        all_result = False
6299

    
6300
  if instance.disk_template == constants.DT_FILE:
6301
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6302
    if target_node:
6303
      tgt = target_node
6304
    else:
6305
      tgt = instance.primary_node
6306
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6307
    if result.fail_msg:
6308
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6309
                    file_storage_dir, instance.primary_node, result.fail_msg)
6310
      all_result = False
6311

    
6312
  return all_result
6313

    
6314

    
6315
def _ComputeDiskSize(disk_template, disks):
6316
  """Compute disk size requirements in the volume group
6317

6318
  """
6319
  # Required free disk space as a function of disk and swap space
6320
  req_size_dict = {
6321
    constants.DT_DISKLESS: None,
6322
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6323
    # 128 MB are added for drbd metadata for each disk
6324
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6325
    constants.DT_FILE: None,
6326
  }
6327

    
6328
  if disk_template not in req_size_dict:
6329
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6330
                                 " is unknown" %  disk_template)
6331

    
6332
  return req_size_dict[disk_template]
6333

    
6334

    
6335
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6336
  """Hypervisor parameter validation.
6337

6338
  This function abstract the hypervisor parameter validation to be
6339
  used in both instance create and instance modify.
6340

6341
  @type lu: L{LogicalUnit}
6342
  @param lu: the logical unit for which we check
6343
  @type nodenames: list
6344
  @param nodenames: the list of nodes on which we should check
6345
  @type hvname: string
6346
  @param hvname: the name of the hypervisor we should use
6347
  @type hvparams: dict
6348
  @param hvparams: the parameters which we need to check
6349
  @raise errors.OpPrereqError: if the parameters are not valid
6350

6351
  """
6352
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6353
                                                  hvname,
6354
                                                  hvparams)
6355
  for node in nodenames:
6356
    info = hvinfo[node]
6357
    if info.offline:
6358
      continue
6359
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6360

    
6361

    
6362
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6363
  """OS parameters validation.
6364

6365
  @type lu: L{LogicalUnit}
6366
  @param lu: the logical unit for which we check
6367
  @type required: boolean
6368
  @param required: whether the validation should fail if the OS is not
6369
      found
6370
  @type nodenames: list
6371
  @param nodenames: the list of nodes on which we should check
6372
  @type osname: string
6373
  @param osname: the name of the hypervisor we should use
6374
  @type osparams: dict
6375
  @param osparams: the parameters which we need to check
6376
  @raise errors.OpPrereqError: if the parameters are not valid
6377

6378
  """
6379
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6380
                                   [constants.OS_VALIDATE_PARAMETERS],
6381
                                   osparams)
6382
  for node, nres in result.items():
6383
    # we don't check for offline cases since this should be run only
6384
    # against the master node and/or an instance's nodes
6385
    nres.Raise("OS Parameters validation failed on node %s" % node)
6386
    if not nres.payload:
6387
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6388
                 osname, node)
6389

    
6390

    
6391
class LUCreateInstance(LogicalUnit):
6392
  """Create an instance.
6393

6394
  """
6395
  HPATH = "instance-add"
6396
  HTYPE = constants.HTYPE_INSTANCE
6397
  _OP_PARAMS = [
6398
    _PInstanceName,
6399
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6400
    ("start", True, _TBool),
6401
    ("wait_for_sync", True, _TBool),
6402
    ("ip_check", True, _TBool),
6403
    ("name_check", True, _TBool),
6404
    ("disks", _NoDefault, _TListOf(_TDict)),
6405
    ("nics", _NoDefault, _TListOf(_TDict)),
6406
    ("hvparams", _EmptyDict, _TDict),
6407
    ("beparams", _EmptyDict, _TDict),
6408
    ("osparams", _EmptyDict, _TDict),
6409
    ("no_install", None, _TMaybeBool),
6410
    ("os_type", None, _TMaybeString),
6411
    ("force_variant", False, _TBool),
6412
    ("source_handshake", None, _TOr(_TList, _TNone)),
6413
    ("source_x509_ca", None, _TOr(_TList, _TNone)),
6414
    ("source_instance_name", None, _TMaybeString),
6415
    ("src_node", None, _TMaybeString),
6416
    ("src_path", None, _TMaybeString),
6417
    ("pnode", None, _TMaybeString),
6418
    ("snode", None, _TMaybeString),
6419
    ("iallocator", None, _TMaybeString),
6420
    ("hypervisor", None, _TMaybeString),
6421
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6422
    ("identify_defaults", False, _TBool),
6423
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6424
    ("file_storage_dir", None, _TMaybeString),
6425
    ("dry_run", False, _TBool),
6426
    ]
6427
  REQ_BGL = False
6428

    
6429
  def CheckArguments(self):
6430
    """Check arguments.
6431

6432
    """
6433
    # do not require name_check to ease forward/backward compatibility
6434
    # for tools
6435
    if self.op.no_install and self.op.start:
6436
      self.LogInfo("No-installation mode selected, disabling startup")
6437
      self.op.start = False
6438
    # validate/normalize the instance name
6439
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6440
    if self.op.ip_check and not self.op.name_check:
6441
      # TODO: make the ip check more flexible and not depend on the name check
6442
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6443
                                 errors.ECODE_INVAL)
6444

    
6445
    # check nics' parameter names
6446
    for nic in self.op.nics:
6447
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6448

    
6449
    # check disks. parameter names and consistent adopt/no-adopt strategy
6450
    has_adopt = has_no_adopt = False
6451
    for disk in self.op.disks:
6452
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6453
      if "adopt" in disk:
6454
        has_adopt = True
6455
      else:
6456
        has_no_adopt = True
6457
    if has_adopt and has_no_adopt:
6458
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6459
                                 errors.ECODE_INVAL)
6460
    if has_adopt:
6461
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6462
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6463
                                   " '%s' disk template" %
6464
                                   self.op.disk_template,
6465
                                   errors.ECODE_INVAL)
6466
      if self.op.iallocator is not None:
6467
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6468
                                   " iallocator script", errors.ECODE_INVAL)
6469
      if self.op.mode == constants.INSTANCE_IMPORT:
6470
        raise errors.OpPrereqError("Disk adoption not allowed for"
6471
                                   " instance import", errors.ECODE_INVAL)
6472

    
6473
    self.adopt_disks = has_adopt
6474

    
6475
    # instance name verification
6476
    if self.op.name_check:
6477
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6478
      self.op.instance_name = self.hostname1.name
6479
      # used in CheckPrereq for ip ping check
6480
      self.check_ip = self.hostname1.ip
6481
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6482
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6483
                                 errors.ECODE_INVAL)
6484
    else:
6485
      self.check_ip = None
6486

    
6487
    # file storage checks
6488
    if (self.op.file_driver and
6489
        not self.op.file_driver in constants.FILE_DRIVER):
6490
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6491
                                 self.op.file_driver, errors.ECODE_INVAL)
6492

    
6493
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6494
      raise errors.OpPrereqError("File storage directory path not absolute",
6495
                                 errors.ECODE_INVAL)
6496

    
6497
    ### Node/iallocator related checks
6498
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6499
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6500
                                 " node must be given",
6501
                                 errors.ECODE_INVAL)
6502

    
6503
    self._cds = _GetClusterDomainSecret()
6504

    
6505
    if self.op.mode == constants.INSTANCE_IMPORT:
6506
      # On import force_variant must be True, because if we forced it at
6507
      # initial install, our only chance when importing it back is that it
6508
      # works again!
6509
      self.op.force_variant = True
6510

    
6511
      if self.op.no_install:
6512
        self.LogInfo("No-installation mode has no effect during import")
6513

    
6514
    elif self.op.mode == constants.INSTANCE_CREATE:
6515
      if self.op.os_type is None:
6516
        raise errors.OpPrereqError("No guest OS specified",
6517
                                   errors.ECODE_INVAL)
6518
      if self.op.disk_template is None:
6519
        raise errors.OpPrereqError("No disk template specified",
6520
                                   errors.ECODE_INVAL)
6521

    
6522
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6523
      # Check handshake to ensure both clusters have the same domain secret
6524
      src_handshake = self.op.source_handshake
6525
      if not src_handshake:
6526
        raise errors.OpPrereqError("Missing source handshake",
6527
                                   errors.ECODE_INVAL)
6528

    
6529
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6530
                                                           src_handshake)
6531
      if errmsg:
6532
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6533
                                   errors.ECODE_INVAL)
6534

    
6535
      # Load and check source CA
6536
      self.source_x509_ca_pem = self.op.source_x509_ca
6537
      if not self.source_x509_ca_pem:
6538
        raise errors.OpPrereqError("Missing source X509 CA",
6539
                                   errors.ECODE_INVAL)
6540

    
6541
      try:
6542
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6543
                                                    self._cds)
6544
      except OpenSSL.crypto.Error, err:
6545
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6546
                                   (err, ), errors.ECODE_INVAL)
6547

    
6548
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6549
      if errcode is not None:
6550
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6551
                                   errors.ECODE_INVAL)
6552

    
6553
      self.source_x509_ca = cert
6554

    
6555
      src_instance_name = self.op.source_instance_name
6556
      if not src_instance_name:
6557
        raise errors.OpPrereqError("Missing source instance name",
6558
                                   errors.ECODE_INVAL)
6559

    
6560
      self.source_instance_name = \
6561
        utils.GetHostInfo(utils.HostInfo.NormalizeName(src_instance_name)).name
6562

    
6563
    else:
6564
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6565
                                 self.op.mode, errors.ECODE_INVAL)
6566

    
6567
  def ExpandNames(self):
6568
    """ExpandNames for CreateInstance.
6569

6570
    Figure out the right locks for instance creation.
6571

6572
    """
6573
    self.needed_locks = {}
6574

    
6575
    instance_name = self.op.instance_name
6576
    # this is just a preventive check, but someone might still add this
6577
    # instance in the meantime, and creation will fail at lock-add time
6578
    if instance_name in self.cfg.GetInstanceList():
6579
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6580
                                 instance_name, errors.ECODE_EXISTS)
6581

    
6582
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6583

    
6584
    if self.op.iallocator:
6585
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6586
    else:
6587
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6588
      nodelist = [self.op.pnode]
6589
      if self.op.snode is not None:
6590
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6591
        nodelist.append(self.op.snode)
6592
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6593

    
6594
    # in case of import lock the source node too
6595
    if self.op.mode == constants.INSTANCE_IMPORT:
6596
      src_node = self.op.src_node
6597
      src_path = self.op.src_path
6598

    
6599
      if src_path is None:
6600
        self.op.src_path = src_path = self.op.instance_name
6601

    
6602
      if src_node is None:
6603
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6604
        self.op.src_node = None
6605
        if os.path.isabs(src_path):
6606
          raise errors.OpPrereqError("Importing an instance from an absolute"
6607
                                     " path requires a source node option.",
6608
                                     errors.ECODE_INVAL)
6609
      else:
6610
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6611
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6612
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6613
        if not os.path.isabs(src_path):
6614
          self.op.src_path = src_path = \
6615
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6616

    
6617
  def _RunAllocator(self):
6618
    """Run the allocator based on input opcode.
6619

6620
    """
6621
    nics = [n.ToDict() for n in self.nics]
6622
    ial = IAllocator(self.cfg, self.rpc,
6623
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6624
                     name=self.op.instance_name,
6625
                     disk_template=self.op.disk_template,
6626
                     tags=[],
6627
                     os=self.op.os_type,
6628
                     vcpus=self.be_full[constants.BE_VCPUS],
6629
                     mem_size=self.be_full[constants.BE_MEMORY],
6630
                     disks=self.disks,
6631
                     nics=nics,
6632
                     hypervisor=self.op.hypervisor,
6633
                     )
6634

    
6635
    ial.Run(self.op.iallocator)
6636

    
6637
    if not ial.success:
6638
      raise errors.OpPrereqError("Can't compute nodes using"
6639
                                 " iallocator '%s': %s" %
6640
                                 (self.op.iallocator, ial.info),
6641
                                 errors.ECODE_NORES)
6642
    if len(ial.result) != ial.required_nodes:
6643
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6644
                                 " of nodes (%s), required %s" %
6645
                                 (self.op.iallocator, len(ial.result),
6646
                                  ial.required_nodes), errors.ECODE_FAULT)
6647
    self.op.pnode = ial.result[0]
6648
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6649
                 self.op.instance_name, self.op.iallocator,
6650
                 utils.CommaJoin(ial.result))
6651
    if ial.required_nodes == 2:
6652
      self.op.snode = ial.result[1]
6653

    
6654
  def BuildHooksEnv(self):
6655
    """Build hooks env.
6656

6657
    This runs on master, primary and secondary nodes of the instance.
6658

6659
    """
6660
    env = {
6661
      "ADD_MODE": self.op.mode,
6662
      }
6663
    if self.op.mode == constants.INSTANCE_IMPORT:
6664
      env["SRC_NODE"] = self.op.src_node
6665
      env["SRC_PATH"] = self.op.src_path
6666
      env["SRC_IMAGES"] = self.src_images
6667

    
6668
    env.update(_BuildInstanceHookEnv(
6669
      name=self.op.instance_name,
6670
      primary_node=self.op.pnode,
6671
      secondary_nodes=self.secondaries,
6672
      status=self.op.start,
6673
      os_type=self.op.os_type,
6674
      memory=self.be_full[constants.BE_MEMORY],
6675
      vcpus=self.be_full[constants.BE_VCPUS],
6676
      nics=_NICListToTuple(self, self.nics),
6677
      disk_template=self.op.disk_template,
6678
      disks=[(d["size"], d["mode"]) for d in self.disks],
6679
      bep=self.be_full,
6680
      hvp=self.hv_full,
6681
      hypervisor_name=self.op.hypervisor,
6682
    ))
6683

    
6684
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6685
          self.secondaries)
6686
    return env, nl, nl
6687

    
6688
  def _ReadExportInfo(self):
6689
    """Reads the export information from disk.
6690

6691
    It will override the opcode source node and path with the actual
6692
    information, if these two were not specified before.
6693

6694
    @return: the export information
6695

6696
    """
6697
    assert self.op.mode == constants.INSTANCE_IMPORT
6698

    
6699
    src_node = self.op.src_node
6700
    src_path = self.op.src_path
6701

    
6702
    if src_node is None:
6703
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6704
      exp_list = self.rpc.call_export_list(locked_nodes)
6705
      found = False
6706
      for node in exp_list:
6707
        if exp_list[node].fail_msg:
6708
          continue
6709
        if src_path in exp_list[node].payload:
6710
          found = True
6711
          self.op.src_node = src_node = node
6712
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6713
                                                       src_path)
6714
          break
6715
      if not found:
6716
        raise errors.OpPrereqError("No export found for relative path %s" %
6717
                                    src_path, errors.ECODE_INVAL)
6718

    
6719
    _CheckNodeOnline(self, src_node)
6720
    result = self.rpc.call_export_info(src_node, src_path)
6721
    result.Raise("No export or invalid export found in dir %s" % src_path)
6722

    
6723
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6724
    if not export_info.has_section(constants.INISECT_EXP):
6725
      raise errors.ProgrammerError("Corrupted export config",
6726
                                   errors.ECODE_ENVIRON)
6727

    
6728
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6729
    if (int(ei_version) != constants.EXPORT_VERSION):
6730
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6731
                                 (ei_version, constants.EXPORT_VERSION),
6732
                                 errors.ECODE_ENVIRON)
6733
    return export_info
6734

    
6735
  def _ReadExportParams(self, einfo):
6736
    """Use export parameters as defaults.
6737

6738
    In case the opcode doesn't specify (as in override) some instance
6739
    parameters, then try to use them from the export information, if
6740
    that declares them.
6741

6742
    """
6743
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6744

    
6745
    if self.op.disk_template is None:
6746
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6747
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6748
                                          "disk_template")
6749
      else:
6750
        raise errors.OpPrereqError("No disk template specified and the export"
6751
                                   " is missing the disk_template information",
6752
                                   errors.ECODE_INVAL)
6753

    
6754
    if not self.op.disks:
6755
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6756
        disks = []
6757
        # TODO: import the disk iv_name too
6758
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6759
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6760
          disks.append({"size": disk_sz})
6761
        self.op.disks = disks
6762
      else:
6763
        raise errors.OpPrereqError("No disk info specified and the export"
6764
                                   " is missing the disk information",
6765
                                   errors.ECODE_INVAL)
6766

    
6767
    if (not self.op.nics and
6768
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6769
      nics = []
6770
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6771
        ndict = {}
6772
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6773
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6774
          ndict[name] = v
6775
        nics.append(ndict)
6776
      self.op.nics = nics
6777

    
6778
    if (self.op.hypervisor is None and
6779
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6780
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6781
    if einfo.has_section(constants.INISECT_HYP):
6782
      # use the export parameters but do not override the ones
6783
      # specified by the user
6784
      for name, value in einfo.items(constants.INISECT_HYP):
6785
        if name not in self.op.hvparams:
6786
          self.op.hvparams[name] = value
6787

    
6788
    if einfo.has_section(constants.INISECT_BEP):
6789
      # use the parameters, without overriding
6790
      for name, value in einfo.items(constants.INISECT_BEP):
6791
        if name not in self.op.beparams:
6792
          self.op.beparams[name] = value
6793
    else:
6794
      # try to read the parameters old style, from the main section
6795
      for name in constants.BES_PARAMETERS:
6796
        if (name not in self.op.beparams and
6797
            einfo.has_option(constants.INISECT_INS, name)):
6798
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6799

    
6800
    if einfo.has_section(constants.INISECT_OSP):
6801
      # use the parameters, without overriding
6802
      for name, value in einfo.items(constants.INISECT_OSP):
6803
        if name not in self.op.osparams:
6804
          self.op.osparams[name] = value
6805

    
6806
  def _RevertToDefaults(self, cluster):
6807
    """Revert the instance parameters to the default values.
6808

6809
    """
6810
    # hvparams
6811
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6812
    for name in self.op.hvparams.keys():
6813
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6814
        del self.op.hvparams[name]
6815
    # beparams
6816
    be_defs = cluster.SimpleFillBE({})
6817
    for name in self.op.beparams.keys():
6818
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6819
        del self.op.beparams[name]
6820
    # nic params
6821
    nic_defs = cluster.SimpleFillNIC({})
6822
    for nic in self.op.nics:
6823
      for name in constants.NICS_PARAMETERS:
6824
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6825
          del nic[name]
6826
    # osparams
6827
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6828
    for name in self.op.osparams.keys():
6829
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6830
        del self.op.osparams[name]
6831

    
6832
  def CheckPrereq(self):
6833
    """Check prerequisites.
6834

6835
    """
6836
    if self.op.mode == constants.INSTANCE_IMPORT:
6837
      export_info = self._ReadExportInfo()
6838
      self._ReadExportParams(export_info)
6839

    
6840
    _CheckDiskTemplate(self.op.disk_template)
6841

    
6842
    if (not self.cfg.GetVGName() and
6843
        self.op.disk_template not in constants.DTS_NOT_LVM):
6844
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6845
                                 " instances", errors.ECODE_STATE)
6846

    
6847
    if self.op.hypervisor is None:
6848
      self.op.hypervisor = self.cfg.GetHypervisorType()
6849

    
6850
    cluster = self.cfg.GetClusterInfo()
6851
    enabled_hvs = cluster.enabled_hypervisors
6852
    if self.op.hypervisor not in enabled_hvs:
6853
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6854
                                 " cluster (%s)" % (self.op.hypervisor,
6855
                                  ",".join(enabled_hvs)),
6856
                                 errors.ECODE_STATE)
6857

    
6858
    # check hypervisor parameter syntax (locally)
6859
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6860
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6861
                                      self.op.hvparams)
6862
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6863
    hv_type.CheckParameterSyntax(filled_hvp)
6864
    self.hv_full = filled_hvp
6865
    # check that we don't specify global parameters on an instance
6866
    _CheckGlobalHvParams(self.op.hvparams)
6867

    
6868
    # fill and remember the beparams dict
6869
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6870
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6871

    
6872
    # build os parameters
6873
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6874

    
6875
    # now that hvp/bep are in final format, let's reset to defaults,
6876
    # if told to do so
6877
    if self.op.identify_defaults:
6878
      self._RevertToDefaults(cluster)
6879

    
6880
    # NIC buildup
6881
    self.nics = []
6882
    for idx, nic in enumerate(self.op.nics):
6883
      nic_mode_req = nic.get("mode", None)
6884
      nic_mode = nic_mode_req
6885
      if nic_mode is None:
6886
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6887

    
6888
      # in routed mode, for the first nic, the default ip is 'auto'
6889
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6890
        default_ip_mode = constants.VALUE_AUTO
6891
      else:
6892
        default_ip_mode = constants.VALUE_NONE
6893

    
6894
      # ip validity checks
6895
      ip = nic.get("ip", default_ip_mode)
6896
      if ip is None or ip.lower() == constants.VALUE_NONE:
6897
        nic_ip = None
6898
      elif ip.lower() == constants.VALUE_AUTO:
6899
        if not self.op.name_check:
6900
          raise errors.OpPrereqError("IP address set to auto but name checks"
6901
                                     " have been skipped. Aborting.",
6902
                                     errors.ECODE_INVAL)
6903
        nic_ip = self.hostname1.ip
6904
      else:
6905
        if not utils.IsValidIP4(ip):
6906
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6907
                                     " like a valid IP" % ip,
6908
                                     errors.ECODE_INVAL)
6909
        nic_ip = ip
6910

    
6911
      # TODO: check the ip address for uniqueness
6912
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6913
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6914
                                   errors.ECODE_INVAL)
6915

    
6916
      # MAC address verification
6917
      mac = nic.get("mac", constants.VALUE_AUTO)
6918
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6919
        mac = utils.NormalizeAndValidateMac(mac)
6920

    
6921
        try:
6922
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6923
        except errors.ReservationError:
6924
          raise errors.OpPrereqError("MAC address %s already in use"
6925
                                     " in cluster" % mac,
6926
                                     errors.ECODE_NOTUNIQUE)
6927

    
6928
      # bridge verification
6929
      bridge = nic.get("bridge", None)
6930
      link = nic.get("link", None)
6931
      if bridge and link:
6932
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6933
                                   " at the same time", errors.ECODE_INVAL)
6934
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6935
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6936
                                   errors.ECODE_INVAL)
6937
      elif bridge:
6938
        link = bridge
6939

    
6940
      nicparams = {}
6941
      if nic_mode_req:
6942
        nicparams[constants.NIC_MODE] = nic_mode_req
6943
      if link:
6944
        nicparams[constants.NIC_LINK] = link
6945

    
6946
      check_params = cluster.SimpleFillNIC(nicparams)
6947
      objects.NIC.CheckParameterSyntax(check_params)
6948
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6949

    
6950
    # disk checks/pre-build
6951
    self.disks = []
6952
    for disk in self.op.disks:
6953
      mode = disk.get("mode", constants.DISK_RDWR)
6954
      if mode not in constants.DISK_ACCESS_SET:
6955
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6956
                                   mode, errors.ECODE_INVAL)
6957
      size = disk.get("size", None)
6958
      if size is None:
6959
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6960
      try:
6961
        size = int(size)
6962
      except (TypeError, ValueError):
6963
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6964
                                   errors.ECODE_INVAL)
6965
      new_disk = {"size": size, "mode": mode}
6966
      if "adopt" in disk:
6967
        new_disk["adopt"] = disk["adopt"]
6968
      self.disks.append(new_disk)
6969

    
6970
    if self.op.mode == constants.INSTANCE_IMPORT:
6971

    
6972
      # Check that the new instance doesn't have less disks than the export
6973
      instance_disks = len(self.disks)
6974
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6975
      if instance_disks < export_disks:
6976
        raise errors.OpPrereqError("Not enough disks to import."
6977
                                   " (instance: %d, export: %d)" %
6978
                                   (instance_disks, export_disks),
6979
                                   errors.ECODE_INVAL)
6980

    
6981
      disk_images = []
6982
      for idx in range(export_disks):
6983
        option = 'disk%d_dump' % idx
6984
        if export_info.has_option(constants.INISECT_INS, option):
6985
          # FIXME: are the old os-es, disk sizes, etc. useful?
6986
          export_name = export_info.get(constants.INISECT_INS, option)
6987
          image = utils.PathJoin(self.op.src_path, export_name)
6988
          disk_images.append(image)
6989
        else:
6990
          disk_images.append(False)
6991

    
6992
      self.src_images = disk_images
6993

    
6994
      old_name = export_info.get(constants.INISECT_INS, 'name')
6995
      try:
6996
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6997
      except (TypeError, ValueError), err:
6998
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6999
                                   " an integer: %s" % str(err),
7000
                                   errors.ECODE_STATE)
7001
      if self.op.instance_name == old_name:
7002
        for idx, nic in enumerate(self.nics):
7003
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7004
            nic_mac_ini = 'nic%d_mac' % idx
7005
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7006

    
7007
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7008

    
7009
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7010
    if self.op.ip_check:
7011
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7012
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7013
                                   (self.check_ip, self.op.instance_name),
7014
                                   errors.ECODE_NOTUNIQUE)
7015

    
7016
    #### mac address generation
7017
    # By generating here the mac address both the allocator and the hooks get
7018
    # the real final mac address rather than the 'auto' or 'generate' value.
7019
    # There is a race condition between the generation and the instance object
7020
    # creation, which means that we know the mac is valid now, but we're not
7021
    # sure it will be when we actually add the instance. If things go bad
7022
    # adding the instance will abort because of a duplicate mac, and the
7023
    # creation job will fail.
7024
    for nic in self.nics:
7025
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7026
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7027

    
7028
    #### allocator run
7029

    
7030
    if self.op.iallocator is not None:
7031
      self._RunAllocator()
7032

    
7033
    #### node related checks
7034

    
7035
    # check primary node
7036
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7037
    assert self.pnode is not None, \
7038
      "Cannot retrieve locked node %s" % self.op.pnode
7039
    if pnode.offline:
7040
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7041
                                 pnode.name, errors.ECODE_STATE)
7042
    if pnode.drained:
7043
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7044
                                 pnode.name, errors.ECODE_STATE)
7045

    
7046
    self.secondaries = []
7047

    
7048
    # mirror node verification
7049
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7050
      if self.op.snode is None:
7051
        raise errors.OpPrereqError("The networked disk templates need"
7052
                                   " a mirror node", errors.ECODE_INVAL)
7053
      if self.op.snode == pnode.name:
7054
        raise errors.OpPrereqError("The secondary node cannot be the"
7055
                                   " primary node.", errors.ECODE_INVAL)
7056
      _CheckNodeOnline(self, self.op.snode)
7057
      _CheckNodeNotDrained(self, self.op.snode)
7058
      self.secondaries.append(self.op.snode)
7059

    
7060
    nodenames = [pnode.name] + self.secondaries
7061

    
7062
    req_size = _ComputeDiskSize(self.op.disk_template,
7063
                                self.disks)
7064

    
7065
    # Check lv size requirements, if not adopting
7066
    if req_size is not None and not self.adopt_disks:
7067
      _CheckNodesFreeDisk(self, nodenames, req_size)
7068

    
7069
    if self.adopt_disks: # instead, we must check the adoption data
7070
      all_lvs = set([i["adopt"] for i in self.disks])
7071
      if len(all_lvs) != len(self.disks):
7072
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7073
                                   errors.ECODE_INVAL)
7074
      for lv_name in all_lvs:
7075
        try:
7076
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7077
        except errors.ReservationError:
7078
          raise errors.OpPrereqError("LV named %s used by another instance" %
7079
                                     lv_name, errors.ECODE_NOTUNIQUE)
7080

    
7081
      node_lvs = self.rpc.call_lv_list([pnode.name],
7082
                                       self.cfg.GetVGName())[pnode.name]
7083
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7084
      node_lvs = node_lvs.payload
7085
      delta = all_lvs.difference(node_lvs.keys())
7086
      if delta:
7087
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7088
                                   utils.CommaJoin(delta),
7089
                                   errors.ECODE_INVAL)
7090
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7091
      if online_lvs:
7092
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7093
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7094
                                   errors.ECODE_STATE)
7095
      # update the size of disk based on what is found
7096
      for dsk in self.disks:
7097
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7098

    
7099
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7100

    
7101
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7102
    # check OS parameters (remotely)
7103
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7104

    
7105
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7106

    
7107
    # memory check on primary node
7108
    if self.op.start:
7109
      _CheckNodeFreeMemory(self, self.pnode.name,
7110
                           "creating instance %s" % self.op.instance_name,
7111
                           self.be_full[constants.BE_MEMORY],
7112
                           self.op.hypervisor)
7113

    
7114
    self.dry_run_result = list(nodenames)
7115

    
7116
  def Exec(self, feedback_fn):
7117
    """Create and add the instance to the cluster.
7118

7119
    """
7120
    instance = self.op.instance_name
7121
    pnode_name = self.pnode.name
7122

    
7123
    ht_kind = self.op.hypervisor
7124
    if ht_kind in constants.HTS_REQ_PORT:
7125
      network_port = self.cfg.AllocatePort()
7126
    else:
7127
      network_port = None
7128

    
7129
    if constants.ENABLE_FILE_STORAGE:
7130
      # this is needed because os.path.join does not accept None arguments
7131
      if self.op.file_storage_dir is None:
7132
        string_file_storage_dir = ""
7133
      else:
7134
        string_file_storage_dir = self.op.file_storage_dir
7135

    
7136
      # build the full file storage dir path
7137
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7138
                                        string_file_storage_dir, instance)
7139
    else:
7140
      file_storage_dir = ""
7141

    
7142
    disks = _GenerateDiskTemplate(self,
7143
                                  self.op.disk_template,
7144
                                  instance, pnode_name,
7145
                                  self.secondaries,
7146
                                  self.disks,
7147
                                  file_storage_dir,
7148
                                  self.op.file_driver,
7149
                                  0)
7150

    
7151
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7152
                            primary_node=pnode_name,
7153
                            nics=self.nics, disks=disks,
7154
                            disk_template=self.op.disk_template,
7155
                            admin_up=False,
7156
                            network_port=network_port,
7157
                            beparams=self.op.beparams,
7158
                            hvparams=self.op.hvparams,
7159
                            hypervisor=self.op.hypervisor,
7160
                            osparams=self.op.osparams,
7161
                            )
7162

    
7163
    if self.adopt_disks:
7164
      # rename LVs to the newly-generated names; we need to construct
7165
      # 'fake' LV disks with the old data, plus the new unique_id
7166
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7167
      rename_to = []
7168
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7169
        rename_to.append(t_dsk.logical_id)
7170
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7171
        self.cfg.SetDiskID(t_dsk, pnode_name)
7172
      result = self.rpc.call_blockdev_rename(pnode_name,
7173
                                             zip(tmp_disks, rename_to))
7174
      result.Raise("Failed to rename adoped LVs")
7175
    else:
7176
      feedback_fn("* creating instance disks...")
7177
      try:
7178
        _CreateDisks(self, iobj)
7179
      except errors.OpExecError:
7180
        self.LogWarning("Device creation failed, reverting...")
7181
        try:
7182
          _RemoveDisks(self, iobj)
7183
        finally:
7184
          self.cfg.ReleaseDRBDMinors(instance)
7185
          raise
7186

    
7187
    feedback_fn("adding instance %s to cluster config" % instance)
7188

    
7189
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7190

    
7191
    # Declare that we don't want to remove the instance lock anymore, as we've
7192
    # added the instance to the config
7193
    del self.remove_locks[locking.LEVEL_INSTANCE]
7194
    # Unlock all the nodes
7195
    if self.op.mode == constants.INSTANCE_IMPORT:
7196
      nodes_keep = [self.op.src_node]
7197
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7198
                       if node != self.op.src_node]
7199
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7200
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7201
    else:
7202
      self.context.glm.release(locking.LEVEL_NODE)
7203
      del self.acquired_locks[locking.LEVEL_NODE]
7204

    
7205
    if self.op.wait_for_sync:
7206
      disk_abort = not _WaitForSync(self, iobj)
7207
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7208
      # make sure the disks are not degraded (still sync-ing is ok)
7209
      time.sleep(15)
7210
      feedback_fn("* checking mirrors status")
7211
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7212
    else:
7213
      disk_abort = False
7214

    
7215
    if disk_abort:
7216
      _RemoveDisks(self, iobj)
7217
      self.cfg.RemoveInstance(iobj.name)
7218
      # Make sure the instance lock gets removed
7219
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7220
      raise errors.OpExecError("There are some degraded disks for"
7221
                               " this instance")
7222

    
7223
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7224
      if self.op.mode == constants.INSTANCE_CREATE:
7225
        if not self.op.no_install:
7226
          feedback_fn("* running the instance OS create scripts...")
7227
          # FIXME: pass debug option from opcode to backend
7228
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7229
                                                 self.op.debug_level)
7230
          result.Raise("Could not add os for instance %s"
7231
                       " on node %s" % (instance, pnode_name))
7232

    
7233
      elif self.op.mode == constants.INSTANCE_IMPORT:
7234
        feedback_fn("* running the instance OS import scripts...")
7235

    
7236
        transfers = []
7237

    
7238
        for idx, image in enumerate(self.src_images):
7239
          if not image:
7240
            continue
7241

    
7242
          # FIXME: pass debug option from opcode to backend
7243
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7244
                                             constants.IEIO_FILE, (image, ),
7245
                                             constants.IEIO_SCRIPT,
7246
                                             (iobj.disks[idx], idx),
7247
                                             None)
7248
          transfers.append(dt)
7249

    
7250
        import_result = \
7251
          masterd.instance.TransferInstanceData(self, feedback_fn,
7252
                                                self.op.src_node, pnode_name,
7253
                                                self.pnode.secondary_ip,
7254
                                                iobj, transfers)
7255
        if not compat.all(import_result):
7256
          self.LogWarning("Some disks for instance %s on node %s were not"
7257
                          " imported successfully" % (instance, pnode_name))
7258

    
7259
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7260
        feedback_fn("* preparing remote import...")
7261
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7262
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7263

    
7264
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7265
                                                     self.source_x509_ca,
7266
                                                     self._cds, timeouts)
7267
        if not compat.all(disk_results):
7268
          # TODO: Should the instance still be started, even if some disks
7269
          # failed to import (valid for local imports, too)?
7270
          self.LogWarning("Some disks for instance %s on node %s were not"
7271
                          " imported successfully" % (instance, pnode_name))
7272

    
7273
        # Run rename script on newly imported instance
7274
        assert iobj.name == instance
7275
        feedback_fn("Running rename script for %s" % instance)
7276
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7277
                                                   self.source_instance_name,
7278
                                                   self.op.debug_level)
7279
        if result.fail_msg:
7280
          self.LogWarning("Failed to run rename script for %s on node"
7281
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7282

    
7283
      else:
7284
        # also checked in the prereq part
7285
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7286
                                     % self.op.mode)
7287

    
7288
    if self.op.start:
7289
      iobj.admin_up = True
7290
      self.cfg.Update(iobj, feedback_fn)
7291
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7292
      feedback_fn("* starting instance...")
7293
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7294
      result.Raise("Could not start instance")
7295

    
7296
    return list(iobj.all_nodes)
7297

    
7298

    
7299
class LUConnectConsole(NoHooksLU):
7300
  """Connect to an instance's console.
7301

7302
  This is somewhat special in that it returns the command line that
7303
  you need to run on the master node in order to connect to the
7304
  console.
7305

7306
  """
7307
  _OP_PARAMS = [
7308
    _PInstanceName
7309
    ]
7310
  REQ_BGL = False
7311

    
7312
  def ExpandNames(self):
7313
    self._ExpandAndLockInstance()
7314

    
7315
  def CheckPrereq(self):
7316
    """Check prerequisites.
7317

7318
    This checks that the instance is in the cluster.
7319

7320
    """
7321
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7322
    assert self.instance is not None, \
7323
      "Cannot retrieve locked instance %s" % self.op.instance_name
7324
    _CheckNodeOnline(self, self.instance.primary_node)
7325

    
7326
  def Exec(self, feedback_fn):
7327
    """Connect to the console of an instance
7328

7329
    """
7330
    instance = self.instance
7331
    node = instance.primary_node
7332

    
7333
    node_insts = self.rpc.call_instance_list([node],
7334
                                             [instance.hypervisor])[node]
7335
    node_insts.Raise("Can't get node information from %s" % node)
7336

    
7337
    if instance.name not in node_insts.payload:
7338
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7339

    
7340
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7341

    
7342
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7343
    cluster = self.cfg.GetClusterInfo()
7344
    # beparams and hvparams are passed separately, to avoid editing the
7345
    # instance and then saving the defaults in the instance itself.
7346
    hvparams = cluster.FillHV(instance)
7347
    beparams = cluster.FillBE(instance)
7348
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7349

    
7350
    # build ssh cmdline
7351
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7352

    
7353

    
7354
class LUReplaceDisks(LogicalUnit):
7355
  """Replace the disks of an instance.
7356

7357
  """
7358
  HPATH = "mirrors-replace"
7359
  HTYPE = constants.HTYPE_INSTANCE
7360
  _OP_PARAMS = [
7361
    _PInstanceName,
7362
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7363
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7364
    ("remote_node", None, _TMaybeString),
7365
    ("iallocator", None, _TMaybeString),
7366
    ("early_release", False, _TBool),
7367
    ]
7368
  REQ_BGL = False
7369

    
7370
  def CheckArguments(self):
7371
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7372
                                  self.op.iallocator)
7373

    
7374
  def ExpandNames(self):
7375
    self._ExpandAndLockInstance()
7376

    
7377
    if self.op.iallocator is not None:
7378
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7379

    
7380
    elif self.op.remote_node is not None:
7381
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7382
      self.op.remote_node = remote_node
7383

    
7384
      # Warning: do not remove the locking of the new secondary here
7385
      # unless DRBD8.AddChildren is changed to work in parallel;
7386
      # currently it doesn't since parallel invocations of
7387
      # FindUnusedMinor will conflict
7388
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7389
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7390

    
7391
    else:
7392
      self.needed_locks[locking.LEVEL_NODE] = []
7393
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7394

    
7395
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7396
                                   self.op.iallocator, self.op.remote_node,
7397
                                   self.op.disks, False, self.op.early_release)
7398

    
7399
    self.tasklets = [self.replacer]
7400

    
7401
  def DeclareLocks(self, level):
7402
    # If we're not already locking all nodes in the set we have to declare the
7403
    # instance's primary/secondary nodes.
7404
    if (level == locking.LEVEL_NODE and
7405
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7406
      self._LockInstancesNodes()
7407

    
7408
  def BuildHooksEnv(self):
7409
    """Build hooks env.
7410

7411
    This runs on the master, the primary and all the secondaries.
7412

7413
    """
7414
    instance = self.replacer.instance
7415
    env = {
7416
      "MODE": self.op.mode,
7417
      "NEW_SECONDARY": self.op.remote_node,
7418
      "OLD_SECONDARY": instance.secondary_nodes[0],
7419
      }
7420
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7421
    nl = [
7422
      self.cfg.GetMasterNode(),
7423
      instance.primary_node,
7424
      ]
7425
    if self.op.remote_node is not None:
7426
      nl.append(self.op.remote_node)
7427
    return env, nl, nl
7428

    
7429

    
7430
class TLReplaceDisks(Tasklet):
7431
  """Replaces disks for an instance.
7432

7433
  Note: Locking is not within the scope of this class.
7434

7435
  """
7436
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7437
               disks, delay_iallocator, early_release):
7438
    """Initializes this class.
7439

7440
    """
7441
    Tasklet.__init__(self, lu)
7442

    
7443
    # Parameters
7444
    self.instance_name = instance_name
7445
    self.mode = mode
7446
    self.iallocator_name = iallocator_name
7447
    self.remote_node = remote_node
7448
    self.disks = disks
7449
    self.delay_iallocator = delay_iallocator
7450
    self.early_release = early_release
7451

    
7452
    # Runtime data
7453
    self.instance = None
7454
    self.new_node = None
7455
    self.target_node = None
7456
    self.other_node = None
7457
    self.remote_node_info = None
7458
    self.node_secondary_ip = None
7459

    
7460
  @staticmethod
7461
  def CheckArguments(mode, remote_node, iallocator):
7462
    """Helper function for users of this class.
7463

7464
    """
7465
    # check for valid parameter combination
7466
    if mode == constants.REPLACE_DISK_CHG:
7467
      if remote_node is None and iallocator is None:
7468
        raise errors.OpPrereqError("When changing the secondary either an"
7469
                                   " iallocator script must be used or the"
7470
                                   " new node given", errors.ECODE_INVAL)
7471

    
7472
      if remote_node is not None and iallocator is not None:
7473
        raise errors.OpPrereqError("Give either the iallocator or the new"
7474
                                   " secondary, not both", errors.ECODE_INVAL)
7475

    
7476
    elif remote_node is not None or iallocator is not None:
7477
      # Not replacing the secondary
7478
      raise errors.OpPrereqError("The iallocator and new node options can"
7479
                                 " only be used when changing the"
7480
                                 " secondary node", errors.ECODE_INVAL)
7481

    
7482
  @staticmethod
7483
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7484
    """Compute a new secondary node using an IAllocator.
7485

7486
    """
7487
    ial = IAllocator(lu.cfg, lu.rpc,
7488
                     mode=constants.IALLOCATOR_MODE_RELOC,
7489
                     name=instance_name,
7490
                     relocate_from=relocate_from)
7491

    
7492
    ial.Run(iallocator_name)
7493

    
7494
    if not ial.success:
7495
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7496
                                 " %s" % (iallocator_name, ial.info),
7497
                                 errors.ECODE_NORES)
7498

    
7499
    if len(ial.result) != ial.required_nodes:
7500
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7501
                                 " of nodes (%s), required %s" %
7502
                                 (iallocator_name,
7503
                                  len(ial.result), ial.required_nodes),
7504
                                 errors.ECODE_FAULT)
7505

    
7506
    remote_node_name = ial.result[0]
7507

    
7508
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7509
               instance_name, remote_node_name)
7510

    
7511
    return remote_node_name
7512

    
7513
  def _FindFaultyDisks(self, node_name):
7514
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7515
                                    node_name, True)
7516

    
7517
  def CheckPrereq(self):
7518
    """Check prerequisites.
7519

7520
    This checks that the instance is in the cluster.
7521

7522
    """
7523
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7524
    assert instance is not None, \
7525
      "Cannot retrieve locked instance %s" % self.instance_name
7526

    
7527
    if instance.disk_template != constants.DT_DRBD8:
7528
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7529
                                 " instances", errors.ECODE_INVAL)
7530

    
7531
    if len(instance.secondary_nodes) != 1:
7532
      raise errors.OpPrereqError("The instance has a strange layout,"
7533
                                 " expected one secondary but found %d" %
7534
                                 len(instance.secondary_nodes),
7535
                                 errors.ECODE_FAULT)
7536

    
7537
    if not self.delay_iallocator:
7538
      self._CheckPrereq2()
7539

    
7540
  def _CheckPrereq2(self):
7541
    """Check prerequisites, second part.
7542

7543
    This function should always be part of CheckPrereq. It was separated and is
7544
    now called from Exec because during node evacuation iallocator was only
7545
    called with an unmodified cluster model, not taking planned changes into
7546
    account.
7547

7548
    """
7549
    instance = self.instance
7550
    secondary_node = instance.secondary_nodes[0]
7551

    
7552
    if self.iallocator_name is None:
7553
      remote_node = self.remote_node
7554
    else:
7555
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7556
                                       instance.name, instance.secondary_nodes)
7557

    
7558
    if remote_node is not None:
7559
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7560
      assert self.remote_node_info is not None, \
7561
        "Cannot retrieve locked node %s" % remote_node
7562
    else:
7563
      self.remote_node_info = None
7564

    
7565
    if remote_node == self.instance.primary_node:
7566
      raise errors.OpPrereqError("The specified node is the primary node of"
7567
                                 " the instance.", errors.ECODE_INVAL)
7568

    
7569
    if remote_node == secondary_node:
7570
      raise errors.OpPrereqError("The specified node is already the"
7571
                                 " secondary node of the instance.",
7572
                                 errors.ECODE_INVAL)
7573

    
7574
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7575
                                    constants.REPLACE_DISK_CHG):
7576
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7577
                                 errors.ECODE_INVAL)
7578

    
7579
    if self.mode == constants.REPLACE_DISK_AUTO:
7580
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7581
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7582

    
7583
      if faulty_primary and faulty_secondary:
7584
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7585
                                   " one node and can not be repaired"
7586
                                   " automatically" % self.instance_name,
7587
                                   errors.ECODE_STATE)
7588

    
7589
      if faulty_primary:
7590
        self.disks = faulty_primary
7591
        self.target_node = instance.primary_node
7592
        self.other_node = secondary_node
7593
        check_nodes = [self.target_node, self.other_node]
7594
      elif faulty_secondary:
7595
        self.disks = faulty_secondary
7596
        self.target_node = secondary_node
7597
        self.other_node = instance.primary_node
7598
        check_nodes = [self.target_node, self.other_node]
7599
      else:
7600
        self.disks = []
7601
        check_nodes = []
7602

    
7603
    else:
7604
      # Non-automatic modes
7605
      if self.mode == constants.REPLACE_DISK_PRI:
7606
        self.target_node = instance.primary_node
7607
        self.other_node = secondary_node
7608
        check_nodes = [self.target_node, self.other_node]
7609

    
7610
      elif self.mode == constants.REPLACE_DISK_SEC:
7611
        self.target_node = secondary_node
7612
        self.other_node = instance.primary_node
7613
        check_nodes = [self.target_node, self.other_node]
7614

    
7615
      elif self.mode == constants.REPLACE_DISK_CHG:
7616
        self.new_node = remote_node
7617
        self.other_node = instance.primary_node
7618
        self.target_node = secondary_node
7619
        check_nodes = [self.new_node, self.other_node]
7620

    
7621
        _CheckNodeNotDrained(self.lu, remote_node)
7622

    
7623
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7624
        assert old_node_info is not None
7625
        if old_node_info.offline and not self.early_release:
7626
          # doesn't make sense to delay the release
7627
          self.early_release = True
7628
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7629
                          " early-release mode", secondary_node)
7630

    
7631
      else:
7632
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7633
                                     self.mode)
7634

    
7635
      # If not specified all disks should be replaced
7636
      if not self.disks:
7637
        self.disks = range(len(self.instance.disks))
7638

    
7639
    for node in check_nodes:
7640
      _CheckNodeOnline(self.lu, node)
7641

    
7642
    # Check whether disks are valid
7643
    for disk_idx in self.disks:
7644
      instance.FindDisk(disk_idx)
7645

    
7646
    # Get secondary node IP addresses
7647
    node_2nd_ip = {}
7648

    
7649
    for node_name in [self.target_node, self.other_node, self.new_node]:
7650
      if node_name is not None:
7651
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7652

    
7653
    self.node_secondary_ip = node_2nd_ip
7654

    
7655
  def Exec(self, feedback_fn):
7656
    """Execute disk replacement.
7657

7658
    This dispatches the disk replacement to the appropriate handler.
7659

7660
    """
7661
    if self.delay_iallocator:
7662
      self._CheckPrereq2()
7663

    
7664
    if not self.disks:
7665
      feedback_fn("No disks need replacement")
7666
      return
7667

    
7668
    feedback_fn("Replacing disk(s) %s for %s" %
7669
                (utils.CommaJoin(self.disks), self.instance.name))
7670

    
7671
    activate_disks = (not self.instance.admin_up)
7672

    
7673
    # Activate the instance disks if we're replacing them on a down instance
7674
    if activate_disks:
7675
      _StartInstanceDisks(self.lu, self.instance, True)
7676

    
7677
    try:
7678
      # Should we replace the secondary node?
7679
      if self.new_node is not None:
7680
        fn = self._ExecDrbd8Secondary
7681
      else:
7682
        fn = self._ExecDrbd8DiskOnly
7683

    
7684
      return fn(feedback_fn)
7685

    
7686
    finally:
7687
      # Deactivate the instance disks if we're replacing them on a
7688
      # down instance
7689
      if activate_disks:
7690
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7691

    
7692
  def _CheckVolumeGroup(self, nodes):
7693
    self.lu.LogInfo("Checking volume groups")
7694

    
7695
    vgname = self.cfg.GetVGName()
7696

    
7697
    # Make sure volume group exists on all involved nodes
7698
    results = self.rpc.call_vg_list(nodes)
7699
    if not results:
7700
      raise errors.OpExecError("Can't list volume groups on the nodes")
7701

    
7702
    for node in nodes:
7703
      res = results[node]
7704
      res.Raise("Error checking node %s" % node)
7705
      if vgname not in res.payload:
7706
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7707
                                 (vgname, node))
7708

    
7709
  def _CheckDisksExistence(self, nodes):
7710
    # Check disk existence
7711
    for idx, dev in enumerate(self.instance.disks):
7712
      if idx not in self.disks:
7713
        continue
7714

    
7715
      for node in nodes:
7716
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7717
        self.cfg.SetDiskID(dev, node)
7718

    
7719
        result = self.rpc.call_blockdev_find(node, dev)
7720

    
7721
        msg = result.fail_msg
7722
        if msg or not result.payload:
7723
          if not msg:
7724
            msg = "disk not found"
7725
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7726
                                   (idx, node, msg))
7727

    
7728
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7729
    for idx, dev in enumerate(self.instance.disks):
7730
      if idx not in self.disks:
7731
        continue
7732

    
7733
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7734
                      (idx, node_name))
7735

    
7736
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7737
                                   ldisk=ldisk):
7738
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7739
                                 " replace disks for instance %s" %
7740
                                 (node_name, self.instance.name))
7741

    
7742
  def _CreateNewStorage(self, node_name):
7743
    vgname = self.cfg.GetVGName()
7744
    iv_names = {}
7745

    
7746
    for idx, dev in enumerate(self.instance.disks):
7747
      if idx not in self.disks:
7748
        continue
7749

    
7750
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7751

    
7752
      self.cfg.SetDiskID(dev, node_name)
7753

    
7754
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7755
      names = _GenerateUniqueNames(self.lu, lv_names)
7756

    
7757
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7758
                             logical_id=(vgname, names[0]))
7759
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7760
                             logical_id=(vgname, names[1]))
7761

    
7762
      new_lvs = [lv_data, lv_meta]
7763
      old_lvs = dev.children
7764
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7765

    
7766
      # we pass force_create=True to force the LVM creation
7767
      for new_lv in new_lvs:
7768
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7769
                        _GetInstanceInfoText(self.instance), False)
7770

    
7771
    return iv_names
7772

    
7773
  def _CheckDevices(self, node_name, iv_names):
7774
    for name, (dev, _, _) in iv_names.iteritems():
7775
      self.cfg.SetDiskID(dev, node_name)
7776

    
7777
      result = self.rpc.call_blockdev_find(node_name, dev)
7778

    
7779
      msg = result.fail_msg
7780
      if msg or not result.payload:
7781
        if not msg:
7782
          msg = "disk not found"
7783
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7784
                                 (name, msg))
7785

    
7786
      if result.payload.is_degraded:
7787
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7788

    
7789
  def _RemoveOldStorage(self, node_name, iv_names):
7790
    for name, (_, old_lvs, _) in iv_names.iteritems():
7791
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7792

    
7793
      for lv in old_lvs:
7794
        self.cfg.SetDiskID(lv, node_name)
7795

    
7796
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7797
        if msg:
7798
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7799
                             hint="remove unused LVs manually")
7800

    
7801
  def _ReleaseNodeLock(self, node_name):
7802
    """Releases the lock for a given node."""
7803
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7804

    
7805
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7806
    """Replace a disk on the primary or secondary for DRBD 8.
7807

7808
    The algorithm for replace is quite complicated:
7809

7810
      1. for each disk to be replaced:
7811

7812
        1. create new LVs on the target node with unique names
7813
        1. detach old LVs from the drbd device
7814
        1. rename old LVs to name_replaced.<time_t>
7815
        1. rename new LVs to old LVs
7816
        1. attach the new LVs (with the old names now) to the drbd device
7817

7818
      1. wait for sync across all devices
7819

7820
      1. for each modified disk:
7821

7822
        1. remove old LVs (which have the name name_replaces.<time_t>)
7823

7824
    Failures are not very well handled.
7825

7826
    """
7827
    steps_total = 6
7828

    
7829
    # Step: check device activation
7830
    self.lu.LogStep(1, steps_total, "Check device existence")
7831
    self._CheckDisksExistence([self.other_node, self.target_node])
7832
    self._CheckVolumeGroup([self.target_node, self.other_node])
7833

    
7834
    # Step: check other node consistency
7835
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7836
    self._CheckDisksConsistency(self.other_node,
7837
                                self.other_node == self.instance.primary_node,
7838
                                False)
7839

    
7840
    # Step: create new storage
7841
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7842
    iv_names = self._CreateNewStorage(self.target_node)
7843

    
7844
    # Step: for each lv, detach+rename*2+attach
7845
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7846
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7847
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7848

    
7849
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7850
                                                     old_lvs)
7851
      result.Raise("Can't detach drbd from local storage on node"
7852
                   " %s for device %s" % (self.target_node, dev.iv_name))
7853
      #dev.children = []
7854
      #cfg.Update(instance)
7855

    
7856
      # ok, we created the new LVs, so now we know we have the needed
7857
      # storage; as such, we proceed on the target node to rename
7858
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7859
      # using the assumption that logical_id == physical_id (which in
7860
      # turn is the unique_id on that node)
7861

    
7862
      # FIXME(iustin): use a better name for the replaced LVs
7863
      temp_suffix = int(time.time())
7864
      ren_fn = lambda d, suff: (d.physical_id[0],
7865
                                d.physical_id[1] + "_replaced-%s" % suff)
7866

    
7867
      # Build the rename list based on what LVs exist on the node
7868
      rename_old_to_new = []
7869
      for to_ren in old_lvs:
7870
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7871
        if not result.fail_msg and result.payload:
7872
          # device exists
7873
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7874

    
7875
      self.lu.LogInfo("Renaming the old LVs on the target node")
7876
      result = self.rpc.call_blockdev_rename(self.target_node,
7877
                                             rename_old_to_new)
7878
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7879

    
7880
      # Now we rename the new LVs to the old LVs
7881
      self.lu.LogInfo("Renaming the new LVs on the target node")
7882
      rename_new_to_old = [(new, old.physical_id)
7883
                           for old, new in zip(old_lvs, new_lvs)]
7884
      result = self.rpc.call_blockdev_rename(self.target_node,
7885
                                             rename_new_to_old)
7886
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7887

    
7888
      for old, new in zip(old_lvs, new_lvs):
7889
        new.logical_id = old.logical_id
7890
        self.cfg.SetDiskID(new, self.target_node)
7891

    
7892
      for disk in old_lvs:
7893
        disk.logical_id = ren_fn(disk, temp_suffix)
7894
        self.cfg.SetDiskID(disk, self.target_node)
7895

    
7896
      # Now that the new lvs have the old name, we can add them to the device
7897
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7898
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7899
                                                  new_lvs)
7900
      msg = result.fail_msg
7901
      if msg:
7902
        for new_lv in new_lvs:
7903
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7904
                                               new_lv).fail_msg
7905
          if msg2:
7906
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7907
                               hint=("cleanup manually the unused logical"
7908
                                     "volumes"))
7909
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7910

    
7911
      dev.children = new_lvs
7912

    
7913
      self.cfg.Update(self.instance, feedback_fn)
7914

    
7915
    cstep = 5
7916
    if self.early_release:
7917
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7918
      cstep += 1
7919
      self._RemoveOldStorage(self.target_node, iv_names)
7920
      # WARNING: we release both node locks here, do not do other RPCs
7921
      # than WaitForSync to the primary node
7922
      self._ReleaseNodeLock([self.target_node, self.other_node])
7923

    
7924
    # Wait for sync
7925
    # This can fail as the old devices are degraded and _WaitForSync
7926
    # does a combined result over all disks, so we don't check its return value
7927
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7928
    cstep += 1
7929
    _WaitForSync(self.lu, self.instance)
7930

    
7931
    # Check all devices manually
7932
    self._CheckDevices(self.instance.primary_node, iv_names)
7933

    
7934
    # Step: remove old storage
7935
    if not self.early_release:
7936
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7937
      cstep += 1
7938
      self._RemoveOldStorage(self.target_node, iv_names)
7939

    
7940
  def _ExecDrbd8Secondary(self, feedback_fn):
7941
    """Replace the secondary node for DRBD 8.
7942

7943
    The algorithm for replace is quite complicated:
7944
      - for all disks of the instance:
7945
        - create new LVs on the new node with same names
7946
        - shutdown the drbd device on the old secondary
7947
        - disconnect the drbd network on the primary
7948
        - create the drbd device on the new secondary
7949
        - network attach the drbd on the primary, using an artifice:
7950
          the drbd code for Attach() will connect to the network if it
7951
          finds a device which is connected to the good local disks but
7952
          not network enabled
7953
      - wait for sync across all devices
7954
      - remove all disks from the old secondary
7955

7956
    Failures are not very well handled.
7957

7958
    """
7959
    steps_total = 6
7960

    
7961
    # Step: check device activation
7962
    self.lu.LogStep(1, steps_total, "Check device existence")
7963
    self._CheckDisksExistence([self.instance.primary_node])
7964
    self._CheckVolumeGroup([self.instance.primary_node])
7965

    
7966
    # Step: check other node consistency
7967
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7968
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7969

    
7970
    # Step: create new storage
7971
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7972
    for idx, dev in enumerate(self.instance.disks):
7973
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7974
                      (self.new_node, idx))
7975
      # we pass force_create=True to force LVM creation
7976
      for new_lv in dev.children:
7977
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7978
                        _GetInstanceInfoText(self.instance), False)
7979

    
7980
    # Step 4: dbrd minors and drbd setups changes
7981
    # after this, we must manually remove the drbd minors on both the
7982
    # error and the success paths
7983
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7984
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7985
                                         for dev in self.instance.disks],
7986
                                        self.instance.name)
7987
    logging.debug("Allocated minors %r", minors)
7988

    
7989
    iv_names = {}
7990
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7991
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7992
                      (self.new_node, idx))
7993
      # create new devices on new_node; note that we create two IDs:
7994
      # one without port, so the drbd will be activated without
7995
      # networking information on the new node at this stage, and one
7996
      # with network, for the latter activation in step 4
7997
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7998
      if self.instance.primary_node == o_node1:
7999
        p_minor = o_minor1
8000
      else:
8001
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8002
        p_minor = o_minor2
8003

    
8004
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8005
                      p_minor, new_minor, o_secret)
8006
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8007
                    p_minor, new_minor, o_secret)
8008

    
8009
      iv_names[idx] = (dev, dev.children, new_net_id)
8010
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8011
                    new_net_id)
8012
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8013
                              logical_id=new_alone_id,
8014
                              children=dev.children,
8015
                              size=dev.size)
8016
      try:
8017
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8018
                              _GetInstanceInfoText(self.instance), False)
8019
      except errors.GenericError:
8020
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8021
        raise
8022

    
8023
    # We have new devices, shutdown the drbd on the old secondary
8024
    for idx, dev in enumerate(self.instance.disks):
8025
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8026
      self.cfg.SetDiskID(dev, self.target_node)
8027
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8028
      if msg:
8029
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8030
                           "node: %s" % (idx, msg),
8031
                           hint=("Please cleanup this device manually as"
8032
                                 " soon as possible"))
8033

    
8034
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8035
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8036
                                               self.node_secondary_ip,
8037
                                               self.instance.disks)\
8038
                                              [self.instance.primary_node]
8039

    
8040
    msg = result.fail_msg
8041
    if msg:
8042
      # detaches didn't succeed (unlikely)
8043
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8044
      raise errors.OpExecError("Can't detach the disks from the network on"
8045
                               " old node: %s" % (msg,))
8046

    
8047
    # if we managed to detach at least one, we update all the disks of
8048
    # the instance to point to the new secondary
8049
    self.lu.LogInfo("Updating instance configuration")
8050
    for dev, _, new_logical_id in iv_names.itervalues():
8051
      dev.logical_id = new_logical_id
8052
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8053

    
8054
    self.cfg.Update(self.instance, feedback_fn)
8055

    
8056
    # and now perform the drbd attach
8057
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8058
                    " (standalone => connected)")
8059
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8060
                                            self.new_node],
8061
                                           self.node_secondary_ip,
8062
                                           self.instance.disks,
8063
                                           self.instance.name,
8064
                                           False)
8065
    for to_node, to_result in result.items():
8066
      msg = to_result.fail_msg
8067
      if msg:
8068
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8069
                           to_node, msg,
8070
                           hint=("please do a gnt-instance info to see the"
8071
                                 " status of disks"))
8072
    cstep = 5
8073
    if self.early_release:
8074
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8075
      cstep += 1
8076
      self._RemoveOldStorage(self.target_node, iv_names)
8077
      # WARNING: we release all node locks here, do not do other RPCs
8078
      # than WaitForSync to the primary node
8079
      self._ReleaseNodeLock([self.instance.primary_node,
8080
                             self.target_node,
8081
                             self.new_node])
8082

    
8083
    # Wait for sync
8084
    # This can fail as the old devices are degraded and _WaitForSync
8085
    # does a combined result over all disks, so we don't check its return value
8086
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8087
    cstep += 1
8088
    _WaitForSync(self.lu, self.instance)
8089

    
8090
    # Check all devices manually
8091
    self._CheckDevices(self.instance.primary_node, iv_names)
8092

    
8093
    # Step: remove old storage
8094
    if not self.early_release:
8095
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8096
      self._RemoveOldStorage(self.target_node, iv_names)
8097

    
8098

    
8099
class LURepairNodeStorage(NoHooksLU):
8100
  """Repairs the volume group on a node.
8101

8102
  """
8103
  _OP_PARAMS = [
8104
    _PNodeName,
8105
    ("storage_type", _NoDefault, _CheckStorageType),
8106
    ("name", _NoDefault, _TNonEmptyString),
8107
    ("ignore_consistency", False, _TBool),
8108
    ]
8109
  REQ_BGL = False
8110

    
8111
  def CheckArguments(self):
8112
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8113

    
8114
    storage_type = self.op.storage_type
8115

    
8116
    if (constants.SO_FIX_CONSISTENCY not in
8117
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8118
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8119
                                 " repaired" % storage_type,
8120
                                 errors.ECODE_INVAL)
8121

    
8122
  def ExpandNames(self):
8123
    self.needed_locks = {
8124
      locking.LEVEL_NODE: [self.op.node_name],
8125
      }
8126

    
8127
  def _CheckFaultyDisks(self, instance, node_name):
8128
    """Ensure faulty disks abort the opcode or at least warn."""
8129
    try:
8130
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8131
                                  node_name, True):
8132
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8133
                                   " node '%s'" % (instance.name, node_name),
8134
                                   errors.ECODE_STATE)
8135
    except errors.OpPrereqError, err:
8136
      if self.op.ignore_consistency:
8137
        self.proc.LogWarning(str(err.args[0]))
8138
      else:
8139
        raise
8140

    
8141
  def CheckPrereq(self):
8142
    """Check prerequisites.
8143

8144
    """
8145
    # Check whether any instance on this node has faulty disks
8146
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8147
      if not inst.admin_up:
8148
        continue
8149
      check_nodes = set(inst.all_nodes)
8150
      check_nodes.discard(self.op.node_name)
8151
      for inst_node_name in check_nodes:
8152
        self._CheckFaultyDisks(inst, inst_node_name)
8153

    
8154
  def Exec(self, feedback_fn):
8155
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8156
                (self.op.name, self.op.node_name))
8157

    
8158
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8159
    result = self.rpc.call_storage_execute(self.op.node_name,
8160
                                           self.op.storage_type, st_args,
8161
                                           self.op.name,
8162
                                           constants.SO_FIX_CONSISTENCY)
8163
    result.Raise("Failed to repair storage unit '%s' on %s" %
8164
                 (self.op.name, self.op.node_name))
8165

    
8166

    
8167
class LUNodeEvacuationStrategy(NoHooksLU):
8168
  """Computes the node evacuation strategy.
8169

8170
  """
8171
  _OP_PARAMS = [
8172
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8173
    ("remote_node", None, _TMaybeString),
8174
    ("iallocator", None, _TMaybeString),
8175
    ]
8176
  REQ_BGL = False
8177

    
8178
  def CheckArguments(self):
8179
    if self.op.remote_node is not None and self.op.iallocator is not None:
8180
      raise errors.OpPrereqError("Give either the iallocator or the new"
8181
                                 " secondary, not both", errors.ECODE_INVAL)
8182

    
8183
  def ExpandNames(self):
8184
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8185
    self.needed_locks = locks = {}
8186
    if self.op.remote_node is None:
8187
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8188
    else:
8189
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8190
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8191

    
8192
  def Exec(self, feedback_fn):
8193
    if self.op.remote_node is not None:
8194
      instances = []
8195
      for node in self.op.nodes:
8196
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8197
      result = []
8198
      for i in instances:
8199
        if i.primary_node == self.op.remote_node:
8200
          raise errors.OpPrereqError("Node %s is the primary node of"
8201
                                     " instance %s, cannot use it as"
8202
                                     " secondary" %
8203
                                     (self.op.remote_node, i.name),
8204
                                     errors.ECODE_INVAL)
8205
        result.append([i.name, self.op.remote_node])
8206
    else:
8207
      ial = IAllocator(self.cfg, self.rpc,
8208
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8209
                       evac_nodes=self.op.nodes)
8210
      ial.Run(self.op.iallocator, validate=True)
8211
      if not ial.success:
8212
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8213
                                 errors.ECODE_NORES)
8214
      result = ial.result
8215
    return result
8216

    
8217

    
8218
class LUGrowDisk(LogicalUnit):
8219
  """Grow a disk of an instance.
8220

8221
  """
8222
  HPATH = "disk-grow"
8223
  HTYPE = constants.HTYPE_INSTANCE
8224
  _OP_PARAMS = [
8225
    _PInstanceName,
8226
    ("disk", _NoDefault, _TInt),
8227
    ("amount", _NoDefault, _TInt),
8228
    ("wait_for_sync", True, _TBool),
8229
    ]
8230
  REQ_BGL = False
8231

    
8232
  def ExpandNames(self):
8233
    self._ExpandAndLockInstance()
8234
    self.needed_locks[locking.LEVEL_NODE] = []
8235
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8236

    
8237
  def DeclareLocks(self, level):
8238
    if level == locking.LEVEL_NODE:
8239
      self._LockInstancesNodes()
8240

    
8241
  def BuildHooksEnv(self):
8242
    """Build hooks env.
8243

8244
    This runs on the master, the primary and all the secondaries.
8245

8246
    """
8247
    env = {
8248
      "DISK": self.op.disk,
8249
      "AMOUNT": self.op.amount,
8250
      }
8251
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8252
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8253
    return env, nl, nl
8254

    
8255
  def CheckPrereq(self):
8256
    """Check prerequisites.
8257

8258
    This checks that the instance is in the cluster.
8259

8260
    """
8261
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8262
    assert instance is not None, \
8263
      "Cannot retrieve locked instance %s" % self.op.instance_name
8264
    nodenames = list(instance.all_nodes)
8265
    for node in nodenames:
8266
      _CheckNodeOnline(self, node)
8267

    
8268
    self.instance = instance
8269

    
8270
    if instance.disk_template not in constants.DTS_GROWABLE:
8271
      raise errors.OpPrereqError("Instance's disk layout does not support"
8272
                                 " growing.", errors.ECODE_INVAL)
8273

    
8274
    self.disk = instance.FindDisk(self.op.disk)
8275

    
8276
    if instance.disk_template != constants.DT_FILE:
8277
      # TODO: check the free disk space for file, when that feature will be
8278
      # supported
8279
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8280

    
8281
  def Exec(self, feedback_fn):
8282
    """Execute disk grow.
8283

8284
    """
8285
    instance = self.instance
8286
    disk = self.disk
8287

    
8288
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8289
    if not disks_ok:
8290
      raise errors.OpExecError("Cannot activate block device to grow")
8291

    
8292
    for node in instance.all_nodes:
8293
      self.cfg.SetDiskID(disk, node)
8294
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8295
      result.Raise("Grow request failed to node %s" % node)
8296

    
8297
      # TODO: Rewrite code to work properly
8298
      # DRBD goes into sync mode for a short amount of time after executing the
8299
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8300
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8301
      # time is a work-around.
8302
      time.sleep(5)
8303

    
8304
    disk.RecordGrow(self.op.amount)
8305
    self.cfg.Update(instance, feedback_fn)
8306
    if self.op.wait_for_sync:
8307
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8308
      if disk_abort:
8309
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8310
                             " status.\nPlease check the instance.")
8311
      if not instance.admin_up:
8312
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8313
    elif not instance.admin_up:
8314
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8315
                           " not supposed to be running because no wait for"
8316
                           " sync mode was requested.")
8317

    
8318

    
8319
class LUQueryInstanceData(NoHooksLU):
8320
  """Query runtime instance data.
8321

8322
  """
8323
  _OP_PARAMS = [
8324
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8325
    ("static", False, _TBool),
8326
    ]
8327
  REQ_BGL = False
8328

    
8329
  def ExpandNames(self):
8330
    self.needed_locks = {}
8331
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8332

    
8333
    if self.op.instances:
8334
      self.wanted_names = []
8335
      for name in self.op.instances:
8336
        full_name = _ExpandInstanceName(self.cfg, name)
8337
        self.wanted_names.append(full_name)
8338
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8339
    else:
8340
      self.wanted_names = None
8341
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8342

    
8343
    self.needed_locks[locking.LEVEL_NODE] = []
8344
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8345

    
8346
  def DeclareLocks(self, level):
8347
    if level == locking.LEVEL_NODE:
8348
      self._LockInstancesNodes()
8349

    
8350
  def CheckPrereq(self):
8351
    """Check prerequisites.
8352

8353
    This only checks the optional instance list against the existing names.
8354

8355
    """
8356
    if self.wanted_names is None:
8357
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8358

    
8359
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8360
                             in self.wanted_names]
8361

    
8362
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8363
    """Returns the status of a block device
8364

8365
    """
8366
    if self.op.static or not node:
8367
      return None
8368

    
8369
    self.cfg.SetDiskID(dev, node)
8370

    
8371
    result = self.rpc.call_blockdev_find(node, dev)
8372
    if result.offline:
8373
      return None
8374

    
8375
    result.Raise("Can't compute disk status for %s" % instance_name)
8376

    
8377
    status = result.payload
8378
    if status is None:
8379
      return None
8380

    
8381
    return (status.dev_path, status.major, status.minor,
8382
            status.sync_percent, status.estimated_time,
8383
            status.is_degraded, status.ldisk_status)
8384

    
8385
  def _ComputeDiskStatus(self, instance, snode, dev):
8386
    """Compute block device status.
8387

8388
    """
8389
    if dev.dev_type in constants.LDS_DRBD:
8390
      # we change the snode then (otherwise we use the one passed in)
8391
      if dev.logical_id[0] == instance.primary_node:
8392
        snode = dev.logical_id[1]
8393
      else:
8394
        snode = dev.logical_id[0]
8395

    
8396
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8397
                                              instance.name, dev)
8398
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8399

    
8400
    if dev.children:
8401
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8402
                      for child in dev.children]
8403
    else:
8404
      dev_children = []
8405

    
8406
    data = {
8407
      "iv_name": dev.iv_name,
8408
      "dev_type": dev.dev_type,
8409
      "logical_id": dev.logical_id,
8410
      "physical_id": dev.physical_id,
8411
      "pstatus": dev_pstatus,
8412
      "sstatus": dev_sstatus,
8413
      "children": dev_children,
8414
      "mode": dev.mode,
8415
      "size": dev.size,
8416
      }
8417

    
8418
    return data
8419

    
8420
  def Exec(self, feedback_fn):
8421
    """Gather and return data"""
8422
    result = {}
8423

    
8424
    cluster = self.cfg.GetClusterInfo()
8425

    
8426
    for instance in self.wanted_instances:
8427
      if not self.op.static:
8428
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8429
                                                  instance.name,
8430
                                                  instance.hypervisor)
8431
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8432
        remote_info = remote_info.payload
8433
        if remote_info and "state" in remote_info:
8434
          remote_state = "up"
8435
        else:
8436
          remote_state = "down"
8437
      else:
8438
        remote_state = None
8439
      if instance.admin_up:
8440
        config_state = "up"
8441
      else:
8442
        config_state = "down"
8443

    
8444
      disks = [self._ComputeDiskStatus(instance, None, device)
8445
               for device in instance.disks]
8446

    
8447
      idict = {
8448
        "name": instance.name,
8449
        "config_state": config_state,
8450
        "run_state": remote_state,
8451
        "pnode": instance.primary_node,
8452
        "snodes": instance.secondary_nodes,
8453
        "os": instance.os,
8454
        # this happens to be the same format used for hooks
8455
        "nics": _NICListToTuple(self, instance.nics),
8456
        "disk_template": instance.disk_template,
8457
        "disks": disks,
8458
        "hypervisor": instance.hypervisor,
8459
        "network_port": instance.network_port,
8460
        "hv_instance": instance.hvparams,
8461
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8462
        "be_instance": instance.beparams,
8463
        "be_actual": cluster.FillBE(instance),
8464
        "os_instance": instance.osparams,
8465
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8466
        "serial_no": instance.serial_no,
8467
        "mtime": instance.mtime,
8468
        "ctime": instance.ctime,
8469
        "uuid": instance.uuid,
8470
        }
8471

    
8472
      result[instance.name] = idict
8473

    
8474
    return result
8475

    
8476

    
8477
class LUSetInstanceParams(LogicalUnit):
8478
  """Modifies an instances's parameters.
8479

8480
  """
8481
  HPATH = "instance-modify"
8482
  HTYPE = constants.HTYPE_INSTANCE
8483
  _OP_PARAMS = [
8484
    _PInstanceName,
8485
    ("nics", _EmptyList, _TList),
8486
    ("disks", _EmptyList, _TList),
8487
    ("beparams", _EmptyDict, _TDict),
8488
    ("hvparams", _EmptyDict, _TDict),
8489
    ("disk_template", None, _TMaybeString),
8490
    ("remote_node", None, _TMaybeString),
8491
    ("os_name", None, _TMaybeString),
8492
    ("force_variant", False, _TBool),
8493
    ("osparams", None, _TOr(_TDict, _TNone)),
8494
    _PForce,
8495
    ]
8496
  REQ_BGL = False
8497

    
8498
  def CheckArguments(self):
8499
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8500
            self.op.hvparams or self.op.beparams or self.op.os_name):
8501
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8502

    
8503
    if self.op.hvparams:
8504
      _CheckGlobalHvParams(self.op.hvparams)
8505

    
8506
    # Disk validation
8507
    disk_addremove = 0
8508
    for disk_op, disk_dict in self.op.disks:
8509
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8510
      if disk_op == constants.DDM_REMOVE:
8511
        disk_addremove += 1
8512
        continue
8513
      elif disk_op == constants.DDM_ADD:
8514
        disk_addremove += 1
8515
      else:
8516
        if not isinstance(disk_op, int):
8517
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8518
        if not isinstance(disk_dict, dict):
8519
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8520
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8521

    
8522
      if disk_op == constants.DDM_ADD:
8523
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8524
        if mode not in constants.DISK_ACCESS_SET:
8525
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8526
                                     errors.ECODE_INVAL)
8527
        size = disk_dict.get('size', None)
8528
        if size is None:
8529
          raise errors.OpPrereqError("Required disk parameter size missing",
8530
                                     errors.ECODE_INVAL)
8531
        try:
8532
          size = int(size)
8533
        except (TypeError, ValueError), err:
8534
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8535
                                     str(err), errors.ECODE_INVAL)
8536
        disk_dict['size'] = size
8537
      else:
8538
        # modification of disk
8539
        if 'size' in disk_dict:
8540
          raise errors.OpPrereqError("Disk size change not possible, use"
8541
                                     " grow-disk", errors.ECODE_INVAL)
8542

    
8543
    if disk_addremove > 1:
8544
      raise errors.OpPrereqError("Only one disk add or remove operation"
8545
                                 " supported at a time", errors.ECODE_INVAL)
8546

    
8547
    if self.op.disks and self.op.disk_template is not None:
8548
      raise errors.OpPrereqError("Disk template conversion and other disk"
8549
                                 " changes not supported at the same time",
8550
                                 errors.ECODE_INVAL)
8551

    
8552
    if self.op.disk_template:
8553
      _CheckDiskTemplate(self.op.disk_template)
8554
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8555
          self.op.remote_node is None):
8556
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8557
                                   " one requires specifying a secondary node",
8558
                                   errors.ECODE_INVAL)
8559

    
8560
    # NIC validation
8561
    nic_addremove = 0
8562
    for nic_op, nic_dict in self.op.nics:
8563
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8564
      if nic_op == constants.DDM_REMOVE:
8565
        nic_addremove += 1
8566
        continue
8567
      elif nic_op == constants.DDM_ADD:
8568
        nic_addremove += 1
8569
      else:
8570
        if not isinstance(nic_op, int):
8571
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8572
        if not isinstance(nic_dict, dict):
8573
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8574
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8575

    
8576
      # nic_dict should be a dict
8577
      nic_ip = nic_dict.get('ip', None)
8578
      if nic_ip is not None:
8579
        if nic_ip.lower() == constants.VALUE_NONE:
8580
          nic_dict['ip'] = None
8581
        else:
8582
          if not utils.IsValidIP4(nic_ip):
8583
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8584
                                       errors.ECODE_INVAL)
8585

    
8586
      nic_bridge = nic_dict.get('bridge', None)
8587
      nic_link = nic_dict.get('link', None)
8588
      if nic_bridge and nic_link:
8589
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8590
                                   " at the same time", errors.ECODE_INVAL)
8591
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8592
        nic_dict['bridge'] = None
8593
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8594
        nic_dict['link'] = None
8595

    
8596
      if nic_op == constants.DDM_ADD:
8597
        nic_mac = nic_dict.get('mac', None)
8598
        if nic_mac is None:
8599
          nic_dict['mac'] = constants.VALUE_AUTO
8600

    
8601
      if 'mac' in nic_dict:
8602
        nic_mac = nic_dict['mac']
8603
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8604
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8605

    
8606
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8607
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8608
                                     " modifying an existing nic",
8609
                                     errors.ECODE_INVAL)
8610

    
8611
    if nic_addremove > 1:
8612
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8613
                                 " supported at a time", errors.ECODE_INVAL)
8614

    
8615
  def ExpandNames(self):
8616
    self._ExpandAndLockInstance()
8617
    self.needed_locks[locking.LEVEL_NODE] = []
8618
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8619

    
8620
  def DeclareLocks(self, level):
8621
    if level == locking.LEVEL_NODE:
8622
      self._LockInstancesNodes()
8623
      if self.op.disk_template and self.op.remote_node:
8624
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8625
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8626

    
8627
  def BuildHooksEnv(self):
8628
    """Build hooks env.
8629

8630
    This runs on the master, primary and secondaries.
8631

8632
    """
8633
    args = dict()
8634
    if constants.BE_MEMORY in self.be_new:
8635
      args['memory'] = self.be_new[constants.BE_MEMORY]
8636
    if constants.BE_VCPUS in self.be_new:
8637
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8638
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8639
    # information at all.
8640
    if self.op.nics:
8641
      args['nics'] = []
8642
      nic_override = dict(self.op.nics)
8643
      for idx, nic in enumerate(self.instance.nics):
8644
        if idx in nic_override:
8645
          this_nic_override = nic_override[idx]
8646
        else:
8647
          this_nic_override = {}
8648
        if 'ip' in this_nic_override:
8649
          ip = this_nic_override['ip']
8650
        else:
8651
          ip = nic.ip
8652
        if 'mac' in this_nic_override:
8653
          mac = this_nic_override['mac']
8654
        else:
8655
          mac = nic.mac
8656
        if idx in self.nic_pnew:
8657
          nicparams = self.nic_pnew[idx]
8658
        else:
8659
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8660
        mode = nicparams[constants.NIC_MODE]
8661
        link = nicparams[constants.NIC_LINK]
8662
        args['nics'].append((ip, mac, mode, link))
8663
      if constants.DDM_ADD in nic_override:
8664
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8665
        mac = nic_override[constants.DDM_ADD]['mac']
8666
        nicparams = self.nic_pnew[constants.DDM_ADD]
8667
        mode = nicparams[constants.NIC_MODE]
8668
        link = nicparams[constants.NIC_LINK]
8669
        args['nics'].append((ip, mac, mode, link))
8670
      elif constants.DDM_REMOVE in nic_override:
8671
        del args['nics'][-1]
8672

    
8673
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8674
    if self.op.disk_template:
8675
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8676
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8677
    return env, nl, nl
8678

    
8679
  def CheckPrereq(self):
8680
    """Check prerequisites.
8681

8682
    This only checks the instance list against the existing names.
8683

8684
    """
8685
    # checking the new params on the primary/secondary nodes
8686

    
8687
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8688
    cluster = self.cluster = self.cfg.GetClusterInfo()
8689
    assert self.instance is not None, \
8690
      "Cannot retrieve locked instance %s" % self.op.instance_name
8691
    pnode = instance.primary_node
8692
    nodelist = list(instance.all_nodes)
8693

    
8694
    # OS change
8695
    if self.op.os_name and not self.op.force:
8696
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8697
                      self.op.force_variant)
8698
      instance_os = self.op.os_name
8699
    else:
8700
      instance_os = instance.os
8701

    
8702
    if self.op.disk_template:
8703
      if instance.disk_template == self.op.disk_template:
8704
        raise errors.OpPrereqError("Instance already has disk template %s" %
8705
                                   instance.disk_template, errors.ECODE_INVAL)
8706

    
8707
      if (instance.disk_template,
8708
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8709
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8710
                                   " %s to %s" % (instance.disk_template,
8711
                                                  self.op.disk_template),
8712
                                   errors.ECODE_INVAL)
8713
      _CheckInstanceDown(self, instance, "cannot change disk template")
8714
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8715
        _CheckNodeOnline(self, self.op.remote_node)
8716
        _CheckNodeNotDrained(self, self.op.remote_node)
8717
        disks = [{"size": d.size} for d in instance.disks]
8718
        required = _ComputeDiskSize(self.op.disk_template, disks)
8719
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8720

    
8721
    # hvparams processing
8722
    if self.op.hvparams:
8723
      hv_type = instance.hypervisor
8724
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8725
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8726
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8727

    
8728
      # local check
8729
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8730
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8731
      self.hv_new = hv_new # the new actual values
8732
      self.hv_inst = i_hvdict # the new dict (without defaults)
8733
    else:
8734
      self.hv_new = self.hv_inst = {}
8735

    
8736
    # beparams processing
8737
    if self.op.beparams:
8738
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8739
                                   use_none=True)
8740
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8741
      be_new = cluster.SimpleFillBE(i_bedict)
8742
      self.be_new = be_new # the new actual values
8743
      self.be_inst = i_bedict # the new dict (without defaults)
8744
    else:
8745
      self.be_new = self.be_inst = {}
8746

    
8747
    # osparams processing
8748
    if self.op.osparams:
8749
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8750
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8751
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8752
      self.os_inst = i_osdict # the new dict (without defaults)
8753
    else:
8754
      self.os_new = self.os_inst = {}
8755

    
8756
    self.warn = []
8757

    
8758
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8759
      mem_check_list = [pnode]
8760
      if be_new[constants.BE_AUTO_BALANCE]:
8761
        # either we changed auto_balance to yes or it was from before
8762
        mem_check_list.extend(instance.secondary_nodes)
8763
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8764
                                                  instance.hypervisor)
8765
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8766
                                         instance.hypervisor)
8767
      pninfo = nodeinfo[pnode]
8768
      msg = pninfo.fail_msg
8769
      if msg:
8770
        # Assume the primary node is unreachable and go ahead
8771
        self.warn.append("Can't get info from primary node %s: %s" %
8772
                         (pnode,  msg))
8773
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8774
        self.warn.append("Node data from primary node %s doesn't contain"
8775
                         " free memory information" % pnode)
8776
      elif instance_info.fail_msg:
8777
        self.warn.append("Can't get instance runtime information: %s" %
8778
                        instance_info.fail_msg)
8779
      else:
8780
        if instance_info.payload:
8781
          current_mem = int(instance_info.payload['memory'])
8782
        else:
8783
          # Assume instance not running
8784
          # (there is a slight race condition here, but it's not very probable,
8785
          # and we have no other way to check)
8786
          current_mem = 0
8787
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8788
                    pninfo.payload['memory_free'])
8789
        if miss_mem > 0:
8790
          raise errors.OpPrereqError("This change will prevent the instance"
8791
                                     " from starting, due to %d MB of memory"
8792
                                     " missing on its primary node" % miss_mem,
8793
                                     errors.ECODE_NORES)
8794

    
8795
      if be_new[constants.BE_AUTO_BALANCE]:
8796
        for node, nres in nodeinfo.items():
8797
          if node not in instance.secondary_nodes:
8798
            continue
8799
          msg = nres.fail_msg
8800
          if msg:
8801
            self.warn.append("Can't get info from secondary node %s: %s" %
8802
                             (node, msg))
8803
          elif not isinstance(nres.payload.get('memory_free', None), int):
8804
            self.warn.append("Secondary node %s didn't return free"
8805
                             " memory information" % node)
8806
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8807
            self.warn.append("Not enough memory to failover instance to"
8808
                             " secondary node %s" % node)
8809

    
8810
    # NIC processing
8811
    self.nic_pnew = {}
8812
    self.nic_pinst = {}
8813
    for nic_op, nic_dict in self.op.nics:
8814
      if nic_op == constants.DDM_REMOVE:
8815
        if not instance.nics:
8816
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8817
                                     errors.ECODE_INVAL)
8818
        continue
8819
      if nic_op != constants.DDM_ADD:
8820
        # an existing nic
8821
        if not instance.nics:
8822
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8823
                                     " no NICs" % nic_op,
8824
                                     errors.ECODE_INVAL)
8825
        if nic_op < 0 or nic_op >= len(instance.nics):
8826
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8827
                                     " are 0 to %d" %
8828
                                     (nic_op, len(instance.nics) - 1),
8829
                                     errors.ECODE_INVAL)
8830
        old_nic_params = instance.nics[nic_op].nicparams
8831
        old_nic_ip = instance.nics[nic_op].ip
8832
      else:
8833
        old_nic_params = {}
8834
        old_nic_ip = None
8835

    
8836
      update_params_dict = dict([(key, nic_dict[key])
8837
                                 for key in constants.NICS_PARAMETERS
8838
                                 if key in nic_dict])
8839

    
8840
      if 'bridge' in nic_dict:
8841
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8842

    
8843
      new_nic_params = _GetUpdatedParams(old_nic_params,
8844
                                         update_params_dict)
8845
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8846
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8847
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8848
      self.nic_pinst[nic_op] = new_nic_params
8849
      self.nic_pnew[nic_op] = new_filled_nic_params
8850
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8851

    
8852
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8853
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8854
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8855
        if msg:
8856
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8857
          if self.op.force:
8858
            self.warn.append(msg)
8859
          else:
8860
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8861
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8862
        if 'ip' in nic_dict:
8863
          nic_ip = nic_dict['ip']
8864
        else:
8865
          nic_ip = old_nic_ip
8866
        if nic_ip is None:
8867
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8868
                                     ' on a routed nic', errors.ECODE_INVAL)
8869
      if 'mac' in nic_dict:
8870
        nic_mac = nic_dict['mac']
8871
        if nic_mac is None:
8872
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8873
                                     errors.ECODE_INVAL)
8874
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8875
          # otherwise generate the mac
8876
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8877
        else:
8878
          # or validate/reserve the current one
8879
          try:
8880
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8881
          except errors.ReservationError:
8882
            raise errors.OpPrereqError("MAC address %s already in use"
8883
                                       " in cluster" % nic_mac,
8884
                                       errors.ECODE_NOTUNIQUE)
8885

    
8886
    # DISK processing
8887
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8888
      raise errors.OpPrereqError("Disk operations not supported for"
8889
                                 " diskless instances",
8890
                                 errors.ECODE_INVAL)
8891
    for disk_op, _ in self.op.disks:
8892
      if disk_op == constants.DDM_REMOVE:
8893
        if len(instance.disks) == 1:
8894
          raise errors.OpPrereqError("Cannot remove the last disk of"
8895
                                     " an instance", errors.ECODE_INVAL)
8896
        _CheckInstanceDown(self, instance, "cannot remove disks")
8897

    
8898
      if (disk_op == constants.DDM_ADD and
8899
          len(instance.nics) >= constants.MAX_DISKS):
8900
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8901
                                   " add more" % constants.MAX_DISKS,
8902
                                   errors.ECODE_STATE)
8903
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8904
        # an existing disk
8905
        if disk_op < 0 or disk_op >= len(instance.disks):
8906
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8907
                                     " are 0 to %d" %
8908
                                     (disk_op, len(instance.disks)),
8909
                                     errors.ECODE_INVAL)
8910

    
8911
    return
8912

    
8913
  def _ConvertPlainToDrbd(self, feedback_fn):
8914
    """Converts an instance from plain to drbd.
8915

8916
    """
8917
    feedback_fn("Converting template to drbd")
8918
    instance = self.instance
8919
    pnode = instance.primary_node
8920
    snode = self.op.remote_node
8921

    
8922
    # create a fake disk info for _GenerateDiskTemplate
8923
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8924
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8925
                                      instance.name, pnode, [snode],
8926
                                      disk_info, None, None, 0)
8927
    info = _GetInstanceInfoText(instance)
8928
    feedback_fn("Creating aditional volumes...")
8929
    # first, create the missing data and meta devices
8930
    for disk in new_disks:
8931
      # unfortunately this is... not too nice
8932
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8933
                            info, True)
8934
      for child in disk.children:
8935
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8936
    # at this stage, all new LVs have been created, we can rename the
8937
    # old ones
8938
    feedback_fn("Renaming original volumes...")
8939
    rename_list = [(o, n.children[0].logical_id)
8940
                   for (o, n) in zip(instance.disks, new_disks)]
8941
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8942
    result.Raise("Failed to rename original LVs")
8943

    
8944
    feedback_fn("Initializing DRBD devices...")
8945
    # all child devices are in place, we can now create the DRBD devices
8946
    for disk in new_disks:
8947
      for node in [pnode, snode]:
8948
        f_create = node == pnode
8949
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8950

    
8951
    # at this point, the instance has been modified
8952
    instance.disk_template = constants.DT_DRBD8
8953
    instance.disks = new_disks
8954
    self.cfg.Update(instance, feedback_fn)
8955

    
8956
    # disks are created, waiting for sync
8957
    disk_abort = not _WaitForSync(self, instance)
8958
    if disk_abort:
8959
      raise errors.OpExecError("There are some degraded disks for"
8960
                               " this instance, please cleanup manually")
8961

    
8962
  def _ConvertDrbdToPlain(self, feedback_fn):
8963
    """Converts an instance from drbd to plain.
8964

8965
    """
8966
    instance = self.instance
8967
    assert len(instance.secondary_nodes) == 1
8968
    pnode = instance.primary_node
8969
    snode = instance.secondary_nodes[0]
8970
    feedback_fn("Converting template to plain")
8971

    
8972
    old_disks = instance.disks
8973
    new_disks = [d.children[0] for d in old_disks]
8974

    
8975
    # copy over size and mode
8976
    for parent, child in zip(old_disks, new_disks):
8977
      child.size = parent.size
8978
      child.mode = parent.mode
8979

    
8980
    # update instance structure
8981
    instance.disks = new_disks
8982
    instance.disk_template = constants.DT_PLAIN
8983
    self.cfg.Update(instance, feedback_fn)
8984

    
8985
    feedback_fn("Removing volumes on the secondary node...")
8986
    for disk in old_disks:
8987
      self.cfg.SetDiskID(disk, snode)
8988
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8989
      if msg:
8990
        self.LogWarning("Could not remove block device %s on node %s,"
8991
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8992

    
8993
    feedback_fn("Removing unneeded volumes on the primary node...")
8994
    for idx, disk in enumerate(old_disks):
8995
      meta = disk.children[1]
8996
      self.cfg.SetDiskID(meta, pnode)
8997
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8998
      if msg:
8999
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9000
                        " continuing anyway: %s", idx, pnode, msg)
9001

    
9002

    
9003
  def Exec(self, feedback_fn):
9004
    """Modifies an instance.
9005

9006
    All parameters take effect only at the next restart of the instance.
9007

9008
    """
9009
    # Process here the warnings from CheckPrereq, as we don't have a
9010
    # feedback_fn there.
9011
    for warn in self.warn:
9012
      feedback_fn("WARNING: %s" % warn)
9013

    
9014
    result = []
9015
    instance = self.instance
9016
    # disk changes
9017
    for disk_op, disk_dict in self.op.disks:
9018
      if disk_op == constants.DDM_REMOVE:
9019
        # remove the last disk
9020
        device = instance.disks.pop()
9021
        device_idx = len(instance.disks)
9022
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9023
          self.cfg.SetDiskID(disk, node)
9024
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9025
          if msg:
9026
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9027
                            " continuing anyway", device_idx, node, msg)
9028
        result.append(("disk/%d" % device_idx, "remove"))
9029
      elif disk_op == constants.DDM_ADD:
9030
        # add a new disk
9031
        if instance.disk_template == constants.DT_FILE:
9032
          file_driver, file_path = instance.disks[0].logical_id
9033
          file_path = os.path.dirname(file_path)
9034
        else:
9035
          file_driver = file_path = None
9036
        disk_idx_base = len(instance.disks)
9037
        new_disk = _GenerateDiskTemplate(self,
9038
                                         instance.disk_template,
9039
                                         instance.name, instance.primary_node,
9040
                                         instance.secondary_nodes,
9041
                                         [disk_dict],
9042
                                         file_path,
9043
                                         file_driver,
9044
                                         disk_idx_base)[0]
9045
        instance.disks.append(new_disk)
9046
        info = _GetInstanceInfoText(instance)
9047

    
9048
        logging.info("Creating volume %s for instance %s",
9049
                     new_disk.iv_name, instance.name)
9050
        # Note: this needs to be kept in sync with _CreateDisks
9051
        #HARDCODE
9052
        for node in instance.all_nodes:
9053
          f_create = node == instance.primary_node
9054
          try:
9055
            _CreateBlockDev(self, node, instance, new_disk,
9056
                            f_create, info, f_create)
9057
          except errors.OpExecError, err:
9058
            self.LogWarning("Failed to create volume %s (%s) on"
9059
                            " node %s: %s",
9060
                            new_disk.iv_name, new_disk, node, err)
9061
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9062
                       (new_disk.size, new_disk.mode)))
9063
      else:
9064
        # change a given disk
9065
        instance.disks[disk_op].mode = disk_dict['mode']
9066
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9067

    
9068
    if self.op.disk_template:
9069
      r_shut = _ShutdownInstanceDisks(self, instance)
9070
      if not r_shut:
9071
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9072
                                 " proceed with disk template conversion")
9073
      mode = (instance.disk_template, self.op.disk_template)
9074
      try:
9075
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9076
      except:
9077
        self.cfg.ReleaseDRBDMinors(instance.name)
9078
        raise
9079
      result.append(("disk_template", self.op.disk_template))
9080

    
9081
    # NIC changes
9082
    for nic_op, nic_dict in self.op.nics:
9083
      if nic_op == constants.DDM_REMOVE:
9084
        # remove the last nic
9085
        del instance.nics[-1]
9086
        result.append(("nic.%d" % len(instance.nics), "remove"))
9087
      elif nic_op == constants.DDM_ADD:
9088
        # mac and bridge should be set, by now
9089
        mac = nic_dict['mac']
9090
        ip = nic_dict.get('ip', None)
9091
        nicparams = self.nic_pinst[constants.DDM_ADD]
9092
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9093
        instance.nics.append(new_nic)
9094
        result.append(("nic.%d" % (len(instance.nics) - 1),
9095
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9096
                       (new_nic.mac, new_nic.ip,
9097
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9098
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9099
                       )))
9100
      else:
9101
        for key in 'mac', 'ip':
9102
          if key in nic_dict:
9103
            setattr(instance.nics[nic_op], key, nic_dict[key])
9104
        if nic_op in self.nic_pinst:
9105
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9106
        for key, val in nic_dict.iteritems():
9107
          result.append(("nic.%s/%d" % (key, nic_op), val))
9108

    
9109
    # hvparams changes
9110
    if self.op.hvparams:
9111
      instance.hvparams = self.hv_inst
9112
      for key, val in self.op.hvparams.iteritems():
9113
        result.append(("hv/%s" % key, val))
9114

    
9115
    # beparams changes
9116
    if self.op.beparams:
9117
      instance.beparams = self.be_inst
9118
      for key, val in self.op.beparams.iteritems():
9119
        result.append(("be/%s" % key, val))
9120

    
9121
    # OS change
9122
    if self.op.os_name:
9123
      instance.os = self.op.os_name
9124

    
9125
    # osparams changes
9126
    if self.op.osparams:
9127
      instance.osparams = self.os_inst
9128
      for key, val in self.op.osparams.iteritems():
9129
        result.append(("os/%s" % key, val))
9130

    
9131
    self.cfg.Update(instance, feedback_fn)
9132

    
9133
    return result
9134

    
9135
  _DISK_CONVERSIONS = {
9136
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9137
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9138
    }
9139

    
9140

    
9141
class LUQueryExports(NoHooksLU):
9142
  """Query the exports list
9143

9144
  """
9145
  _OP_PARAMS = [
9146
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9147
    ("use_locking", False, _TBool),
9148
    ]
9149
  REQ_BGL = False
9150

    
9151
  def ExpandNames(self):
9152
    self.needed_locks = {}
9153
    self.share_locks[locking.LEVEL_NODE] = 1
9154
    if not self.op.nodes:
9155
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9156
    else:
9157
      self.needed_locks[locking.LEVEL_NODE] = \
9158
        _GetWantedNodes(self, self.op.nodes)
9159

    
9160
  def Exec(self, feedback_fn):
9161
    """Compute the list of all the exported system images.
9162

9163
    @rtype: dict
9164
    @return: a dictionary with the structure node->(export-list)
9165
        where export-list is a list of the instances exported on
9166
        that node.
9167

9168
    """
9169
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9170
    rpcresult = self.rpc.call_export_list(self.nodes)
9171
    result = {}
9172
    for node in rpcresult:
9173
      if rpcresult[node].fail_msg:
9174
        result[node] = False
9175
      else:
9176
        result[node] = rpcresult[node].payload
9177

    
9178
    return result
9179

    
9180

    
9181
class LUPrepareExport(NoHooksLU):
9182
  """Prepares an instance for an export and returns useful information.
9183

9184
  """
9185
  _OP_PARAMS = [
9186
    _PInstanceName,
9187
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9188
    ]
9189
  REQ_BGL = False
9190

    
9191
  def ExpandNames(self):
9192
    self._ExpandAndLockInstance()
9193

    
9194
  def CheckPrereq(self):
9195
    """Check prerequisites.
9196

9197
    """
9198
    instance_name = self.op.instance_name
9199

    
9200
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9201
    assert self.instance is not None, \
9202
          "Cannot retrieve locked instance %s" % self.op.instance_name
9203
    _CheckNodeOnline(self, self.instance.primary_node)
9204

    
9205
    self._cds = _GetClusterDomainSecret()
9206

    
9207
  def Exec(self, feedback_fn):
9208
    """Prepares an instance for an export.
9209

9210
    """
9211
    instance = self.instance
9212

    
9213
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9214
      salt = utils.GenerateSecret(8)
9215

    
9216
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9217
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9218
                                              constants.RIE_CERT_VALIDITY)
9219
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9220

    
9221
      (name, cert_pem) = result.payload
9222

    
9223
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9224
                                             cert_pem)
9225

    
9226
      return {
9227
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9228
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9229
                          salt),
9230
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9231
        }
9232

    
9233
    return None
9234

    
9235

    
9236
class LUExportInstance(LogicalUnit):
9237
  """Export an instance to an image in the cluster.
9238

9239
  """
9240
  HPATH = "instance-export"
9241
  HTYPE = constants.HTYPE_INSTANCE
9242
  _OP_PARAMS = [
9243
    _PInstanceName,
9244
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9245
    ("shutdown", True, _TBool),
9246
    _PShutdownTimeout,
9247
    ("remove_instance", False, _TBool),
9248
    ("ignore_remove_failures", False, _TBool),
9249
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9250
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9251
    ("destination_x509_ca", None, _TMaybeString),
9252
    ]
9253
  REQ_BGL = False
9254

    
9255
  def CheckArguments(self):
9256
    """Check the arguments.
9257

9258
    """
9259
    self.x509_key_name = self.op.x509_key_name
9260
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9261

    
9262
    if self.op.remove_instance and not self.op.shutdown:
9263
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9264
                                 " down before")
9265

    
9266
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9267
      if not self.x509_key_name:
9268
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9269
                                   errors.ECODE_INVAL)
9270

    
9271
      if not self.dest_x509_ca_pem:
9272
        raise errors.OpPrereqError("Missing destination X509 CA",
9273
                                   errors.ECODE_INVAL)
9274

    
9275
  def ExpandNames(self):
9276
    self._ExpandAndLockInstance()
9277

    
9278
    # Lock all nodes for local exports
9279
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9280
      # FIXME: lock only instance primary and destination node
9281
      #
9282
      # Sad but true, for now we have do lock all nodes, as we don't know where
9283
      # the previous export might be, and in this LU we search for it and
9284
      # remove it from its current node. In the future we could fix this by:
9285
      #  - making a tasklet to search (share-lock all), then create the
9286
      #    new one, then one to remove, after
9287
      #  - removing the removal operation altogether
9288
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9289

    
9290
  def DeclareLocks(self, level):
9291
    """Last minute lock declaration."""
9292
    # All nodes are locked anyway, so nothing to do here.
9293

    
9294
  def BuildHooksEnv(self):
9295
    """Build hooks env.
9296

9297
    This will run on the master, primary node and target node.
9298

9299
    """
9300
    env = {
9301
      "EXPORT_MODE": self.op.mode,
9302
      "EXPORT_NODE": self.op.target_node,
9303
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9304
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9305
      # TODO: Generic function for boolean env variables
9306
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9307
      }
9308

    
9309
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9310

    
9311
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9312

    
9313
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9314
      nl.append(self.op.target_node)
9315

    
9316
    return env, nl, nl
9317

    
9318
  def CheckPrereq(self):
9319
    """Check prerequisites.
9320

9321
    This checks that the instance and node names are valid.
9322

9323
    """
9324
    instance_name = self.op.instance_name
9325

    
9326
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9327
    assert self.instance is not None, \
9328
          "Cannot retrieve locked instance %s" % self.op.instance_name
9329
    _CheckNodeOnline(self, self.instance.primary_node)
9330

    
9331
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9332
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9333
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9334
      assert self.dst_node is not None
9335

    
9336
      _CheckNodeOnline(self, self.dst_node.name)
9337
      _CheckNodeNotDrained(self, self.dst_node.name)
9338

    
9339
      self._cds = None
9340
      self.dest_disk_info = None
9341
      self.dest_x509_ca = None
9342

    
9343
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9344
      self.dst_node = None
9345

    
9346
      if len(self.op.target_node) != len(self.instance.disks):
9347
        raise errors.OpPrereqError(("Received destination information for %s"
9348
                                    " disks, but instance %s has %s disks") %
9349
                                   (len(self.op.target_node), instance_name,
9350
                                    len(self.instance.disks)),
9351
                                   errors.ECODE_INVAL)
9352

    
9353
      cds = _GetClusterDomainSecret()
9354

    
9355
      # Check X509 key name
9356
      try:
9357
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9358
      except (TypeError, ValueError), err:
9359
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9360

    
9361
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9362
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9363
                                   errors.ECODE_INVAL)
9364

    
9365
      # Load and verify CA
9366
      try:
9367
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9368
      except OpenSSL.crypto.Error, err:
9369
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9370
                                   (err, ), errors.ECODE_INVAL)
9371

    
9372
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9373
      if errcode is not None:
9374
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9375
                                   (msg, ), errors.ECODE_INVAL)
9376

    
9377
      self.dest_x509_ca = cert
9378

    
9379
      # Verify target information
9380
      disk_info = []
9381
      for idx, disk_data in enumerate(self.op.target_node):
9382
        try:
9383
          (host, port, magic) = \
9384
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9385
        except errors.GenericError, err:
9386
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9387
                                     (idx, err), errors.ECODE_INVAL)
9388

    
9389
        disk_info.append((host, port, magic))
9390

    
9391
      assert len(disk_info) == len(self.op.target_node)
9392
      self.dest_disk_info = disk_info
9393

    
9394
    else:
9395
      raise errors.ProgrammerError("Unhandled export mode %r" %
9396
                                   self.op.mode)
9397

    
9398
    # instance disk type verification
9399
    # TODO: Implement export support for file-based disks
9400
    for disk in self.instance.disks:
9401
      if disk.dev_type == constants.LD_FILE:
9402
        raise errors.OpPrereqError("Export not supported for instances with"
9403
                                   " file-based disks", errors.ECODE_INVAL)
9404

    
9405
  def _CleanupExports(self, feedback_fn):
9406
    """Removes exports of current instance from all other nodes.
9407

9408
    If an instance in a cluster with nodes A..D was exported to node C, its
9409
    exports will be removed from the nodes A, B and D.
9410

9411
    """
9412
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9413

    
9414
    nodelist = self.cfg.GetNodeList()
9415
    nodelist.remove(self.dst_node.name)
9416

    
9417
    # on one-node clusters nodelist will be empty after the removal
9418
    # if we proceed the backup would be removed because OpQueryExports
9419
    # substitutes an empty list with the full cluster node list.
9420
    iname = self.instance.name
9421
    if nodelist:
9422
      feedback_fn("Removing old exports for instance %s" % iname)
9423
      exportlist = self.rpc.call_export_list(nodelist)
9424
      for node in exportlist:
9425
        if exportlist[node].fail_msg:
9426
          continue
9427
        if iname in exportlist[node].payload:
9428
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9429
          if msg:
9430
            self.LogWarning("Could not remove older export for instance %s"
9431
                            " on node %s: %s", iname, node, msg)
9432

    
9433
  def Exec(self, feedback_fn):
9434
    """Export an instance to an image in the cluster.
9435

9436
    """
9437
    assert self.op.mode in constants.EXPORT_MODES
9438

    
9439
    instance = self.instance
9440
    src_node = instance.primary_node
9441

    
9442
    if self.op.shutdown:
9443
      # shutdown the instance, but not the disks
9444
      feedback_fn("Shutting down instance %s" % instance.name)
9445
      result = self.rpc.call_instance_shutdown(src_node, instance,
9446
                                               self.op.shutdown_timeout)
9447
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9448
      result.Raise("Could not shutdown instance %s on"
9449
                   " node %s" % (instance.name, src_node))
9450

    
9451
    # set the disks ID correctly since call_instance_start needs the
9452
    # correct drbd minor to create the symlinks
9453
    for disk in instance.disks:
9454
      self.cfg.SetDiskID(disk, src_node)
9455

    
9456
    activate_disks = (not instance.admin_up)
9457

    
9458
    if activate_disks:
9459
      # Activate the instance disks if we'exporting a stopped instance
9460
      feedback_fn("Activating disks for %s" % instance.name)
9461
      _StartInstanceDisks(self, instance, None)
9462

    
9463
    try:
9464
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9465
                                                     instance)
9466

    
9467
      helper.CreateSnapshots()
9468
      try:
9469
        if (self.op.shutdown and instance.admin_up and
9470
            not self.op.remove_instance):
9471
          assert not activate_disks
9472
          feedback_fn("Starting instance %s" % instance.name)
9473
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9474
          msg = result.fail_msg
9475
          if msg:
9476
            feedback_fn("Failed to start instance: %s" % msg)
9477
            _ShutdownInstanceDisks(self, instance)
9478
            raise errors.OpExecError("Could not start instance: %s" % msg)
9479

    
9480
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9481
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9482
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9483
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9484
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9485

    
9486
          (key_name, _, _) = self.x509_key_name
9487

    
9488
          dest_ca_pem = \
9489
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9490
                                            self.dest_x509_ca)
9491

    
9492
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9493
                                                     key_name, dest_ca_pem,
9494
                                                     timeouts)
9495
      finally:
9496
        helper.Cleanup()
9497

    
9498
      # Check for backwards compatibility
9499
      assert len(dresults) == len(instance.disks)
9500
      assert compat.all(isinstance(i, bool) for i in dresults), \
9501
             "Not all results are boolean: %r" % dresults
9502

    
9503
    finally:
9504
      if activate_disks:
9505
        feedback_fn("Deactivating disks for %s" % instance.name)
9506
        _ShutdownInstanceDisks(self, instance)
9507

    
9508
    # Remove instance if requested
9509
    if self.op.remove_instance:
9510
      if not (compat.all(dresults) and fin_resu):
9511
        feedback_fn("Not removing instance %s as parts of the export failed" %
9512
                    instance.name)
9513
      else:
9514
        feedback_fn("Removing instance %s" % instance.name)
9515
        _RemoveInstance(self, feedback_fn, instance,
9516
                        self.op.ignore_remove_failures)
9517

    
9518
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9519
      self._CleanupExports(feedback_fn)
9520

    
9521
    return fin_resu, dresults
9522

    
9523

    
9524
class LURemoveExport(NoHooksLU):
9525
  """Remove exports related to the named instance.
9526

9527
  """
9528
  _OP_PARAMS = [
9529
    _PInstanceName,
9530
    ]
9531
  REQ_BGL = False
9532

    
9533
  def ExpandNames(self):
9534
    self.needed_locks = {}
9535
    # We need all nodes to be locked in order for RemoveExport to work, but we
9536
    # don't need to lock the instance itself, as nothing will happen to it (and
9537
    # we can remove exports also for a removed instance)
9538
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9539

    
9540
  def Exec(self, feedback_fn):
9541
    """Remove any export.
9542

9543
    """
9544
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9545
    # If the instance was not found we'll try with the name that was passed in.
9546
    # This will only work if it was an FQDN, though.
9547
    fqdn_warn = False
9548
    if not instance_name:
9549
      fqdn_warn = True
9550
      instance_name = self.op.instance_name
9551

    
9552
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9553
    exportlist = self.rpc.call_export_list(locked_nodes)
9554
    found = False
9555
    for node in exportlist:
9556
      msg = exportlist[node].fail_msg
9557
      if msg:
9558
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9559
        continue
9560
      if instance_name in exportlist[node].payload:
9561
        found = True
9562
        result = self.rpc.call_export_remove(node, instance_name)
9563
        msg = result.fail_msg
9564
        if msg:
9565
          logging.error("Could not remove export for instance %s"
9566
                        " on node %s: %s", instance_name, node, msg)
9567

    
9568
    if fqdn_warn and not found:
9569
      feedback_fn("Export not found. If trying to remove an export belonging"
9570
                  " to a deleted instance please use its Fully Qualified"
9571
                  " Domain Name.")
9572

    
9573

    
9574
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9575
  """Generic tags LU.
9576

9577
  This is an abstract class which is the parent of all the other tags LUs.
9578

9579
  """
9580

    
9581
  def ExpandNames(self):
9582
    self.needed_locks = {}
9583
    if self.op.kind == constants.TAG_NODE:
9584
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9585
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9586
    elif self.op.kind == constants.TAG_INSTANCE:
9587
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9588
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9589

    
9590
  def CheckPrereq(self):
9591
    """Check prerequisites.
9592

9593
    """
9594
    if self.op.kind == constants.TAG_CLUSTER:
9595
      self.target = self.cfg.GetClusterInfo()
9596
    elif self.op.kind == constants.TAG_NODE:
9597
      self.target = self.cfg.GetNodeInfo(self.op.name)
9598
    elif self.op.kind == constants.TAG_INSTANCE:
9599
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9600
    else:
9601
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9602
                                 str(self.op.kind), errors.ECODE_INVAL)
9603

    
9604

    
9605
class LUGetTags(TagsLU):
9606
  """Returns the tags of a given object.
9607

9608
  """
9609
  _OP_PARAMS = [
9610
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9611
    ("name", _NoDefault, _TNonEmptyString),
9612
    ]
9613
  REQ_BGL = False
9614

    
9615
  def Exec(self, feedback_fn):
9616
    """Returns the tag list.
9617

9618
    """
9619
    return list(self.target.GetTags())
9620

    
9621

    
9622
class LUSearchTags(NoHooksLU):
9623
  """Searches the tags for a given pattern.
9624

9625
  """
9626
  _OP_PARAMS = [
9627
    ("pattern", _NoDefault, _TNonEmptyString),
9628
    ]
9629
  REQ_BGL = False
9630

    
9631
  def ExpandNames(self):
9632
    self.needed_locks = {}
9633

    
9634
  def CheckPrereq(self):
9635
    """Check prerequisites.
9636

9637
    This checks the pattern passed for validity by compiling it.
9638

9639
    """
9640
    try:
9641
      self.re = re.compile(self.op.pattern)
9642
    except re.error, err:
9643
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9644
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9645

    
9646
  def Exec(self, feedback_fn):
9647
    """Returns the tag list.
9648

9649
    """
9650
    cfg = self.cfg
9651
    tgts = [("/cluster", cfg.GetClusterInfo())]
9652
    ilist = cfg.GetAllInstancesInfo().values()
9653
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9654
    nlist = cfg.GetAllNodesInfo().values()
9655
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9656
    results = []
9657
    for path, target in tgts:
9658
      for tag in target.GetTags():
9659
        if self.re.search(tag):
9660
          results.append((path, tag))
9661
    return results
9662

    
9663

    
9664
class LUAddTags(TagsLU):
9665
  """Sets a tag on a given object.
9666

9667
  """
9668
  _OP_PARAMS = [
9669
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9670
    ("name", _NoDefault, _TNonEmptyString),
9671
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9672
    ]
9673
  REQ_BGL = False
9674

    
9675
  def CheckPrereq(self):
9676
    """Check prerequisites.
9677

9678
    This checks the type and length of the tag name and value.
9679

9680
    """
9681
    TagsLU.CheckPrereq(self)
9682
    for tag in self.op.tags:
9683
      objects.TaggableObject.ValidateTag(tag)
9684

    
9685
  def Exec(self, feedback_fn):
9686
    """Sets the tag.
9687

9688
    """
9689
    try:
9690
      for tag in self.op.tags:
9691
        self.target.AddTag(tag)
9692
    except errors.TagError, err:
9693
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9694
    self.cfg.Update(self.target, feedback_fn)
9695

    
9696

    
9697
class LUDelTags(TagsLU):
9698
  """Delete a list of tags from a given object.
9699

9700
  """
9701
  _OP_PARAMS = [
9702
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9703
    ("name", _NoDefault, _TNonEmptyString),
9704
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9705
    ]
9706
  REQ_BGL = False
9707

    
9708
  def CheckPrereq(self):
9709
    """Check prerequisites.
9710

9711
    This checks that we have the given tag.
9712

9713
    """
9714
    TagsLU.CheckPrereq(self)
9715
    for tag in self.op.tags:
9716
      objects.TaggableObject.ValidateTag(tag)
9717
    del_tags = frozenset(self.op.tags)
9718
    cur_tags = self.target.GetTags()
9719
    if not del_tags <= cur_tags:
9720
      diff_tags = del_tags - cur_tags
9721
      diff_names = ["'%s'" % tag for tag in diff_tags]
9722
      diff_names.sort()
9723
      raise errors.OpPrereqError("Tag(s) %s not found" %
9724
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9725

    
9726
  def Exec(self, feedback_fn):
9727
    """Remove the tag from the object.
9728

9729
    """
9730
    for tag in self.op.tags:
9731
      self.target.RemoveTag(tag)
9732
    self.cfg.Update(self.target, feedback_fn)
9733

    
9734

    
9735
class LUTestDelay(NoHooksLU):
9736
  """Sleep for a specified amount of time.
9737

9738
  This LU sleeps on the master and/or nodes for a specified amount of
9739
  time.
9740

9741
  """
9742
  _OP_PARAMS = [
9743
    ("duration", _NoDefault, _TFloat),
9744
    ("on_master", True, _TBool),
9745
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9746
    ("repeat", 0, _TPositiveInt)
9747
    ]
9748
  REQ_BGL = False
9749

    
9750
  def ExpandNames(self):
9751
    """Expand names and set required locks.
9752

9753
    This expands the node list, if any.
9754

9755
    """
9756
    self.needed_locks = {}
9757
    if self.op.on_nodes:
9758
      # _GetWantedNodes can be used here, but is not always appropriate to use
9759
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9760
      # more information.
9761
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9762
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9763

    
9764
  def _TestDelay(self):
9765
    """Do the actual sleep.
9766

9767
    """
9768
    if self.op.on_master:
9769
      if not utils.TestDelay(self.op.duration):
9770
        raise errors.OpExecError("Error during master delay test")
9771
    if self.op.on_nodes:
9772
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9773
      for node, node_result in result.items():
9774
        node_result.Raise("Failure during rpc call to node %s" % node)
9775

    
9776
  def Exec(self, feedback_fn):
9777
    """Execute the test delay opcode, with the wanted repetitions.
9778

9779
    """
9780
    if self.op.repeat == 0:
9781
      self._TestDelay()
9782
    else:
9783
      top_value = self.op.repeat - 1
9784
      for i in range(self.op.repeat):
9785
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9786
        self._TestDelay()
9787

    
9788

    
9789
class IAllocator(object):
9790
  """IAllocator framework.
9791

9792
  An IAllocator instance has three sets of attributes:
9793
    - cfg that is needed to query the cluster
9794
    - input data (all members of the _KEYS class attribute are required)
9795
    - four buffer attributes (in|out_data|text), that represent the
9796
      input (to the external script) in text and data structure format,
9797
      and the output from it, again in two formats
9798
    - the result variables from the script (success, info, nodes) for
9799
      easy usage
9800

9801
  """
9802
  # pylint: disable-msg=R0902
9803
  # lots of instance attributes
9804
  _ALLO_KEYS = [
9805
    "name", "mem_size", "disks", "disk_template",
9806
    "os", "tags", "nics", "vcpus", "hypervisor",
9807
    ]
9808
  _RELO_KEYS = [
9809
    "name", "relocate_from",
9810
    ]
9811
  _EVAC_KEYS = [
9812
    "evac_nodes",
9813
    ]
9814

    
9815
  def __init__(self, cfg, rpc, mode, **kwargs):
9816
    self.cfg = cfg
9817
    self.rpc = rpc
9818
    # init buffer variables
9819
    self.in_text = self.out_text = self.in_data = self.out_data = None
9820
    # init all input fields so that pylint is happy
9821
    self.mode = mode
9822
    self.mem_size = self.disks = self.disk_template = None
9823
    self.os = self.tags = self.nics = self.vcpus = None
9824
    self.hypervisor = None
9825
    self.relocate_from = None
9826
    self.name = None
9827
    self.evac_nodes = None
9828
    # computed fields
9829
    self.required_nodes = None
9830
    # init result fields
9831
    self.success = self.info = self.result = None
9832
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9833
      keyset = self._ALLO_KEYS
9834
      fn = self._AddNewInstance
9835
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9836
      keyset = self._RELO_KEYS
9837
      fn = self._AddRelocateInstance
9838
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9839
      keyset = self._EVAC_KEYS
9840
      fn = self._AddEvacuateNodes
9841
    else:
9842
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9843
                                   " IAllocator" % self.mode)
9844
    for key in kwargs:
9845
      if key not in keyset:
9846
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9847
                                     " IAllocator" % key)
9848
      setattr(self, key, kwargs[key])
9849

    
9850
    for key in keyset:
9851
      if key not in kwargs:
9852
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9853
                                     " IAllocator" % key)
9854
    self._BuildInputData(fn)
9855

    
9856
  def _ComputeClusterData(self):
9857
    """Compute the generic allocator input data.
9858

9859
    This is the data that is independent of the actual operation.
9860

9861
    """
9862
    cfg = self.cfg
9863
    cluster_info = cfg.GetClusterInfo()
9864
    # cluster data
9865
    data = {
9866
      "version": constants.IALLOCATOR_VERSION,
9867
      "cluster_name": cfg.GetClusterName(),
9868
      "cluster_tags": list(cluster_info.GetTags()),
9869
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9870
      # we don't have job IDs
9871
      }
9872
    iinfo = cfg.GetAllInstancesInfo().values()
9873
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9874

    
9875
    # node data
9876
    node_results = {}
9877
    node_list = cfg.GetNodeList()
9878

    
9879
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9880
      hypervisor_name = self.hypervisor
9881
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9882
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9883
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9884
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9885

    
9886
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9887
                                        hypervisor_name)
9888
    node_iinfo = \
9889
      self.rpc.call_all_instances_info(node_list,
9890
                                       cluster_info.enabled_hypervisors)
9891
    for nname, nresult in node_data.items():
9892
      # first fill in static (config-based) values
9893
      ninfo = cfg.GetNodeInfo(nname)
9894
      pnr = {
9895
        "tags": list(ninfo.GetTags()),
9896
        "primary_ip": ninfo.primary_ip,
9897
        "secondary_ip": ninfo.secondary_ip,
9898
        "offline": ninfo.offline,
9899
        "drained": ninfo.drained,
9900
        "master_candidate": ninfo.master_candidate,
9901
        }
9902

    
9903
      if not (ninfo.offline or ninfo.drained):
9904
        nresult.Raise("Can't get data for node %s" % nname)
9905
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9906
                                nname)
9907
        remote_info = nresult.payload
9908

    
9909
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9910
                     'vg_size', 'vg_free', 'cpu_total']:
9911
          if attr not in remote_info:
9912
            raise errors.OpExecError("Node '%s' didn't return attribute"
9913
                                     " '%s'" % (nname, attr))
9914
          if not isinstance(remote_info[attr], int):
9915
            raise errors.OpExecError("Node '%s' returned invalid value"
9916
                                     " for '%s': %s" %
9917
                                     (nname, attr, remote_info[attr]))
9918
        # compute memory used by primary instances
9919
        i_p_mem = i_p_up_mem = 0
9920
        for iinfo, beinfo in i_list:
9921
          if iinfo.primary_node == nname:
9922
            i_p_mem += beinfo[constants.BE_MEMORY]
9923
            if iinfo.name not in node_iinfo[nname].payload:
9924
              i_used_mem = 0
9925
            else:
9926
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9927
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9928
            remote_info['memory_free'] -= max(0, i_mem_diff)
9929

    
9930
            if iinfo.admin_up:
9931
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9932

    
9933
        # compute memory used by instances
9934
        pnr_dyn = {
9935
          "total_memory": remote_info['memory_total'],
9936
          "reserved_memory": remote_info['memory_dom0'],
9937
          "free_memory": remote_info['memory_free'],
9938
          "total_disk": remote_info['vg_size'],
9939
          "free_disk": remote_info['vg_free'],
9940
          "total_cpus": remote_info['cpu_total'],
9941
          "i_pri_memory": i_p_mem,
9942
          "i_pri_up_memory": i_p_up_mem,
9943
          }
9944
        pnr.update(pnr_dyn)
9945

    
9946
      node_results[nname] = pnr
9947
    data["nodes"] = node_results
9948

    
9949
    # instance data
9950
    instance_data = {}
9951
    for iinfo, beinfo in i_list:
9952
      nic_data = []
9953
      for nic in iinfo.nics:
9954
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
9955
        nic_dict = {"mac": nic.mac,
9956
                    "ip": nic.ip,
9957
                    "mode": filled_params[constants.NIC_MODE],
9958
                    "link": filled_params[constants.NIC_LINK],
9959
                   }
9960
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9961
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9962
        nic_data.append(nic_dict)
9963
      pir = {
9964
        "tags": list(iinfo.GetTags()),
9965
        "admin_up": iinfo.admin_up,
9966
        "vcpus": beinfo[constants.BE_VCPUS],
9967
        "memory": beinfo[constants.BE_MEMORY],
9968
        "os": iinfo.os,
9969
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9970
        "nics": nic_data,
9971
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9972
        "disk_template": iinfo.disk_template,
9973
        "hypervisor": iinfo.hypervisor,
9974
        }
9975
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9976
                                                 pir["disks"])
9977
      instance_data[iinfo.name] = pir
9978

    
9979
    data["instances"] = instance_data
9980

    
9981
    self.in_data = data
9982

    
9983
  def _AddNewInstance(self):
9984
    """Add new instance data to allocator structure.
9985

9986
    This in combination with _AllocatorGetClusterData will create the
9987
    correct structure needed as input for the allocator.
9988

9989
    The checks for the completeness of the opcode must have already been
9990
    done.
9991

9992
    """
9993
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9994

    
9995
    if self.disk_template in constants.DTS_NET_MIRROR:
9996
      self.required_nodes = 2
9997
    else:
9998
      self.required_nodes = 1
9999
    request = {
10000
      "name": self.name,
10001
      "disk_template": self.disk_template,
10002
      "tags": self.tags,
10003
      "os": self.os,
10004
      "vcpus": self.vcpus,
10005
      "memory": self.mem_size,
10006
      "disks": self.disks,
10007
      "disk_space_total": disk_space,
10008
      "nics": self.nics,
10009
      "required_nodes": self.required_nodes,
10010
      }
10011
    return request
10012

    
10013
  def _AddRelocateInstance(self):
10014
    """Add relocate instance data to allocator structure.
10015

10016
    This in combination with _IAllocatorGetClusterData will create the
10017
    correct structure needed as input for the allocator.
10018

10019
    The checks for the completeness of the opcode must have already been
10020
    done.
10021

10022
    """
10023
    instance = self.cfg.GetInstanceInfo(self.name)
10024
    if instance is None:
10025
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10026
                                   " IAllocator" % self.name)
10027

    
10028
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10029
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10030
                                 errors.ECODE_INVAL)
10031

    
10032
    if len(instance.secondary_nodes) != 1:
10033
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10034
                                 errors.ECODE_STATE)
10035

    
10036
    self.required_nodes = 1
10037
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10038
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10039

    
10040
    request = {
10041
      "name": self.name,
10042
      "disk_space_total": disk_space,
10043
      "required_nodes": self.required_nodes,
10044
      "relocate_from": self.relocate_from,
10045
      }
10046
    return request
10047

    
10048
  def _AddEvacuateNodes(self):
10049
    """Add evacuate nodes data to allocator structure.
10050

10051
    """
10052
    request = {
10053
      "evac_nodes": self.evac_nodes
10054
      }
10055
    return request
10056

    
10057
  def _BuildInputData(self, fn):
10058
    """Build input data structures.
10059

10060
    """
10061
    self._ComputeClusterData()
10062

    
10063
    request = fn()
10064
    request["type"] = self.mode
10065
    self.in_data["request"] = request
10066

    
10067
    self.in_text = serializer.Dump(self.in_data)
10068

    
10069
  def Run(self, name, validate=True, call_fn=None):
10070
    """Run an instance allocator and return the results.
10071

10072
    """
10073
    if call_fn is None:
10074
      call_fn = self.rpc.call_iallocator_runner
10075

    
10076
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10077
    result.Raise("Failure while running the iallocator script")
10078

    
10079
    self.out_text = result.payload
10080
    if validate:
10081
      self._ValidateResult()
10082

    
10083
  def _ValidateResult(self):
10084
    """Process the allocator results.
10085

10086
    This will process and if successful save the result in
10087
    self.out_data and the other parameters.
10088

10089
    """
10090
    try:
10091
      rdict = serializer.Load(self.out_text)
10092
    except Exception, err:
10093
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10094

    
10095
    if not isinstance(rdict, dict):
10096
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10097

    
10098
    # TODO: remove backwards compatiblity in later versions
10099
    if "nodes" in rdict and "result" not in rdict:
10100
      rdict["result"] = rdict["nodes"]
10101
      del rdict["nodes"]
10102

    
10103
    for key in "success", "info", "result":
10104
      if key not in rdict:
10105
        raise errors.OpExecError("Can't parse iallocator results:"
10106
                                 " missing key '%s'" % key)
10107
      setattr(self, key, rdict[key])
10108

    
10109
    if not isinstance(rdict["result"], list):
10110
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10111
                               " is not a list")
10112
    self.out_data = rdict
10113

    
10114

    
10115
class LUTestAllocator(NoHooksLU):
10116
  """Run allocator tests.
10117

10118
  This LU runs the allocator tests
10119

10120
  """
10121
  _OP_PARAMS = [
10122
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10123
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10124
    ("name", _NoDefault, _TNonEmptyString),
10125
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10126
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10127
               _TOr(_TNone, _TNonEmptyString))))),
10128
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10129
    ("hypervisor", None, _TMaybeString),
10130
    ("allocator", None, _TMaybeString),
10131
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10132
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10133
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10134
    ("os", None, _TMaybeString),
10135
    ("disk_template", None, _TMaybeString),
10136
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10137
    ]
10138

    
10139
  def CheckPrereq(self):
10140
    """Check prerequisites.
10141

10142
    This checks the opcode parameters depending on the director and mode test.
10143

10144
    """
10145
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10146
      for attr in ["mem_size", "disks", "disk_template",
10147
                   "os", "tags", "nics", "vcpus"]:
10148
        if not hasattr(self.op, attr):
10149
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10150
                                     attr, errors.ECODE_INVAL)
10151
      iname = self.cfg.ExpandInstanceName(self.op.name)
10152
      if iname is not None:
10153
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10154
                                   iname, errors.ECODE_EXISTS)
10155
      if not isinstance(self.op.nics, list):
10156
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10157
                                   errors.ECODE_INVAL)
10158
      if not isinstance(self.op.disks, list):
10159
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10160
                                   errors.ECODE_INVAL)
10161
      for row in self.op.disks:
10162
        if (not isinstance(row, dict) or
10163
            "size" not in row or
10164
            not isinstance(row["size"], int) or
10165
            "mode" not in row or
10166
            row["mode"] not in ['r', 'w']):
10167
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10168
                                     " parameter", errors.ECODE_INVAL)
10169
      if self.op.hypervisor is None:
10170
        self.op.hypervisor = self.cfg.GetHypervisorType()
10171
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10172
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10173
      self.op.name = fname
10174
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10175
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10176
      if not hasattr(self.op, "evac_nodes"):
10177
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10178
                                   " opcode input", errors.ECODE_INVAL)
10179
    else:
10180
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10181
                                 self.op.mode, errors.ECODE_INVAL)
10182

    
10183
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10184
      if self.op.allocator is None:
10185
        raise errors.OpPrereqError("Missing allocator name",
10186
                                   errors.ECODE_INVAL)
10187
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10188
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10189
                                 self.op.direction, errors.ECODE_INVAL)
10190

    
10191
  def Exec(self, feedback_fn):
10192
    """Run the allocator test.
10193

10194
    """
10195
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10196
      ial = IAllocator(self.cfg, self.rpc,
10197
                       mode=self.op.mode,
10198
                       name=self.op.name,
10199
                       mem_size=self.op.mem_size,
10200
                       disks=self.op.disks,
10201
                       disk_template=self.op.disk_template,
10202
                       os=self.op.os,
10203
                       tags=self.op.tags,
10204
                       nics=self.op.nics,
10205
                       vcpus=self.op.vcpus,
10206
                       hypervisor=self.op.hypervisor,
10207
                       )
10208
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10209
      ial = IAllocator(self.cfg, self.rpc,
10210
                       mode=self.op.mode,
10211
                       name=self.op.name,
10212
                       relocate_from=list(self.relocate_from),
10213
                       )
10214
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10215
      ial = IAllocator(self.cfg, self.rpc,
10216
                       mode=self.op.mode,
10217
                       evac_nodes=self.op.evac_nodes)
10218
    else:
10219
      raise errors.ProgrammerError("Uncatched mode %s in"
10220
                                   " LUTestAllocator.Exec", self.op.mode)
10221

    
10222
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10223
      result = ial.in_text
10224
    else:
10225
      ial.Run(self.op.allocator, validate=False)
10226
      result = ial.out_text
10227
    return result