Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ a744b676

History | View | Annotate | Download (358.8 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
from ganeti import netutils
53

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

    
56

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

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

63
  """
64
  return []
65

    
66

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

70
  """
71
  return {}
72

    
73

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

    
77

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

    
81

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

86
  """
87
  return val is not None
88

    
89

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

93
  """
94
  return val is None
95

    
96

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

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

    
103

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

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

    
110

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

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

    
117

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

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

    
124

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

128
  """
129
  return bool(val)
130

    
131

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

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

    
138

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

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

    
146

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

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

    
153

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

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

    
163

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

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

    
172

    
173
# Type aliases
174

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

    
178

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

    
182

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

    
186

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

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

    
193

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

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

    
201

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

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

    
211

    
212
# Common opcode attributes
213

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

    
217

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

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

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

    
228

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

    
232

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

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

246
  Note that all commands require root permissions.
247

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

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

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

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

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

    
291
    # Tasklets
292
    self.tasklets = None
293

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

    
321
    self.CheckArguments()
322

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

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

    
331
  ssh = property(fget=__GetSSH)
332

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

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

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

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

348
    """
349
    pass
350

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

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

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

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

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

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

376
    Examples::
377

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

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

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

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

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

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

415
    """
416

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

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

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

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

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

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

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

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

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

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

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

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

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

474
    """
475
    raise NotImplementedError
476

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
563
    del self.recalculate_locks[locking.LEVEL_NODE]
564

    
565

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

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

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

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

579
    This just raises an error.
580

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

    
584

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

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

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

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

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

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

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

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

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

617
    """
618
    pass
619

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

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

627
    """
628
    raise NotImplementedError
629

    
630

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

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

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

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

    
650

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

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

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

    
670

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

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

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

    
703

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

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

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

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

    
722

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

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

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

    
737

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

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

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

    
750

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

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

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

    
763

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

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

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

    
781

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

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

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

    
792

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

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

    
805

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

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

    
817

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

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

    
825

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

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

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

    
841

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

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

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

    
858

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

    
863

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

    
868

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

874
  This builds the hook environment from individual variables.
875

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

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

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

    
938
  env["INSTANCE_NIC_COUNT"] = nic_count
939

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

    
948
  env["INSTANCE_DISK_COUNT"] = disk_count
949

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

    
954
  return env
955

    
956

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

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

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

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

    
980

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

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

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

    
1018

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

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

    
1034

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

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

    
1045

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

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

    
1059

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

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

    
1068

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

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

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

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

    
1089

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

    
1093

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

1097
  """
1098

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

    
1101

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

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

    
1109

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

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

    
1117

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

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

    
1127
  return []
1128

    
1129

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

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

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

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

    
1144
  return faulty
1145

    
1146

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

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

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

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

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

    
1178

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

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

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

1189
    """
1190
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1191
    mn = self.cfg.GetMasterNode()
1192
    return env, [], [mn]
1193

    
1194
  def Exec(self, feedback_fn):
1195
    """Nothing to do.
1196

1197
    """
1198
    return True
1199

    
1200

    
1201
class LUDestroyCluster(LogicalUnit):
1202
  """Logical unit for destroying the cluster.
1203

1204
  """
1205
  HPATH = "cluster-destroy"
1206
  HTYPE = constants.HTYPE_CLUSTER
1207

    
1208
  def BuildHooksEnv(self):
1209
    """Build hooks env.
1210

1211
    """
1212
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1213
    return env, [], []
1214

    
1215
  def CheckPrereq(self):
1216
    """Check prerequisites.
1217

1218
    This checks whether the cluster is empty.
1219

1220
    Any errors are signaled by raising errors.OpPrereqError.
1221

1222
    """
1223
    master = self.cfg.GetMasterNode()
1224

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

    
1236
  def Exec(self, feedback_fn):
1237
    """Destroys the cluster.
1238

1239
    """
1240
    master = self.cfg.GetMasterNode()
1241
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1242

    
1243
    # Run post hooks on master node before it's removed
1244
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1245
    try:
1246
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1247
    except:
1248
      # pylint: disable-msg=W0702
1249
      self.LogWarning("Errors occurred running hooks on %s" % master)
1250

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

    
1254
    if modify_ssh_setup:
1255
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1256
      utils.CreateBackup(priv_key)
1257
      utils.CreateBackup(pub_key)
1258

    
1259
    return master
1260

    
1261

    
1262
def _VerifyCertificate(filename):
1263
  """Verifies a certificate for LUVerifyCluster.
1264

1265
  @type filename: string
1266
  @param filename: Path to PEM file
1267

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

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

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

    
1285
  if errcode is None:
1286
    return (None, fnamemsg)
1287
  elif errcode == utils.CERT_WARNING:
1288
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1289
  elif errcode == utils.CERT_ERROR:
1290
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1291

    
1292
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1293

    
1294

    
1295
class LUVerifyCluster(LogicalUnit):
1296
  """Verifies the cluster status.
1297

1298
  """
1299
  HPATH = "cluster-verify"
1300
  HTYPE = constants.HTYPE_CLUSTER
1301
  _OP_PARAMS = [
1302
    ("skip_checks", _EmptyList,
1303
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1304
    ("verbose", False, _TBool),
1305
    ("error_codes", False, _TBool),
1306
    ("debug_simulate_errors", False, _TBool),
1307
    ]
1308
  REQ_BGL = False
1309

    
1310
  TCLUSTER = "cluster"
1311
  TNODE = "node"
1312
  TINSTANCE = "instance"
1313

    
1314
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1315
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1316
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1317
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1318
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1319
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1320
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1321
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1322
  ENODEDRBD = (TNODE, "ENODEDRBD")
1323
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1324
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1325
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1326
  ENODEHV = (TNODE, "ENODEHV")
1327
  ENODELVM = (TNODE, "ENODELVM")
1328
  ENODEN1 = (TNODE, "ENODEN1")
1329
  ENODENET = (TNODE, "ENODENET")
1330
  ENODEOS = (TNODE, "ENODEOS")
1331
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1332
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1333
  ENODERPC = (TNODE, "ENODERPC")
1334
  ENODESSH = (TNODE, "ENODESSH")
1335
  ENODEVERSION = (TNODE, "ENODEVERSION")
1336
  ENODESETUP = (TNODE, "ENODESETUP")
1337
  ENODETIME = (TNODE, "ENODETIME")
1338

    
1339
  ETYPE_FIELD = "code"
1340
  ETYPE_ERROR = "ERROR"
1341
  ETYPE_WARNING = "WARNING"
1342

    
1343
  class NodeImage(object):
1344
    """A class representing the logical and physical status of a node.
1345

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

1372
    """
1373
    def __init__(self, offline=False, name=None):
1374
      self.name = name
1375
      self.volumes = {}
1376
      self.instances = []
1377
      self.pinst = []
1378
      self.sinst = []
1379
      self.sbp = {}
1380
      self.mfree = 0
1381
      self.dfree = 0
1382
      self.offline = offline
1383
      self.rpc_fail = False
1384
      self.lvm_fail = False
1385
      self.hyp_fail = False
1386
      self.ghost = False
1387
      self.os_fail = False
1388
      self.oslist = {}
1389

    
1390
  def ExpandNames(self):
1391
    self.needed_locks = {
1392
      locking.LEVEL_NODE: locking.ALL_SET,
1393
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1394
    }
1395
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1396

    
1397
  def _Error(self, ecode, item, msg, *args, **kwargs):
1398
    """Format an error message.
1399

1400
    Based on the opcode's error_codes parameter, either format a
1401
    parseable error code, or a simpler error string.
1402

1403
    This must be called only from Exec and functions called from Exec.
1404

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

    
1423
  def _ErrorIf(self, cond, *args, **kwargs):
1424
    """Log an error message if the passed condition is True.
1425

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

    
1434
  def _VerifyNode(self, ninfo, nresult):
1435
    """Run multiple tests against a node.
1436

1437
    Test list:
1438

1439
      - compares ganeti version
1440
      - checks vg existence and size > 20G
1441
      - checks config file checksum
1442
      - checks ssh to other nodes
1443

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

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

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

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

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

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

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

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

    
1496

    
1497
    test = nresult.get(constants.NV_NODESETUP,
1498
                           ["Missing NODESETUP results"])
1499
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1500
             "; ".join(test))
1501

    
1502
    return True
1503

    
1504
  def _VerifyNodeTime(self, ninfo, nresult,
1505
                      nvinfo_starttime, nvinfo_endtime):
1506
    """Check the node time.
1507

1508
    @type ninfo: L{objects.Node}
1509
    @param ninfo: the node to check
1510
    @param nresult: the remote results for the node
1511
    @param nvinfo_starttime: the start time of the RPC call
1512
    @param nvinfo_endtime: the end time of the RPC call
1513

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

    
1518
    ntime = nresult.get(constants.NV_TIME, None)
1519
    try:
1520
      ntime_merged = utils.MergeTime(ntime)
1521
    except (ValueError, TypeError):
1522
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1523
      return
1524

    
1525
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1526
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1527
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1528
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1529
    else:
1530
      ntime_diff = None
1531

    
1532
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1533
             "Node time diverges by at least %s from master node time",
1534
             ntime_diff)
1535

    
1536
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1537
    """Check the node time.
1538

1539
    @type ninfo: L{objects.Node}
1540
    @param ninfo: the node to check
1541
    @param nresult: the remote results for the node
1542
    @param vg_name: the configured VG name
1543

1544
    """
1545
    if vg_name is None:
1546
      return
1547

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

    
1551
    # checks vg existence and size > 20G
1552
    vglist = nresult.get(constants.NV_VGLIST, None)
1553
    test = not vglist
1554
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1555
    if not test:
1556
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1557
                                            constants.MIN_VG_SIZE)
1558
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1559

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

    
1573
  def _VerifyNodeNetwork(self, ninfo, nresult):
1574
    """Check the node time.
1575

1576
    @type ninfo: L{objects.Node}
1577
    @param ninfo: the node to check
1578
    @param nresult: the remote results for the node
1579

1580
    """
1581
    node = ninfo.name
1582
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1583

    
1584
    test = constants.NV_NODELIST not in nresult
1585
    _ErrorIf(test, self.ENODESSH, node,
1586
             "node hasn't returned node ssh connectivity data")
1587
    if not test:
1588
      if nresult[constants.NV_NODELIST]:
1589
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1590
          _ErrorIf(True, self.ENODESSH, node,
1591
                   "ssh communication with node '%s': %s", a_node, a_msg)
1592

    
1593
    test = constants.NV_NODENETTEST not in nresult
1594
    _ErrorIf(test, self.ENODENET, node,
1595
             "node hasn't returned node tcp connectivity data")
1596
    if not test:
1597
      if nresult[constants.NV_NODENETTEST]:
1598
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1599
        for anode in nlist:
1600
          _ErrorIf(True, self.ENODENET, node,
1601
                   "tcp communication with node '%s': %s",
1602
                   anode, nresult[constants.NV_NODENETTEST][anode])
1603

    
1604
    test = constants.NV_MASTERIP not in nresult
1605
    _ErrorIf(test, self.ENODENET, node,
1606
             "node hasn't returned node master IP reachability data")
1607
    if not test:
1608
      if not nresult[constants.NV_MASTERIP]:
1609
        if node == self.master_node:
1610
          msg = "the master node cannot reach the master IP (not configured?)"
1611
        else:
1612
          msg = "cannot reach the master IP"
1613
        _ErrorIf(True, self.ENODENET, node, msg)
1614

    
1615

    
1616
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1617
    """Verify an instance.
1618

1619
    This function checks to see if the required block devices are
1620
    available on the instance's node.
1621

1622
    """
1623
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1624
    node_current = instanceconfig.primary_node
1625

    
1626
    node_vol_should = {}
1627
    instanceconfig.MapLVsByNode(node_vol_should)
1628

    
1629
    for node in node_vol_should:
1630
      n_img = node_image[node]
1631
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1632
        # ignore missing volumes on offline or broken nodes
1633
        continue
1634
      for volume in node_vol_should[node]:
1635
        test = volume not in n_img.volumes
1636
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1637
                 "volume %s missing on node %s", volume, node)
1638

    
1639
    if instanceconfig.admin_up:
1640
      pri_img = node_image[node_current]
1641
      test = instance not in pri_img.instances and not pri_img.offline
1642
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1643
               "instance not running on its primary node %s",
1644
               node_current)
1645

    
1646
    for node, n_img in node_image.items():
1647
      if (not node == node_current):
1648
        test = instance in n_img.instances
1649
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1650
                 "instance should not run on node %s", node)
1651

    
1652
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1653
    """Verify if there are any unknown volumes in the cluster.
1654

1655
    The .os, .swap and backup volumes are ignored. All other volumes are
1656
    reported as unknown.
1657

1658
    """
1659
    for node, n_img in node_image.items():
1660
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1661
        # skip non-healthy nodes
1662
        continue
1663
      for volume in n_img.volumes:
1664
        test = (node not in node_vol_should or
1665
                volume not in node_vol_should[node])
1666
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1667
                      "volume %s is unknown", volume)
1668

    
1669
  def _VerifyOrphanInstances(self, instancelist, node_image):
1670
    """Verify the list of running instances.
1671

1672
    This checks what instances are running but unknown to the cluster.
1673

1674
    """
1675
    for node, n_img in node_image.items():
1676
      for o_inst in n_img.instances:
1677
        test = o_inst not in instancelist
1678
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1679
                      "instance %s on node %s should not exist", o_inst, node)
1680

    
1681
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1682
    """Verify N+1 Memory Resilience.
1683

1684
    Check that if one single node dies we can still start all the
1685
    instances it was primary for.
1686

1687
    """
1688
    for node, n_img in node_image.items():
1689
      # This code checks that every node which is now listed as
1690
      # secondary has enough memory to host all instances it is
1691
      # supposed to should a single other node in the cluster fail.
1692
      # FIXME: not ready for failover to an arbitrary node
1693
      # FIXME: does not support file-backed instances
1694
      # WARNING: we currently take into account down instances as well
1695
      # as up ones, considering that even if they're down someone
1696
      # might want to start them even in the event of a node failure.
1697
      for prinode, instances in n_img.sbp.items():
1698
        needed_mem = 0
1699
        for instance in instances:
1700
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1701
          if bep[constants.BE_AUTO_BALANCE]:
1702
            needed_mem += bep[constants.BE_MEMORY]
1703
        test = n_img.mfree < needed_mem
1704
        self._ErrorIf(test, self.ENODEN1, node,
1705
                      "not enough memory on to accommodate"
1706
                      " failovers should peer node %s fail", prinode)
1707

    
1708
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1709
                       master_files):
1710
    """Verifies and computes the node required file checksums.
1711

1712
    @type ninfo: L{objects.Node}
1713
    @param ninfo: the node to check
1714
    @param nresult: the remote results for the node
1715
    @param file_list: required list of files
1716
    @param local_cksum: dictionary of local files and their checksums
1717
    @param master_files: list of files that only masters should have
1718

1719
    """
1720
    node = ninfo.name
1721
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1722

    
1723
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1724
    test = not isinstance(remote_cksum, dict)
1725
    _ErrorIf(test, self.ENODEFILECHECK, node,
1726
             "node hasn't returned file checksum data")
1727
    if test:
1728
      return
1729

    
1730
    for file_name in file_list:
1731
      node_is_mc = ninfo.master_candidate
1732
      must_have = (file_name not in master_files) or node_is_mc
1733
      # missing
1734
      test1 = file_name not in remote_cksum
1735
      # invalid checksum
1736
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1737
      # existing and good
1738
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1739
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1740
               "file '%s' missing", file_name)
1741
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1742
               "file '%s' has wrong checksum", file_name)
1743
      # not candidate and this is not a must-have file
1744
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1745
               "file '%s' should not exist on non master"
1746
               " candidates (and the file is outdated)", file_name)
1747
      # all good, except non-master/non-must have combination
1748
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1749
               "file '%s' should not exist"
1750
               " on non master candidates", file_name)
1751

    
1752
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1753
                      drbd_map):
1754
    """Verifies and the node DRBD status.
1755

1756
    @type ninfo: L{objects.Node}
1757
    @param ninfo: the node to check
1758
    @param nresult: the remote results for the node
1759
    @param instanceinfo: the dict of instances
1760
    @param drbd_helper: the configured DRBD usermode helper
1761
    @param drbd_map: the DRBD map as returned by
1762
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1763

1764
    """
1765
    node = ninfo.name
1766
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1767

    
1768
    if drbd_helper:
1769
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1770
      test = (helper_result == None)
1771
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1772
               "no drbd usermode helper returned")
1773
      if helper_result:
1774
        status, payload = helper_result
1775
        test = not status
1776
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1777
                 "drbd usermode helper check unsuccessful: %s", payload)
1778
        test = status and (payload != drbd_helper)
1779
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1780
                 "wrong drbd usermode helper: %s", payload)
1781

    
1782
    # compute the DRBD minors
1783
    node_drbd = {}
1784
    for minor, instance in drbd_map[node].items():
1785
      test = instance not in instanceinfo
1786
      _ErrorIf(test, self.ECLUSTERCFG, None,
1787
               "ghost instance '%s' in temporary DRBD map", instance)
1788
        # ghost instance should not be running, but otherwise we
1789
        # don't give double warnings (both ghost instance and
1790
        # unallocated minor in use)
1791
      if test:
1792
        node_drbd[minor] = (instance, False)
1793
      else:
1794
        instance = instanceinfo[instance]
1795
        node_drbd[minor] = (instance.name, instance.admin_up)
1796

    
1797
    # and now check them
1798
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1799
    test = not isinstance(used_minors, (tuple, list))
1800
    _ErrorIf(test, self.ENODEDRBD, node,
1801
             "cannot parse drbd status file: %s", str(used_minors))
1802
    if test:
1803
      # we cannot check drbd status
1804
      return
1805

    
1806
    for minor, (iname, must_exist) in node_drbd.items():
1807
      test = minor not in used_minors and must_exist
1808
      _ErrorIf(test, self.ENODEDRBD, node,
1809
               "drbd minor %d of instance %s is not active", minor, iname)
1810
    for minor in used_minors:
1811
      test = minor not in node_drbd
1812
      _ErrorIf(test, self.ENODEDRBD, node,
1813
               "unallocated drbd minor %d is in use", minor)
1814

    
1815
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1816
    """Builds the node OS structures.
1817

1818
    @type ninfo: L{objects.Node}
1819
    @param ninfo: the node to check
1820
    @param nresult: the remote results for the node
1821
    @param nimg: the node image object
1822

1823
    """
1824
    node = ninfo.name
1825
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1826

    
1827
    remote_os = nresult.get(constants.NV_OSLIST, None)
1828
    test = (not isinstance(remote_os, list) or
1829
            not compat.all(isinstance(v, list) and len(v) == 7
1830
                           for v in remote_os))
1831

    
1832
    _ErrorIf(test, self.ENODEOS, node,
1833
             "node hasn't returned valid OS data")
1834

    
1835
    nimg.os_fail = test
1836

    
1837
    if test:
1838
      return
1839

    
1840
    os_dict = {}
1841

    
1842
    for (name, os_path, status, diagnose,
1843
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1844

    
1845
      if name not in os_dict:
1846
        os_dict[name] = []
1847

    
1848
      # parameters is a list of lists instead of list of tuples due to
1849
      # JSON lacking a real tuple type, fix it:
1850
      parameters = [tuple(v) for v in parameters]
1851
      os_dict[name].append((os_path, status, diagnose,
1852
                            set(variants), set(parameters), set(api_ver)))
1853

    
1854
    nimg.oslist = os_dict
1855

    
1856
  def _VerifyNodeOS(self, ninfo, nimg, base):
1857
    """Verifies the node OS list.
1858

1859
    @type ninfo: L{objects.Node}
1860
    @param ninfo: the node to check
1861
    @param nimg: the node image object
1862
    @param base: the 'template' node we match against (e.g. from the master)
1863

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

    
1868
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1869

    
1870
    for os_name, os_data in nimg.oslist.items():
1871
      assert os_data, "Empty OS status for OS %s?!" % os_name
1872
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1873
      _ErrorIf(not f_status, self.ENODEOS, node,
1874
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1875
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1876
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1877
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1878
      # this will catched in backend too
1879
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1880
               and not f_var, self.ENODEOS, node,
1881
               "OS %s with API at least %d does not declare any variant",
1882
               os_name, constants.OS_API_V15)
1883
      # comparisons with the 'base' image
1884
      test = os_name not in base.oslist
1885
      _ErrorIf(test, self.ENODEOS, node,
1886
               "Extra OS %s not present on reference node (%s)",
1887
               os_name, base.name)
1888
      if test:
1889
        continue
1890
      assert base.oslist[os_name], "Base node has empty OS status?"
1891
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1892
      if not b_status:
1893
        # base OS is invalid, skipping
1894
        continue
1895
      for kind, a, b in [("API version", f_api, b_api),
1896
                         ("variants list", f_var, b_var),
1897
                         ("parameters", f_param, b_param)]:
1898
        _ErrorIf(a != b, self.ENODEOS, node,
1899
                 "OS %s %s differs from reference node %s: %s vs. %s",
1900
                 kind, os_name, base.name,
1901
                 utils.CommaJoin(a), utils.CommaJoin(b))
1902

    
1903
    # check any missing OSes
1904
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1905
    _ErrorIf(missing, self.ENODEOS, node,
1906
             "OSes present on reference node %s but missing on this node: %s",
1907
             base.name, utils.CommaJoin(missing))
1908

    
1909
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1910
    """Verifies and updates the node volume data.
1911

1912
    This function will update a L{NodeImage}'s internal structures
1913
    with data from the remote call.
1914

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

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

    
1925
    nimg.lvm_fail = True
1926
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1927
    if vg_name is None:
1928
      pass
1929
    elif isinstance(lvdata, basestring):
1930
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1931
               utils.SafeEncode(lvdata))
1932
    elif not isinstance(lvdata, dict):
1933
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1934
    else:
1935
      nimg.volumes = lvdata
1936
      nimg.lvm_fail = False
1937

    
1938
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1939
    """Verifies and updates the node instance list.
1940

1941
    If the listing was successful, then updates this node's instance
1942
    list. Otherwise, it marks the RPC call as failed for the instance
1943
    list key.
1944

1945
    @type ninfo: L{objects.Node}
1946
    @param ninfo: the node to check
1947
    @param nresult: the remote results for the node
1948
    @param nimg: the node image object
1949

1950
    """
1951
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1952
    test = not isinstance(idata, list)
1953
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1954
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1955
    if test:
1956
      nimg.hyp_fail = True
1957
    else:
1958
      nimg.instances = idata
1959

    
1960
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1961
    """Verifies and computes a node information map
1962

1963
    @type ninfo: L{objects.Node}
1964
    @param ninfo: the node to check
1965
    @param nresult: the remote results for the node
1966
    @param nimg: the node image object
1967
    @param vg_name: the configured VG name
1968

1969
    """
1970
    node = ninfo.name
1971
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1972

    
1973
    # try to read free memory (from the hypervisor)
1974
    hv_info = nresult.get(constants.NV_HVINFO, None)
1975
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
1976
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
1977
    if not test:
1978
      try:
1979
        nimg.mfree = int(hv_info["memory_free"])
1980
      except (ValueError, TypeError):
1981
        _ErrorIf(True, self.ENODERPC, node,
1982
                 "node returned invalid nodeinfo, check hypervisor")
1983

    
1984
    # FIXME: devise a free space model for file based instances as well
1985
    if vg_name is not None:
1986
      test = (constants.NV_VGLIST not in nresult or
1987
              vg_name not in nresult[constants.NV_VGLIST])
1988
      _ErrorIf(test, self.ENODELVM, node,
1989
               "node didn't return data for the volume group '%s'"
1990
               " - it is either missing or broken", vg_name)
1991
      if not test:
1992
        try:
1993
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
1994
        except (ValueError, TypeError):
1995
          _ErrorIf(True, self.ENODERPC, node,
1996
                   "node returned invalid LVM info, check LVM status")
1997

    
1998
  def BuildHooksEnv(self):
1999
    """Build hooks env.
2000

2001
    Cluster-Verify hooks just ran in the post phase and their failure makes
2002
    the output be logged in the verify output and the verification to fail.
2003

2004
    """
2005
    all_nodes = self.cfg.GetNodeList()
2006
    env = {
2007
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2008
      }
2009
    for node in self.cfg.GetAllNodesInfo().values():
2010
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2011

    
2012
    return env, [], all_nodes
2013

    
2014
  def Exec(self, feedback_fn):
2015
    """Verify integrity of cluster, performing various test on nodes.
2016

2017
    """
2018
    self.bad = False
2019
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2020
    verbose = self.op.verbose
2021
    self._feedback_fn = feedback_fn
2022
    feedback_fn("* Verifying global settings")
2023
    for msg in self.cfg.VerifyConfig():
2024
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2025

    
2026
    # Check the cluster certificates
2027
    for cert_filename in constants.ALL_CERT_FILES:
2028
      (errcode, msg) = _VerifyCertificate(cert_filename)
2029
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2030

    
2031
    vg_name = self.cfg.GetVGName()
2032
    drbd_helper = self.cfg.GetDRBDHelper()
2033
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2034
    cluster = self.cfg.GetClusterInfo()
2035
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2036
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2037
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2038
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2039
                        for iname in instancelist)
2040
    i_non_redundant = [] # Non redundant instances
2041
    i_non_a_balanced = [] # Non auto-balanced instances
2042
    n_offline = 0 # Count of offline nodes
2043
    n_drained = 0 # Count of nodes being drained
2044
    node_vol_should = {}
2045

    
2046
    # FIXME: verify OS list
2047
    # do local checksums
2048
    master_files = [constants.CLUSTER_CONF_FILE]
2049
    master_node = self.master_node = self.cfg.GetMasterNode()
2050
    master_ip = self.cfg.GetMasterIP()
2051

    
2052
    file_names = ssconf.SimpleStore().GetFileList()
2053
    file_names.extend(constants.ALL_CERT_FILES)
2054
    file_names.extend(master_files)
2055
    if cluster.modify_etc_hosts:
2056
      file_names.append(constants.ETC_HOSTS)
2057

    
2058
    local_checksums = utils.FingerprintFiles(file_names)
2059

    
2060
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2061
    node_verify_param = {
2062
      constants.NV_FILELIST: file_names,
2063
      constants.NV_NODELIST: [node.name for node in nodeinfo
2064
                              if not node.offline],
2065
      constants.NV_HYPERVISOR: hypervisors,
2066
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2067
                                  node.secondary_ip) for node in nodeinfo
2068
                                 if not node.offline],
2069
      constants.NV_INSTANCELIST: hypervisors,
2070
      constants.NV_VERSION: None,
2071
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2072
      constants.NV_NODESETUP: None,
2073
      constants.NV_TIME: None,
2074
      constants.NV_MASTERIP: (master_node, master_ip),
2075
      constants.NV_OSLIST: None,
2076
      }
2077

    
2078
    if vg_name is not None:
2079
      node_verify_param[constants.NV_VGLIST] = None
2080
      node_verify_param[constants.NV_LVLIST] = vg_name
2081
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2082
      node_verify_param[constants.NV_DRBDLIST] = None
2083

    
2084
    if drbd_helper:
2085
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2086

    
2087
    # Build our expected cluster state
2088
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2089
                                                 name=node.name))
2090
                      for node in nodeinfo)
2091

    
2092
    for instance in instancelist:
2093
      inst_config = instanceinfo[instance]
2094

    
2095
      for nname in inst_config.all_nodes:
2096
        if nname not in node_image:
2097
          # ghost node
2098
          gnode = self.NodeImage(name=nname)
2099
          gnode.ghost = True
2100
          node_image[nname] = gnode
2101

    
2102
      inst_config.MapLVsByNode(node_vol_should)
2103

    
2104
      pnode = inst_config.primary_node
2105
      node_image[pnode].pinst.append(instance)
2106

    
2107
      for snode in inst_config.secondary_nodes:
2108
        nimg = node_image[snode]
2109
        nimg.sinst.append(instance)
2110
        if pnode not in nimg.sbp:
2111
          nimg.sbp[pnode] = []
2112
        nimg.sbp[pnode].append(instance)
2113

    
2114
    # At this point, we have the in-memory data structures complete,
2115
    # except for the runtime information, which we'll gather next
2116

    
2117
    # Due to the way our RPC system works, exact response times cannot be
2118
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2119
    # time before and after executing the request, we can at least have a time
2120
    # window.
2121
    nvinfo_starttime = time.time()
2122
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2123
                                           self.cfg.GetClusterName())
2124
    nvinfo_endtime = time.time()
2125

    
2126
    all_drbd_map = self.cfg.ComputeDRBDMap()
2127

    
2128
    feedback_fn("* Verifying node status")
2129

    
2130
    refos_img = None
2131

    
2132
    for node_i in nodeinfo:
2133
      node = node_i.name
2134
      nimg = node_image[node]
2135

    
2136
      if node_i.offline:
2137
        if verbose:
2138
          feedback_fn("* Skipping offline node %s" % (node,))
2139
        n_offline += 1
2140
        continue
2141

    
2142
      if node == master_node:
2143
        ntype = "master"
2144
      elif node_i.master_candidate:
2145
        ntype = "master candidate"
2146
      elif node_i.drained:
2147
        ntype = "drained"
2148
        n_drained += 1
2149
      else:
2150
        ntype = "regular"
2151
      if verbose:
2152
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2153

    
2154
      msg = all_nvinfo[node].fail_msg
2155
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2156
      if msg:
2157
        nimg.rpc_fail = True
2158
        continue
2159

    
2160
      nresult = all_nvinfo[node].payload
2161

    
2162
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2163
      self._VerifyNodeNetwork(node_i, nresult)
2164
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2165
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2166
                            master_files)
2167
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2168
                           all_drbd_map)
2169
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2170

    
2171
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2172
      self._UpdateNodeInstances(node_i, nresult, nimg)
2173
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2174
      self._UpdateNodeOS(node_i, nresult, nimg)
2175
      if not nimg.os_fail:
2176
        if refos_img is None:
2177
          refos_img = nimg
2178
        self._VerifyNodeOS(node_i, nimg, refos_img)
2179

    
2180
    feedback_fn("* Verifying instance status")
2181
    for instance in instancelist:
2182
      if verbose:
2183
        feedback_fn("* Verifying instance %s" % instance)
2184
      inst_config = instanceinfo[instance]
2185
      self._VerifyInstance(instance, inst_config, node_image)
2186
      inst_nodes_offline = []
2187

    
2188
      pnode = inst_config.primary_node
2189
      pnode_img = node_image[pnode]
2190
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2191
               self.ENODERPC, pnode, "instance %s, connection to"
2192
               " primary node failed", instance)
2193

    
2194
      if pnode_img.offline:
2195
        inst_nodes_offline.append(pnode)
2196

    
2197
      # If the instance is non-redundant we cannot survive losing its primary
2198
      # node, so we are not N+1 compliant. On the other hand we have no disk
2199
      # templates with more than one secondary so that situation is not well
2200
      # supported either.
2201
      # FIXME: does not support file-backed instances
2202
      if not inst_config.secondary_nodes:
2203
        i_non_redundant.append(instance)
2204
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2205
               instance, "instance has multiple secondary nodes: %s",
2206
               utils.CommaJoin(inst_config.secondary_nodes),
2207
               code=self.ETYPE_WARNING)
2208

    
2209
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2210
        i_non_a_balanced.append(instance)
2211

    
2212
      for snode in inst_config.secondary_nodes:
2213
        s_img = node_image[snode]
2214
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2215
                 "instance %s, connection to secondary node failed", instance)
2216

    
2217
        if s_img.offline:
2218
          inst_nodes_offline.append(snode)
2219

    
2220
      # warn that the instance lives on offline nodes
2221
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2222
               "instance lives on offline node(s) %s",
2223
               utils.CommaJoin(inst_nodes_offline))
2224
      # ... or ghost nodes
2225
      for node in inst_config.all_nodes:
2226
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2227
                 "instance lives on ghost node %s", node)
2228

    
2229
    feedback_fn("* Verifying orphan volumes")
2230
    self._VerifyOrphanVolumes(node_vol_should, node_image)
2231

    
2232
    feedback_fn("* Verifying orphan instances")
2233
    self._VerifyOrphanInstances(instancelist, node_image)
2234

    
2235
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2236
      feedback_fn("* Verifying N+1 Memory redundancy")
2237
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2238

    
2239
    feedback_fn("* Other Notes")
2240
    if i_non_redundant:
2241
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2242
                  % len(i_non_redundant))
2243

    
2244
    if i_non_a_balanced:
2245
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2246
                  % len(i_non_a_balanced))
2247

    
2248
    if n_offline:
2249
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2250

    
2251
    if n_drained:
2252
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2253

    
2254
    return not self.bad
2255

    
2256
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2257
    """Analyze the post-hooks' result
2258

2259
    This method analyses the hook result, handles it, and sends some
2260
    nicely-formatted feedback back to the user.
2261

2262
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2263
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2264
    @param hooks_results: the results of the multi-node hooks rpc call
2265
    @param feedback_fn: function used send feedback back to the caller
2266
    @param lu_result: previous Exec result
2267
    @return: the new Exec result, based on the previous result
2268
        and hook results
2269

2270
    """
2271
    # We only really run POST phase hooks, and are only interested in
2272
    # their results
2273
    if phase == constants.HOOKS_PHASE_POST:
2274
      # Used to change hooks' output to proper indentation
2275
      indent_re = re.compile('^', re.M)
2276
      feedback_fn("* Hooks Results")
2277
      assert hooks_results, "invalid result from hooks"
2278

    
2279
      for node_name in hooks_results:
2280
        res = hooks_results[node_name]
2281
        msg = res.fail_msg
2282
        test = msg and not res.offline
2283
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2284
                      "Communication failure in hooks execution: %s", msg)
2285
        if res.offline or msg:
2286
          # No need to investigate payload if node is offline or gave an error.
2287
          # override manually lu_result here as _ErrorIf only
2288
          # overrides self.bad
2289
          lu_result = 1
2290
          continue
2291
        for script, hkr, output in res.payload:
2292
          test = hkr == constants.HKR_FAIL
2293
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2294
                        "Script %s failed, output:", script)
2295
          if test:
2296
            output = indent_re.sub('      ', output)
2297
            feedback_fn("%s" % output)
2298
            lu_result = 0
2299

    
2300
      return lu_result
2301

    
2302

    
2303
class LUVerifyDisks(NoHooksLU):
2304
  """Verifies the cluster disks status.
2305

2306
  """
2307
  REQ_BGL = False
2308

    
2309
  def ExpandNames(self):
2310
    self.needed_locks = {
2311
      locking.LEVEL_NODE: locking.ALL_SET,
2312
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2313
    }
2314
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2315

    
2316
  def Exec(self, feedback_fn):
2317
    """Verify integrity of cluster disks.
2318

2319
    @rtype: tuple of three items
2320
    @return: a tuple of (dict of node-to-node_error, list of instances
2321
        which need activate-disks, dict of instance: (node, volume) for
2322
        missing volumes
2323

2324
    """
2325
    result = res_nodes, res_instances, res_missing = {}, [], {}
2326

    
2327
    vg_name = self.cfg.GetVGName()
2328
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2329
    instances = [self.cfg.GetInstanceInfo(name)
2330
                 for name in self.cfg.GetInstanceList()]
2331

    
2332
    nv_dict = {}
2333
    for inst in instances:
2334
      inst_lvs = {}
2335
      if (not inst.admin_up or
2336
          inst.disk_template not in constants.DTS_NET_MIRROR):
2337
        continue
2338
      inst.MapLVsByNode(inst_lvs)
2339
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2340
      for node, vol_list in inst_lvs.iteritems():
2341
        for vol in vol_list:
2342
          nv_dict[(node, vol)] = inst
2343

    
2344
    if not nv_dict:
2345
      return result
2346

    
2347
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2348

    
2349
    for node in nodes:
2350
      # node_volume
2351
      node_res = node_lvs[node]
2352
      if node_res.offline:
2353
        continue
2354
      msg = node_res.fail_msg
2355
      if msg:
2356
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2357
        res_nodes[node] = msg
2358
        continue
2359

    
2360
      lvs = node_res.payload
2361
      for lv_name, (_, _, lv_online) in lvs.items():
2362
        inst = nv_dict.pop((node, lv_name), None)
2363
        if (not lv_online and inst is not None
2364
            and inst.name not in res_instances):
2365
          res_instances.append(inst.name)
2366

    
2367
    # any leftover items in nv_dict are missing LVs, let's arrange the
2368
    # data better
2369
    for key, inst in nv_dict.iteritems():
2370
      if inst.name not in res_missing:
2371
        res_missing[inst.name] = []
2372
      res_missing[inst.name].append(key)
2373

    
2374
    return result
2375

    
2376

    
2377
class LURepairDiskSizes(NoHooksLU):
2378
  """Verifies the cluster disks sizes.
2379

2380
  """
2381
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2382
  REQ_BGL = False
2383

    
2384
  def ExpandNames(self):
2385
    if self.op.instances:
2386
      self.wanted_names = []
2387
      for name in self.op.instances:
2388
        full_name = _ExpandInstanceName(self.cfg, name)
2389
        self.wanted_names.append(full_name)
2390
      self.needed_locks = {
2391
        locking.LEVEL_NODE: [],
2392
        locking.LEVEL_INSTANCE: self.wanted_names,
2393
        }
2394
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2395
    else:
2396
      self.wanted_names = None
2397
      self.needed_locks = {
2398
        locking.LEVEL_NODE: locking.ALL_SET,
2399
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2400
        }
2401
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2402

    
2403
  def DeclareLocks(self, level):
2404
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2405
      self._LockInstancesNodes(primary_only=True)
2406

    
2407
  def CheckPrereq(self):
2408
    """Check prerequisites.
2409

2410
    This only checks the optional instance list against the existing names.
2411

2412
    """
2413
    if self.wanted_names is None:
2414
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2415

    
2416
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2417
                             in self.wanted_names]
2418

    
2419
  def _EnsureChildSizes(self, disk):
2420
    """Ensure children of the disk have the needed disk size.
2421

2422
    This is valid mainly for DRBD8 and fixes an issue where the
2423
    children have smaller disk size.
2424

2425
    @param disk: an L{ganeti.objects.Disk} object
2426

2427
    """
2428
    if disk.dev_type == constants.LD_DRBD8:
2429
      assert disk.children, "Empty children for DRBD8?"
2430
      fchild = disk.children[0]
2431
      mismatch = fchild.size < disk.size
2432
      if mismatch:
2433
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2434
                     fchild.size, disk.size)
2435
        fchild.size = disk.size
2436

    
2437
      # and we recurse on this child only, not on the metadev
2438
      return self._EnsureChildSizes(fchild) or mismatch
2439
    else:
2440
      return False
2441

    
2442
  def Exec(self, feedback_fn):
2443
    """Verify the size of cluster disks.
2444

2445
    """
2446
    # TODO: check child disks too
2447
    # TODO: check differences in size between primary/secondary nodes
2448
    per_node_disks = {}
2449
    for instance in self.wanted_instances:
2450
      pnode = instance.primary_node
2451
      if pnode not in per_node_disks:
2452
        per_node_disks[pnode] = []
2453
      for idx, disk in enumerate(instance.disks):
2454
        per_node_disks[pnode].append((instance, idx, disk))
2455

    
2456
    changed = []
2457
    for node, dskl in per_node_disks.items():
2458
      newl = [v[2].Copy() for v in dskl]
2459
      for dsk in newl:
2460
        self.cfg.SetDiskID(dsk, node)
2461
      result = self.rpc.call_blockdev_getsizes(node, newl)
2462
      if result.fail_msg:
2463
        self.LogWarning("Failure in blockdev_getsizes call to node"
2464
                        " %s, ignoring", node)
2465
        continue
2466
      if len(result.data) != len(dskl):
2467
        self.LogWarning("Invalid result from node %s, ignoring node results",
2468
                        node)
2469
        continue
2470
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2471
        if size is None:
2472
          self.LogWarning("Disk %d of instance %s did not return size"
2473
                          " information, ignoring", idx, instance.name)
2474
          continue
2475
        if not isinstance(size, (int, long)):
2476
          self.LogWarning("Disk %d of instance %s did not return valid"
2477
                          " size information, ignoring", idx, instance.name)
2478
          continue
2479
        size = size >> 20
2480
        if size != disk.size:
2481
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2482
                       " correcting: recorded %d, actual %d", idx,
2483
                       instance.name, disk.size, size)
2484
          disk.size = size
2485
          self.cfg.Update(instance, feedback_fn)
2486
          changed.append((instance.name, idx, size))
2487
        if self._EnsureChildSizes(disk):
2488
          self.cfg.Update(instance, feedback_fn)
2489
          changed.append((instance.name, idx, disk.size))
2490
    return changed
2491

    
2492

    
2493
class LURenameCluster(LogicalUnit):
2494
  """Rename the cluster.
2495

2496
  """
2497
  HPATH = "cluster-rename"
2498
  HTYPE = constants.HTYPE_CLUSTER
2499
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2500

    
2501
  def BuildHooksEnv(self):
2502
    """Build hooks env.
2503

2504
    """
2505
    env = {
2506
      "OP_TARGET": self.cfg.GetClusterName(),
2507
      "NEW_NAME": self.op.name,
2508
      }
2509
    mn = self.cfg.GetMasterNode()
2510
    all_nodes = self.cfg.GetNodeList()
2511
    return env, [mn], all_nodes
2512

    
2513
  def CheckPrereq(self):
2514
    """Verify that the passed name is a valid one.
2515

2516
    """
2517
    hostname = netutils.GetHostInfo(self.op.name)
2518

    
2519
    new_name = hostname.name
2520
    self.ip = new_ip = hostname.ip
2521
    old_name = self.cfg.GetClusterName()
2522
    old_ip = self.cfg.GetMasterIP()
2523
    if new_name == old_name and new_ip == old_ip:
2524
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2525
                                 " cluster has changed",
2526
                                 errors.ECODE_INVAL)
2527
    if new_ip != old_ip:
2528
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2529
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2530
                                   " reachable on the network. Aborting." %
2531
                                   new_ip, errors.ECODE_NOTUNIQUE)
2532

    
2533
    self.op.name = new_name
2534

    
2535
  def Exec(self, feedback_fn):
2536
    """Rename the cluster.
2537

2538
    """
2539
    clustername = self.op.name
2540
    ip = self.ip
2541

    
2542
    # shutdown the master IP
2543
    master = self.cfg.GetMasterNode()
2544
    result = self.rpc.call_node_stop_master(master, False)
2545
    result.Raise("Could not disable the master role")
2546

    
2547
    try:
2548
      cluster = self.cfg.GetClusterInfo()
2549
      cluster.cluster_name = clustername
2550
      cluster.master_ip = ip
2551
      self.cfg.Update(cluster, feedback_fn)
2552

    
2553
      # update the known hosts file
2554
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2555
      node_list = self.cfg.GetNodeList()
2556
      try:
2557
        node_list.remove(master)
2558
      except ValueError:
2559
        pass
2560
      result = self.rpc.call_upload_file(node_list,
2561
                                         constants.SSH_KNOWN_HOSTS_FILE)
2562
      for to_node, to_result in result.iteritems():
2563
        msg = to_result.fail_msg
2564
        if msg:
2565
          msg = ("Copy of file %s to node %s failed: %s" %
2566
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2567
          self.proc.LogWarning(msg)
2568

    
2569
    finally:
2570
      result = self.rpc.call_node_start_master(master, False, False)
2571
      msg = result.fail_msg
2572
      if msg:
2573
        self.LogWarning("Could not re-enable the master role on"
2574
                        " the master, please restart manually: %s", msg)
2575

    
2576

    
2577
class LUSetClusterParams(LogicalUnit):
2578
  """Change the parameters of the cluster.
2579

2580
  """
2581
  HPATH = "cluster-modify"
2582
  HTYPE = constants.HTYPE_CLUSTER
2583
  _OP_PARAMS = [
2584
    ("vg_name", None, _TMaybeString),
2585
    ("enabled_hypervisors", None,
2586
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2587
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2588
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2589
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2590
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2591
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2592
    ("uid_pool", None, _NoType),
2593
    ("add_uids", None, _NoType),
2594
    ("remove_uids", None, _NoType),
2595
    ("maintain_node_health", None, _TMaybeBool),
2596
    ("nicparams", None, _TOr(_TDict, _TNone)),
2597
    ("drbd_helper", None, _TOr(_TString, _TNone)),
2598
    ("default_iallocator", None, _TMaybeString),
2599
    ]
2600
  REQ_BGL = False
2601

    
2602
  def CheckArguments(self):
2603
    """Check parameters
2604

2605
    """
2606
    if self.op.uid_pool:
2607
      uidpool.CheckUidPool(self.op.uid_pool)
2608

    
2609
    if self.op.add_uids:
2610
      uidpool.CheckUidPool(self.op.add_uids)
2611

    
2612
    if self.op.remove_uids:
2613
      uidpool.CheckUidPool(self.op.remove_uids)
2614

    
2615
  def ExpandNames(self):
2616
    # FIXME: in the future maybe other cluster params won't require checking on
2617
    # all nodes to be modified.
2618
    self.needed_locks = {
2619
      locking.LEVEL_NODE: locking.ALL_SET,
2620
    }
2621
    self.share_locks[locking.LEVEL_NODE] = 1
2622

    
2623
  def BuildHooksEnv(self):
2624
    """Build hooks env.
2625

2626
    """
2627
    env = {
2628
      "OP_TARGET": self.cfg.GetClusterName(),
2629
      "NEW_VG_NAME": self.op.vg_name,
2630
      }
2631
    mn = self.cfg.GetMasterNode()
2632
    return env, [mn], [mn]
2633

    
2634
  def CheckPrereq(self):
2635
    """Check prerequisites.
2636

2637
    This checks whether the given params don't conflict and
2638
    if the given volume group is valid.
2639

2640
    """
2641
    if self.op.vg_name is not None and not self.op.vg_name:
2642
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2643
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2644
                                   " instances exist", errors.ECODE_INVAL)
2645

    
2646
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2647
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2648
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2649
                                   " drbd-based instances exist",
2650
                                   errors.ECODE_INVAL)
2651

    
2652
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2653

    
2654
    # if vg_name not None, checks given volume group on all nodes
2655
    if self.op.vg_name:
2656
      vglist = self.rpc.call_vg_list(node_list)
2657
      for node in node_list:
2658
        msg = vglist[node].fail_msg
2659
        if msg:
2660
          # ignoring down node
2661
          self.LogWarning("Error while gathering data on node %s"
2662
                          " (ignoring node): %s", node, msg)
2663
          continue
2664
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2665
                                              self.op.vg_name,
2666
                                              constants.MIN_VG_SIZE)
2667
        if vgstatus:
2668
          raise errors.OpPrereqError("Error on node '%s': %s" %
2669
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2670

    
2671
    if self.op.drbd_helper:
2672
      # checks given drbd helper on all nodes
2673
      helpers = self.rpc.call_drbd_helper(node_list)
2674
      for node in node_list:
2675
        ninfo = self.cfg.GetNodeInfo(node)
2676
        if ninfo.offline:
2677
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2678
          continue
2679
        msg = helpers[node].fail_msg
2680
        if msg:
2681
          raise errors.OpPrereqError("Error checking drbd helper on node"
2682
                                     " '%s': %s" % (node, msg),
2683
                                     errors.ECODE_ENVIRON)
2684
        node_helper = helpers[node].payload
2685
        if node_helper != self.op.drbd_helper:
2686
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2687
                                     (node, node_helper), errors.ECODE_ENVIRON)
2688

    
2689
    self.cluster = cluster = self.cfg.GetClusterInfo()
2690
    # validate params changes
2691
    if self.op.beparams:
2692
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2693
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2694

    
2695
    if self.op.nicparams:
2696
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2697
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2698
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2699
      nic_errors = []
2700

    
2701
      # check all instances for consistency
2702
      for instance in self.cfg.GetAllInstancesInfo().values():
2703
        for nic_idx, nic in enumerate(instance.nics):
2704
          params_copy = copy.deepcopy(nic.nicparams)
2705
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2706

    
2707
          # check parameter syntax
2708
          try:
2709
            objects.NIC.CheckParameterSyntax(params_filled)
2710
          except errors.ConfigurationError, err:
2711
            nic_errors.append("Instance %s, nic/%d: %s" %
2712
                              (instance.name, nic_idx, err))
2713

    
2714
          # if we're moving instances to routed, check that they have an ip
2715
          target_mode = params_filled[constants.NIC_MODE]
2716
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2717
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2718
                              (instance.name, nic_idx))
2719
      if nic_errors:
2720
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2721
                                   "\n".join(nic_errors))
2722

    
2723
    # hypervisor list/parameters
2724
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2725
    if self.op.hvparams:
2726
      for hv_name, hv_dict in self.op.hvparams.items():
2727
        if hv_name not in self.new_hvparams:
2728
          self.new_hvparams[hv_name] = hv_dict
2729
        else:
2730
          self.new_hvparams[hv_name].update(hv_dict)
2731

    
2732
    # os hypervisor parameters
2733
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2734
    if self.op.os_hvp:
2735
      for os_name, hvs in self.op.os_hvp.items():
2736
        if os_name not in self.new_os_hvp:
2737
          self.new_os_hvp[os_name] = hvs
2738
        else:
2739
          for hv_name, hv_dict in hvs.items():
2740
            if hv_name not in self.new_os_hvp[os_name]:
2741
              self.new_os_hvp[os_name][hv_name] = hv_dict
2742
            else:
2743
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2744

    
2745
    # os parameters
2746
    self.new_osp = objects.FillDict(cluster.osparams, {})
2747
    if self.op.osparams:
2748
      for os_name, osp in self.op.osparams.items():
2749
        if os_name not in self.new_osp:
2750
          self.new_osp[os_name] = {}
2751

    
2752
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2753
                                                  use_none=True)
2754

    
2755
        if not self.new_osp[os_name]:
2756
          # we removed all parameters
2757
          del self.new_osp[os_name]
2758
        else:
2759
          # check the parameter validity (remote check)
2760
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2761
                         os_name, self.new_osp[os_name])
2762

    
2763
    # changes to the hypervisor list
2764
    if self.op.enabled_hypervisors is not None:
2765
      self.hv_list = self.op.enabled_hypervisors
2766
      for hv in self.hv_list:
2767
        # if the hypervisor doesn't already exist in the cluster
2768
        # hvparams, we initialize it to empty, and then (in both
2769
        # cases) we make sure to fill the defaults, as we might not
2770
        # have a complete defaults list if the hypervisor wasn't
2771
        # enabled before
2772
        if hv not in new_hvp:
2773
          new_hvp[hv] = {}
2774
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2775
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2776
    else:
2777
      self.hv_list = cluster.enabled_hypervisors
2778

    
2779
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2780
      # either the enabled list has changed, or the parameters have, validate
2781
      for hv_name, hv_params in self.new_hvparams.items():
2782
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2783
            (self.op.enabled_hypervisors and
2784
             hv_name in self.op.enabled_hypervisors)):
2785
          # either this is a new hypervisor, or its parameters have changed
2786
          hv_class = hypervisor.GetHypervisor(hv_name)
2787
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2788
          hv_class.CheckParameterSyntax(hv_params)
2789
          _CheckHVParams(self, node_list, hv_name, hv_params)
2790

    
2791
    if self.op.os_hvp:
2792
      # no need to check any newly-enabled hypervisors, since the
2793
      # defaults have already been checked in the above code-block
2794
      for os_name, os_hvp in self.new_os_hvp.items():
2795
        for hv_name, hv_params in os_hvp.items():
2796
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2797
          # we need to fill in the new os_hvp on top of the actual hv_p
2798
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2799
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2800
          hv_class = hypervisor.GetHypervisor(hv_name)
2801
          hv_class.CheckParameterSyntax(new_osp)
2802
          _CheckHVParams(self, node_list, hv_name, new_osp)
2803

    
2804
    if self.op.default_iallocator:
2805
      alloc_script = utils.FindFile(self.op.default_iallocator,
2806
                                    constants.IALLOCATOR_SEARCH_PATH,
2807
                                    os.path.isfile)
2808
      if alloc_script is None:
2809
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2810
                                   " specified" % self.op.default_iallocator,
2811
                                   errors.ECODE_INVAL)
2812

    
2813
  def Exec(self, feedback_fn):
2814
    """Change the parameters of the cluster.
2815

2816
    """
2817
    if self.op.vg_name is not None:
2818
      new_volume = self.op.vg_name
2819
      if not new_volume:
2820
        new_volume = None
2821
      if new_volume != self.cfg.GetVGName():
2822
        self.cfg.SetVGName(new_volume)
2823
      else:
2824
        feedback_fn("Cluster LVM configuration already in desired"
2825
                    " state, not changing")
2826
    if self.op.drbd_helper is not None:
2827
      new_helper = self.op.drbd_helper
2828
      if not new_helper:
2829
        new_helper = None
2830
      if new_helper != self.cfg.GetDRBDHelper():
2831
        self.cfg.SetDRBDHelper(new_helper)
2832
      else:
2833
        feedback_fn("Cluster DRBD helper already in desired state,"
2834
                    " not changing")
2835
    if self.op.hvparams:
2836
      self.cluster.hvparams = self.new_hvparams
2837
    if self.op.os_hvp:
2838
      self.cluster.os_hvp = self.new_os_hvp
2839
    if self.op.enabled_hypervisors is not None:
2840
      self.cluster.hvparams = self.new_hvparams
2841
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2842
    if self.op.beparams:
2843
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2844
    if self.op.nicparams:
2845
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2846
    if self.op.osparams:
2847
      self.cluster.osparams = self.new_osp
2848

    
2849
    if self.op.candidate_pool_size is not None:
2850
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2851
      # we need to update the pool size here, otherwise the save will fail
2852
      _AdjustCandidatePool(self, [])
2853

    
2854
    if self.op.maintain_node_health is not None:
2855
      self.cluster.maintain_node_health = self.op.maintain_node_health
2856

    
2857
    if self.op.add_uids is not None:
2858
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2859

    
2860
    if self.op.remove_uids is not None:
2861
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2862

    
2863
    if self.op.uid_pool is not None:
2864
      self.cluster.uid_pool = self.op.uid_pool
2865

    
2866
    if self.op.default_iallocator is not None:
2867
      self.cluster.default_iallocator = self.op.default_iallocator
2868

    
2869
    self.cfg.Update(self.cluster, feedback_fn)
2870

    
2871

    
2872
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2873
  """Distribute additional files which are part of the cluster configuration.
2874

2875
  ConfigWriter takes care of distributing the config and ssconf files, but
2876
  there are more files which should be distributed to all nodes. This function
2877
  makes sure those are copied.
2878

2879
  @param lu: calling logical unit
2880
  @param additional_nodes: list of nodes not in the config to distribute to
2881

2882
  """
2883
  # 1. Gather target nodes
2884
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2885
  dist_nodes = lu.cfg.GetOnlineNodeList()
2886
  if additional_nodes is not None:
2887
    dist_nodes.extend(additional_nodes)
2888
  if myself.name in dist_nodes:
2889
    dist_nodes.remove(myself.name)
2890

    
2891
  # 2. Gather files to distribute
2892
  dist_files = set([constants.ETC_HOSTS,
2893
                    constants.SSH_KNOWN_HOSTS_FILE,
2894
                    constants.RAPI_CERT_FILE,
2895
                    constants.RAPI_USERS_FILE,
2896
                    constants.CONFD_HMAC_KEY,
2897
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2898
                   ])
2899

    
2900
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2901
  for hv_name in enabled_hypervisors:
2902
    hv_class = hypervisor.GetHypervisor(hv_name)
2903
    dist_files.update(hv_class.GetAncillaryFiles())
2904

    
2905
  # 3. Perform the files upload
2906
  for fname in dist_files:
2907
    if os.path.exists(fname):
2908
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2909
      for to_node, to_result in result.items():
2910
        msg = to_result.fail_msg
2911
        if msg:
2912
          msg = ("Copy of file %s to node %s failed: %s" %
2913
                 (fname, to_node, msg))
2914
          lu.proc.LogWarning(msg)
2915

    
2916

    
2917
class LURedistributeConfig(NoHooksLU):
2918
  """Force the redistribution of cluster configuration.
2919

2920
  This is a very simple LU.
2921

2922
  """
2923
  REQ_BGL = False
2924

    
2925
  def ExpandNames(self):
2926
    self.needed_locks = {
2927
      locking.LEVEL_NODE: locking.ALL_SET,
2928
    }
2929
    self.share_locks[locking.LEVEL_NODE] = 1
2930

    
2931
  def Exec(self, feedback_fn):
2932
    """Redistribute the configuration.
2933

2934
    """
2935
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2936
    _RedistributeAncillaryFiles(self)
2937

    
2938

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

2942
  """
2943
  if not instance.disks or disks is not None and not disks:
2944
    return True
2945

    
2946
  disks = _ExpandCheckDisks(instance, disks)
2947

    
2948
  if not oneshot:
2949
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2950

    
2951
  node = instance.primary_node
2952

    
2953
  for dev in disks:
2954
    lu.cfg.SetDiskID(dev, node)
2955

    
2956
  # TODO: Convert to utils.Retry
2957

    
2958
  retries = 0
2959
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2960
  while True:
2961
    max_time = 0
2962
    done = True
2963
    cumul_degraded = False
2964
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2965
    msg = rstats.fail_msg
2966
    if msg:
2967
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
2968
      retries += 1
2969
      if retries >= 10:
2970
        raise errors.RemoteError("Can't contact node %s for mirror data,"
2971
                                 " aborting." % node)
2972
      time.sleep(6)
2973
      continue
2974
    rstats = rstats.payload
2975
    retries = 0
2976
    for i, mstat in enumerate(rstats):
2977
      if mstat is None:
2978
        lu.LogWarning("Can't compute data for node %s/%s",
2979
                           node, disks[i].iv_name)
2980
        continue
2981

    
2982
      cumul_degraded = (cumul_degraded or
2983
                        (mstat.is_degraded and mstat.sync_percent is None))
2984
      if mstat.sync_percent is not None:
2985
        done = False
2986
        if mstat.estimated_time is not None:
2987
          rem_time = ("%s remaining (estimated)" %
2988
                      utils.FormatSeconds(mstat.estimated_time))
2989
          max_time = mstat.estimated_time
2990
        else:
2991
          rem_time = "no time estimate"
2992
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2993
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2994

    
2995
    # if we're done but degraded, let's do a few small retries, to
2996
    # make sure we see a stable and not transient situation; therefore
2997
    # we force restart of the loop
2998
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2999
      logging.info("Degraded disks found, %d retries left", degr_retries)
3000
      degr_retries -= 1
3001
      time.sleep(1)
3002
      continue
3003

    
3004
    if done or oneshot:
3005
      break
3006

    
3007
    time.sleep(min(60, max_time))
3008

    
3009
  if done:
3010
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3011
  return not cumul_degraded
3012

    
3013

    
3014
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3015
  """Check that mirrors are not degraded.
3016

3017
  The ldisk parameter, if True, will change the test from the
3018
  is_degraded attribute (which represents overall non-ok status for
3019
  the device(s)) to the ldisk (representing the local storage status).
3020

3021
  """
3022
  lu.cfg.SetDiskID(dev, node)
3023

    
3024
  result = True
3025

    
3026
  if on_primary or dev.AssembleOnSecondary():
3027
    rstats = lu.rpc.call_blockdev_find(node, dev)
3028
    msg = rstats.fail_msg
3029
    if msg:
3030
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3031
      result = False
3032
    elif not rstats.payload:
3033
      lu.LogWarning("Can't find disk on node %s", node)
3034
      result = False
3035
    else:
3036
      if ldisk:
3037
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3038
      else:
3039
        result = result and not rstats.payload.is_degraded
3040

    
3041
  if dev.children:
3042
    for child in dev.children:
3043
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3044

    
3045
  return result
3046

    
3047

    
3048
class LUDiagnoseOS(NoHooksLU):
3049
  """Logical unit for OS diagnose/query.
3050

3051
  """
3052
  _OP_PARAMS = [
3053
    _POutputFields,
3054
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3055
    ]
3056
  REQ_BGL = False
3057
  _FIELDS_STATIC = utils.FieldSet()
3058
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3059
                                   "parameters", "api_versions")
3060

    
3061
  def CheckArguments(self):
3062
    if self.op.names:
3063
      raise errors.OpPrereqError("Selective OS query not supported",
3064
                                 errors.ECODE_INVAL)
3065

    
3066
    _CheckOutputFields(static=self._FIELDS_STATIC,
3067
                       dynamic=self._FIELDS_DYNAMIC,
3068
                       selected=self.op.output_fields)
3069

    
3070
  def ExpandNames(self):
3071
    # Lock all nodes, in shared mode
3072
    # Temporary removal of locks, should be reverted later
3073
    # TODO: reintroduce locks when they are lighter-weight
3074
    self.needed_locks = {}
3075
    #self.share_locks[locking.LEVEL_NODE] = 1
3076
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3077

    
3078
  @staticmethod
3079
  def _DiagnoseByOS(rlist):
3080
    """Remaps a per-node return list into an a per-os per-node dictionary
3081

3082
    @param rlist: a map with node names as keys and OS objects as values
3083

3084
    @rtype: dict
3085
    @return: a dictionary with osnames as keys and as value another
3086
        map, with nodes as keys and tuples of (path, status, diagnose,
3087
        variants, parameters, api_versions) as values, eg::
3088

3089
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3090
                                     (/srv/..., False, "invalid api")],
3091
                           "node2": [(/srv/..., True, "", [], [])]}
3092
          }
3093

3094
    """
3095
    all_os = {}
3096
    # we build here the list of nodes that didn't fail the RPC (at RPC
3097
    # level), so that nodes with a non-responding node daemon don't
3098
    # make all OSes invalid
3099
    good_nodes = [node_name for node_name in rlist
3100
                  if not rlist[node_name].fail_msg]
3101
    for node_name, nr in rlist.items():
3102
      if nr.fail_msg or not nr.payload:
3103
        continue
3104
      for (name, path, status, diagnose, variants,
3105
           params, api_versions) in nr.payload:
3106
        if name not in all_os:
3107
          # build a list of nodes for this os containing empty lists
3108
          # for each node in node_list
3109
          all_os[name] = {}
3110
          for nname in good_nodes:
3111
            all_os[name][nname] = []
3112
        # convert params from [name, help] to (name, help)
3113
        params = [tuple(v) for v in params]
3114
        all_os[name][node_name].append((path, status, diagnose,
3115
                                        variants, params, api_versions))
3116
    return all_os
3117

    
3118
  def Exec(self, feedback_fn):
3119
    """Compute the list of OSes.
3120

3121
    """
3122
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3123
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3124
    pol = self._DiagnoseByOS(node_data)
3125
    output = []
3126

    
3127
    for os_name, os_data in pol.items():
3128
      row = []
3129
      valid = True
3130
      (variants, params, api_versions) = null_state = (set(), set(), set())
3131
      for idx, osl in enumerate(os_data.values()):
3132
        valid = bool(valid and osl and osl[0][1])
3133
        if not valid:
3134
          (variants, params, api_versions) = null_state
3135
          break
3136
        node_variants, node_params, node_api = osl[0][3:6]
3137
        if idx == 0: # first entry
3138
          variants = set(node_variants)
3139
          params = set(node_params)
3140
          api_versions = set(node_api)
3141
        else: # keep consistency
3142
          variants.intersection_update(node_variants)
3143
          params.intersection_update(node_params)
3144
          api_versions.intersection_update(node_api)
3145

    
3146
      for field in self.op.output_fields:
3147
        if field == "name":
3148
          val = os_name
3149
        elif field == "valid":
3150
          val = valid
3151
        elif field == "node_status":
3152
          # this is just a copy of the dict
3153
          val = {}
3154
          for node_name, nos_list in os_data.items():
3155
            val[node_name] = nos_list
3156
        elif field == "variants":
3157
          val = list(variants)
3158
        elif field == "parameters":
3159
          val = list(params)
3160
        elif field == "api_versions":
3161
          val = list(api_versions)
3162
        else:
3163
          raise errors.ParameterError(field)
3164
        row.append(val)
3165
      output.append(row)
3166

    
3167
    return output
3168

    
3169

    
3170
class LURemoveNode(LogicalUnit):
3171
  """Logical unit for removing a node.
3172

3173
  """
3174
  HPATH = "node-remove"
3175
  HTYPE = constants.HTYPE_NODE
3176
  _OP_PARAMS = [
3177
    _PNodeName,
3178
    ]
3179

    
3180
  def BuildHooksEnv(self):
3181
    """Build hooks env.
3182

3183
    This doesn't run on the target node in the pre phase as a failed
3184
    node would then be impossible to remove.
3185

3186
    """
3187
    env = {
3188
      "OP_TARGET": self.op.node_name,
3189
      "NODE_NAME": self.op.node_name,
3190
      }
3191
    all_nodes = self.cfg.GetNodeList()
3192
    try:
3193
      all_nodes.remove(self.op.node_name)
3194
    except ValueError:
3195
      logging.warning("Node %s which is about to be removed not found"
3196
                      " in the all nodes list", self.op.node_name)
3197
    return env, all_nodes, all_nodes
3198

    
3199
  def CheckPrereq(self):
3200
    """Check prerequisites.
3201

3202
    This checks:
3203
     - the node exists in the configuration
3204
     - it does not have primary or secondary instances
3205
     - it's not the master
3206

3207
    Any errors are signaled by raising errors.OpPrereqError.
3208

3209
    """
3210
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3211
    node = self.cfg.GetNodeInfo(self.op.node_name)
3212
    assert node is not None
3213

    
3214
    instance_list = self.cfg.GetInstanceList()
3215

    
3216
    masternode = self.cfg.GetMasterNode()
3217
    if node.name == masternode:
3218
      raise errors.OpPrereqError("Node is the master node,"
3219
                                 " you need to failover first.",
3220
                                 errors.ECODE_INVAL)
3221

    
3222
    for instance_name in instance_list:
3223
      instance = self.cfg.GetInstanceInfo(instance_name)
3224
      if node.name in instance.all_nodes:
3225
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3226
                                   " please remove first." % instance_name,
3227
                                   errors.ECODE_INVAL)
3228
    self.op.node_name = node.name
3229
    self.node = node
3230

    
3231
  def Exec(self, feedback_fn):
3232
    """Removes the node from the cluster.
3233

3234
    """
3235
    node = self.node
3236
    logging.info("Stopping the node daemon and removing configs from node %s",
3237
                 node.name)
3238

    
3239
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3240

    
3241
    # Promote nodes to master candidate as needed
3242
    _AdjustCandidatePool(self, exceptions=[node.name])
3243
    self.context.RemoveNode(node.name)
3244

    
3245
    # Run post hooks on the node before it's removed
3246
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3247
    try:
3248
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3249
    except:
3250
      # pylint: disable-msg=W0702
3251
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3252

    
3253
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3254
    msg = result.fail_msg
3255
    if msg:
3256
      self.LogWarning("Errors encountered on the remote node while leaving"
3257
                      " the cluster: %s", msg)
3258

    
3259
    # Remove node from our /etc/hosts
3260
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3261
      # FIXME: this should be done via an rpc call to node daemon
3262
      utils.RemoveHostFromEtcHosts(node.name)
3263
      _RedistributeAncillaryFiles(self)
3264

    
3265

    
3266
class LUQueryNodes(NoHooksLU):
3267
  """Logical unit for querying nodes.
3268

3269
  """
3270
  # pylint: disable-msg=W0142
3271
  _OP_PARAMS = [
3272
    _POutputFields,
3273
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3274
    ("use_locking", False, _TBool),
3275
    ]
3276
  REQ_BGL = False
3277

    
3278
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3279
                    "master_candidate", "offline", "drained"]
3280

    
3281
  _FIELDS_DYNAMIC = utils.FieldSet(
3282
    "dtotal", "dfree",
3283
    "mtotal", "mnode", "mfree",
3284
    "bootid",
3285
    "ctotal", "cnodes", "csockets",
3286
    )
3287

    
3288
  _FIELDS_STATIC = utils.FieldSet(*[
3289
    "pinst_cnt", "sinst_cnt",
3290
    "pinst_list", "sinst_list",
3291
    "pip", "sip", "tags",
3292
    "master",
3293
    "role"] + _SIMPLE_FIELDS
3294
    )
3295

    
3296
  def CheckArguments(self):
3297
    _CheckOutputFields(static=self._FIELDS_STATIC,
3298
                       dynamic=self._FIELDS_DYNAMIC,
3299
                       selected=self.op.output_fields)
3300

    
3301
  def ExpandNames(self):
3302
    self.needed_locks = {}
3303
    self.share_locks[locking.LEVEL_NODE] = 1
3304

    
3305
    if self.op.names:
3306
      self.wanted = _GetWantedNodes(self, self.op.names)
3307
    else:
3308
      self.wanted = locking.ALL_SET
3309

    
3310
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3311
    self.do_locking = self.do_node_query and self.op.use_locking
3312
    if self.do_locking:
3313
      # if we don't request only static fields, we need to lock the nodes
3314
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3315

    
3316
  def Exec(self, feedback_fn):
3317
    """Computes the list of nodes and their attributes.
3318

3319
    """
3320
    all_info = self.cfg.GetAllNodesInfo()
3321
    if self.do_locking:
3322
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3323
    elif self.wanted != locking.ALL_SET:
3324
      nodenames = self.wanted
3325
      missing = set(nodenames).difference(all_info.keys())
3326
      if missing:
3327
        raise errors.OpExecError(
3328
          "Some nodes were removed before retrieving their data: %s" % missing)
3329
    else:
3330
      nodenames = all_info.keys()
3331

    
3332
    nodenames = utils.NiceSort(nodenames)
3333
    nodelist = [all_info[name] for name in nodenames]
3334

    
3335
    # begin data gathering
3336

    
3337
    if self.do_node_query:
3338
      live_data = {}
3339
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3340
                                          self.cfg.GetHypervisorType())
3341
      for name in nodenames:
3342
        nodeinfo = node_data[name]
3343
        if not nodeinfo.fail_msg and nodeinfo.payload:
3344
          nodeinfo = nodeinfo.payload
3345
          fn = utils.TryConvert
3346
          live_data[name] = {
3347
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3348
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3349
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3350
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3351
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3352
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3353
            "bootid": nodeinfo.get('bootid', None),
3354
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3355
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3356
            }
3357
        else:
3358
          live_data[name] = {}
3359
    else:
3360
      live_data = dict.fromkeys(nodenames, {})
3361

    
3362
    node_to_primary = dict([(name, set()) for name in nodenames])
3363
    node_to_secondary = dict([(name, set()) for name in nodenames])
3364

    
3365
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3366
                             "sinst_cnt", "sinst_list"))
3367
    if inst_fields & frozenset(self.op.output_fields):
3368
      inst_data = self.cfg.GetAllInstancesInfo()
3369

    
3370
      for inst in inst_data.values():
3371
        if inst.primary_node in node_to_primary:
3372
          node_to_primary[inst.primary_node].add(inst.name)
3373
        for secnode in inst.secondary_nodes:
3374
          if secnode in node_to_secondary:
3375
            node_to_secondary[secnode].add(inst.name)
3376

    
3377
    master_node = self.cfg.GetMasterNode()
3378

    
3379
    # end data gathering
3380

    
3381
    output = []
3382
    for node in nodelist:
3383
      node_output = []
3384
      for field in self.op.output_fields:
3385
        if field in self._SIMPLE_FIELDS:
3386
          val = getattr(node, field)
3387
        elif field == "pinst_list":
3388
          val = list(node_to_primary[node.name])
3389
        elif field == "sinst_list":
3390
          val = list(node_to_secondary[node.name])
3391
        elif field == "pinst_cnt":
3392
          val = len(node_to_primary[node.name])
3393
        elif field == "sinst_cnt":
3394
          val = len(node_to_secondary[node.name])
3395
        elif field == "pip":
3396
          val = node.primary_ip
3397
        elif field == "sip":
3398
          val = node.secondary_ip
3399
        elif field == "tags":
3400
          val = list(node.GetTags())
3401
        elif field == "master":
3402
          val = node.name == master_node
3403
        elif self._FIELDS_DYNAMIC.Matches(field):
3404
          val = live_data[node.name].get(field, None)
3405
        elif field == "role":
3406
          if node.name == master_node:
3407
            val = "M"
3408
          elif node.master_candidate:
3409
            val = "C"
3410
          elif node.drained:
3411
            val = "D"
3412
          elif node.offline:
3413
            val = "O"
3414
          else:
3415
            val = "R"
3416
        else:
3417
          raise errors.ParameterError(field)
3418
        node_output.append(val)
3419
      output.append(node_output)
3420

    
3421
    return output
3422

    
3423

    
3424
class LUQueryNodeVolumes(NoHooksLU):
3425
  """Logical unit for getting volumes on node(s).
3426

3427
  """
3428
  _OP_PARAMS = [
3429
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3430
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3431
    ]
3432
  REQ_BGL = False
3433
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3434
  _FIELDS_STATIC = utils.FieldSet("node")
3435

    
3436
  def CheckArguments(self):
3437
    _CheckOutputFields(static=self._FIELDS_STATIC,
3438
                       dynamic=self._FIELDS_DYNAMIC,
3439
                       selected=self.op.output_fields)
3440

    
3441
  def ExpandNames(self):
3442
    self.needed_locks = {}
3443
    self.share_locks[locking.LEVEL_NODE] = 1
3444
    if not self.op.nodes:
3445
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3446
    else:
3447
      self.needed_locks[locking.LEVEL_NODE] = \
3448
        _GetWantedNodes(self, self.op.nodes)
3449

    
3450
  def Exec(self, feedback_fn):
3451
    """Computes the list of nodes and their attributes.
3452

3453
    """
3454
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3455
    volumes = self.rpc.call_node_volumes(nodenames)
3456

    
3457
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3458
             in self.cfg.GetInstanceList()]
3459

    
3460
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3461

    
3462
    output = []
3463
    for node in nodenames:
3464
      nresult = volumes[node]
3465
      if nresult.offline:
3466
        continue
3467
      msg = nresult.fail_msg
3468
      if msg:
3469
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3470
        continue
3471

    
3472
      node_vols = nresult.payload[:]
3473
      node_vols.sort(key=lambda vol: vol['dev'])
3474

    
3475
      for vol in node_vols:
3476
        node_output = []
3477
        for field in self.op.output_fields:
3478
          if field == "node":
3479
            val = node
3480
          elif field == "phys":
3481
            val = vol['dev']
3482
          elif field == "vg":
3483
            val = vol['vg']
3484
          elif field == "name":
3485
            val = vol['name']
3486
          elif field == "size":
3487
            val = int(float(vol['size']))
3488
          elif field == "instance":
3489
            for inst in ilist:
3490
              if node not in lv_by_node[inst]:
3491
                continue
3492
              if vol['name'] in lv_by_node[inst][node]:
3493
                val = inst.name
3494
                break
3495
            else:
3496
              val = '-'
3497
          else:
3498
            raise errors.ParameterError(field)
3499
          node_output.append(str(val))
3500

    
3501
        output.append(node_output)
3502

    
3503
    return output
3504

    
3505

    
3506
class LUQueryNodeStorage(NoHooksLU):
3507
  """Logical unit for getting information on storage units on node(s).
3508

3509
  """
3510
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3511
  _OP_PARAMS = [
3512
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3513
    ("storage_type", _NoDefault, _CheckStorageType),
3514
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3515
    ("name", None, _TMaybeString),
3516
    ]
3517
  REQ_BGL = False
3518

    
3519
  def CheckArguments(self):
3520
    _CheckOutputFields(static=self._FIELDS_STATIC,
3521
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3522
                       selected=self.op.output_fields)
3523

    
3524
  def ExpandNames(self):
3525
    self.needed_locks = {}
3526
    self.share_locks[locking.LEVEL_NODE] = 1
3527

    
3528
    if self.op.nodes:
3529
      self.needed_locks[locking.LEVEL_NODE] = \
3530
        _GetWantedNodes(self, self.op.nodes)
3531
    else:
3532
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3533

    
3534
  def Exec(self, feedback_fn):
3535
    """Computes the list of nodes and their attributes.
3536

3537
    """
3538
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3539

    
3540
    # Always get name to sort by
3541
    if constants.SF_NAME in self.op.output_fields:
3542
      fields = self.op.output_fields[:]
3543
    else:
3544
      fields = [constants.SF_NAME] + self.op.output_fields
3545

    
3546
    # Never ask for node or type as it's only known to the LU
3547
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3548
      while extra in fields:
3549
        fields.remove(extra)
3550

    
3551
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3552
    name_idx = field_idx[constants.SF_NAME]
3553

    
3554
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3555
    data = self.rpc.call_storage_list(self.nodes,
3556
                                      self.op.storage_type, st_args,
3557
                                      self.op.name, fields)
3558

    
3559
    result = []
3560

    
3561
    for node in utils.NiceSort(self.nodes):
3562
      nresult = data[node]
3563
      if nresult.offline:
3564
        continue
3565

    
3566
      msg = nresult.fail_msg
3567
      if msg:
3568
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3569
        continue
3570

    
3571
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3572

    
3573
      for name in utils.NiceSort(rows.keys()):
3574
        row = rows[name]
3575

    
3576
        out = []
3577

    
3578
        for field in self.op.output_fields:
3579
          if field == constants.SF_NODE:
3580
            val = node
3581
          elif field == constants.SF_TYPE:
3582
            val = self.op.storage_type
3583
          elif field in field_idx:
3584
            val = row[field_idx[field]]
3585
          else:
3586
            raise errors.ParameterError(field)
3587

    
3588
          out.append(val)
3589

    
3590
        result.append(out)
3591

    
3592
    return result
3593

    
3594

    
3595
class LUModifyNodeStorage(NoHooksLU):
3596
  """Logical unit for modifying a storage volume on a node.
3597

3598
  """
3599
  _OP_PARAMS = [
3600
    _PNodeName,
3601
    ("storage_type", _NoDefault, _CheckStorageType),
3602
    ("name", _NoDefault, _TNonEmptyString),
3603
    ("changes", _NoDefault, _TDict),
3604
    ]
3605
  REQ_BGL = False
3606

    
3607
  def CheckArguments(self):
3608
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3609

    
3610
    storage_type = self.op.storage_type
3611

    
3612
    try:
3613
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3614
    except KeyError:
3615
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3616
                                 " modified" % storage_type,
3617
                                 errors.ECODE_INVAL)
3618

    
3619
    diff = set(self.op.changes.keys()) - modifiable
3620
    if diff:
3621
      raise errors.OpPrereqError("The following fields can not be modified for"
3622
                                 " storage units of type '%s': %r" %
3623
                                 (storage_type, list(diff)),
3624
                                 errors.ECODE_INVAL)
3625

    
3626
  def ExpandNames(self):
3627
    self.needed_locks = {
3628
      locking.LEVEL_NODE: self.op.node_name,
3629
      }
3630

    
3631
  def Exec(self, feedback_fn):
3632
    """Computes the list of nodes and their attributes.
3633

3634
    """
3635
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3636
    result = self.rpc.call_storage_modify(self.op.node_name,
3637
                                          self.op.storage_type, st_args,
3638
                                          self.op.name, self.op.changes)
3639
    result.Raise("Failed to modify storage unit '%s' on %s" %
3640
                 (self.op.name, self.op.node_name))
3641

    
3642

    
3643
class LUAddNode(LogicalUnit):
3644
  """Logical unit for adding node to the cluster.
3645

3646
  """
3647
  HPATH = "node-add"
3648
  HTYPE = constants.HTYPE_NODE
3649
  _OP_PARAMS = [
3650
    _PNodeName,
3651
    ("primary_ip", None, _NoType),
3652
    ("secondary_ip", None, _TMaybeString),
3653
    ("readd", False, _TBool),
3654
    ]
3655

    
3656
  def CheckArguments(self):
3657
    # validate/normalize the node name
3658
    self.op.node_name = netutils.HostInfo.NormalizeName(self.op.node_name)
3659

    
3660
  def BuildHooksEnv(self):
3661
    """Build hooks env.
3662

3663
    This will run on all nodes before, and on all nodes + the new node after.
3664

3665
    """
3666
    env = {
3667
      "OP_TARGET": self.op.node_name,
3668
      "NODE_NAME": self.op.node_name,
3669
      "NODE_PIP": self.op.primary_ip,
3670
      "NODE_SIP": self.op.secondary_ip,
3671
      }
3672
    nodes_0 = self.cfg.GetNodeList()
3673
    nodes_1 = nodes_0 + [self.op.node_name, ]
3674
    return env, nodes_0, nodes_1
3675

    
3676
  def CheckPrereq(self):
3677
    """Check prerequisites.
3678

3679
    This checks:
3680
     - the new node is not already in the config
3681
     - it is resolvable
3682
     - its parameters (single/dual homed) matches the cluster
3683

3684
    Any errors are signaled by raising errors.OpPrereqError.
3685

3686
    """
3687
    node_name = self.op.node_name
3688
    cfg = self.cfg
3689

    
3690
    dns_data = netutils.GetHostInfo(node_name)
3691

    
3692
    node = dns_data.name
3693
    primary_ip = self.op.primary_ip = dns_data.ip
3694
    if self.op.secondary_ip is None:
3695
      self.op.secondary_ip = primary_ip
3696
    if not netutils.IsValidIP4(self.op.secondary_ip):
3697
      raise errors.OpPrereqError("Invalid secondary IP given",
3698
                                 errors.ECODE_INVAL)
3699
    secondary_ip = self.op.secondary_ip
3700

    
3701
    node_list = cfg.GetNodeList()
3702
    if not self.op.readd and node in node_list:
3703
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3704
                                 node, errors.ECODE_EXISTS)
3705
    elif self.op.readd and node not in node_list:
3706
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3707
                                 errors.ECODE_NOENT)
3708

    
3709
    self.changed_primary_ip = False
3710

    
3711
    for existing_node_name in node_list:
3712
      existing_node = cfg.GetNodeInfo(existing_node_name)
3713

    
3714
      if self.op.readd and node == existing_node_name:
3715
        if existing_node.secondary_ip != secondary_ip:
3716
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3717
                                     " address configuration as before",
3718
                                     errors.ECODE_INVAL)
3719
        if existing_node.primary_ip != primary_ip:
3720
          self.changed_primary_ip = True
3721

    
3722
        continue
3723

    
3724
      if (existing_node.primary_ip == primary_ip or
3725
          existing_node.secondary_ip == primary_ip or
3726
          existing_node.primary_ip == secondary_ip or
3727
          existing_node.secondary_ip == secondary_ip):
3728
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3729
                                   " existing node %s" % existing_node.name,
3730
                                   errors.ECODE_NOTUNIQUE)
3731

    
3732
    # check that the type of the node (single versus dual homed) is the
3733
    # same as for the master
3734
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3735
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3736
    newbie_singlehomed = secondary_ip == primary_ip
3737
    if master_singlehomed != newbie_singlehomed:
3738
      if master_singlehomed:
3739
        raise errors.OpPrereqError("The master has no private ip but the"
3740
                                   " new node has one",
3741
                                   errors.ECODE_INVAL)
3742
      else:
3743
        raise errors.OpPrereqError("The master has a private ip but the"
3744
                                   " new node doesn't have one",
3745
                                   errors.ECODE_INVAL)
3746

    
3747
    # checks reachability
3748
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3749
      raise errors.OpPrereqError("Node not reachable by ping",
3750
                                 errors.ECODE_ENVIRON)
3751

    
3752
    if not newbie_singlehomed:
3753
      # check reachability from my secondary ip to newbie's secondary ip
3754
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3755
                           source=myself.secondary_ip):
3756
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3757
                                   " based ping to noded port",
3758
                                   errors.ECODE_ENVIRON)
3759

    
3760
    if self.op.readd:
3761
      exceptions = [node]
3762
    else:
3763
      exceptions = []
3764

    
3765
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3766

    
3767
    if self.op.readd:
3768
      self.new_node = self.cfg.GetNodeInfo(node)
3769
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3770
    else:
3771
      self.new_node = objects.Node(name=node,
3772
                                   primary_ip=primary_ip,
3773
                                   secondary_ip=secondary_ip,
3774
                                   master_candidate=self.master_candidate,
3775
                                   offline=False, drained=False)
3776

    
3777
  def Exec(self, feedback_fn):
3778
    """Adds the new node to the cluster.
3779

3780
    """
3781
    new_node = self.new_node
3782
    node = new_node.name
3783

    
3784
    # for re-adds, reset the offline/drained/master-candidate flags;
3785
    # we need to reset here, otherwise offline would prevent RPC calls
3786
    # later in the procedure; this also means that if the re-add
3787
    # fails, we are left with a non-offlined, broken node
3788
    if self.op.readd:
3789
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3790
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3791
      # if we demote the node, we do cleanup later in the procedure
3792
      new_node.master_candidate = self.master_candidate
3793
      if self.changed_primary_ip:
3794
        new_node.primary_ip = self.op.primary_ip
3795

    
3796
    # notify the user about any possible mc promotion
3797
    if new_node.master_candidate:
3798
      self.LogInfo("Node will be a master candidate")
3799

    
3800
    # check connectivity
3801
    result = self.rpc.call_version([node])[node]
3802
    result.Raise("Can't get version information from node %s" % node)
3803
    if constants.PROTOCOL_VERSION == result.payload:
3804
      logging.info("Communication to node %s fine, sw version %s match",
3805
                   node, result.payload)
3806
    else:
3807
      raise errors.OpExecError("Version mismatch master version %s,"
3808
                               " node version %s" %
3809
                               (constants.PROTOCOL_VERSION, result.payload))
3810

    
3811
    # setup ssh on node
3812
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3813
      logging.info("Copy ssh key to node %s", node)
3814
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3815
      keyarray = []
3816
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3817
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3818
                  priv_key, pub_key]
3819

    
3820
      for i in keyfiles:
3821
        keyarray.append(utils.ReadFile(i))
3822

    
3823
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3824
                                      keyarray[2], keyarray[3], keyarray[4],
3825
                                      keyarray[5])
3826
      result.Raise("Cannot transfer ssh keys to the new node")
3827

    
3828
    # Add node to our /etc/hosts, and add key to known_hosts
3829
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3830
      # FIXME: this should be done via an rpc call to node daemon
3831
      utils.AddHostToEtcHosts(new_node.name)
3832

    
3833
    if new_node.secondary_ip != new_node.primary_ip:
3834
      result = self.rpc.call_node_has_ip_address(new_node.name,
3835
                                                 new_node.secondary_ip)
3836
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3837
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3838
      if not result.payload:
3839
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3840
                                 " you gave (%s). Please fix and re-run this"
3841
                                 " command." % new_node.secondary_ip)
3842

    
3843
    node_verify_list = [self.cfg.GetMasterNode()]
3844
    node_verify_param = {
3845
      constants.NV_NODELIST: [node],
3846
      # TODO: do a node-net-test as well?
3847
    }
3848

    
3849
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3850
                                       self.cfg.GetClusterName())
3851
    for verifier in node_verify_list:
3852
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3853
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3854
      if nl_payload:
3855
        for failed in nl_payload:
3856
          feedback_fn("ssh/hostname verification failed"
3857
                      " (checking from %s): %s" %
3858
                      (verifier, nl_payload[failed]))
3859
        raise errors.OpExecError("ssh/hostname verification failed.")
3860

    
3861
    if self.op.readd:
3862
      _RedistributeAncillaryFiles(self)
3863
      self.context.ReaddNode(new_node)
3864
      # make sure we redistribute the config
3865
      self.cfg.Update(new_node, feedback_fn)
3866
      # and make sure the new node will not have old files around
3867
      if not new_node.master_candidate:
3868
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3869
        msg = result.fail_msg
3870
        if msg:
3871
          self.LogWarning("Node failed to demote itself from master"
3872
                          " candidate status: %s" % msg)
3873
    else:
3874
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3875
      self.context.AddNode(new_node, self.proc.GetECId())
3876

    
3877

    
3878
class LUSetNodeParams(LogicalUnit):
3879
  """Modifies the parameters of a node.
3880

3881
  """
3882
  HPATH = "node-modify"
3883
  HTYPE = constants.HTYPE_NODE
3884
  _OP_PARAMS = [
3885
    _PNodeName,
3886
    ("master_candidate", None, _TMaybeBool),
3887
    ("offline", None, _TMaybeBool),
3888
    ("drained", None, _TMaybeBool),
3889
    ("auto_promote", False, _TBool),
3890
    _PForce,
3891
    ]
3892
  REQ_BGL = False
3893

    
3894
  def CheckArguments(self):
3895
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3896
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3897
    if all_mods.count(None) == 3:
3898
      raise errors.OpPrereqError("Please pass at least one modification",
3899
                                 errors.ECODE_INVAL)
3900
    if all_mods.count(True) > 1:
3901
      raise errors.OpPrereqError("Can't set the node into more than one"
3902
                                 " state at the same time",
3903
                                 errors.ECODE_INVAL)
3904

    
3905
    # Boolean value that tells us whether we're offlining or draining the node
3906
    self.offline_or_drain = (self.op.offline == True or
3907
                             self.op.drained == True)
3908
    self.deoffline_or_drain = (self.op.offline == False or
3909
                               self.op.drained == False)
3910
    self.might_demote = (self.op.master_candidate == False or
3911
                         self.offline_or_drain)
3912

    
3913
    self.lock_all = self.op.auto_promote and self.might_demote
3914

    
3915

    
3916
  def ExpandNames(self):
3917
    if self.lock_all:
3918
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3919
    else:
3920
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3921

    
3922
  def BuildHooksEnv(self):
3923
    """Build hooks env.
3924

3925
    This runs on the master node.
3926

3927
    """
3928
    env = {
3929
      "OP_TARGET": self.op.node_name,
3930
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3931
      "OFFLINE": str(self.op.offline),
3932
      "DRAINED": str(self.op.drained),
3933
      }
3934
    nl = [self.cfg.GetMasterNode(),
3935
          self.op.node_name]
3936
    return env, nl, nl
3937

    
3938
  def CheckPrereq(self):
3939
    """Check prerequisites.
3940

3941
    This only checks the instance list against the existing names.
3942

3943
    """
3944
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3945

    
3946
    if (self.op.master_candidate is not None or
3947
        self.op.drained is not None or
3948
        self.op.offline is not None):
3949
      # we can't change the master's node flags
3950
      if self.op.node_name == self.cfg.GetMasterNode():
3951
        raise errors.OpPrereqError("The master role can be changed"
3952
                                   " only via masterfailover",
3953
                                   errors.ECODE_INVAL)
3954

    
3955

    
3956
    if node.master_candidate and self.might_demote and not self.lock_all:
3957
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3958
      # check if after removing the current node, we're missing master
3959
      # candidates
3960
      (mc_remaining, mc_should, _) = \
3961
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3962
      if mc_remaining < mc_should:
3963
        raise errors.OpPrereqError("Not enough master candidates, please"
3964
                                   " pass auto_promote to allow promotion",
3965
                                   errors.ECODE_INVAL)
3966

    
3967
    if (self.op.master_candidate == True and
3968
        ((node.offline and not self.op.offline == False) or
3969
         (node.drained and not self.op.drained == False))):
3970
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3971
                                 " to master_candidate" % node.name,
3972
                                 errors.ECODE_INVAL)
3973

    
3974
    # If we're being deofflined/drained, we'll MC ourself if needed
3975
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3976
        self.op.master_candidate == True and not node.master_candidate):
3977
      self.op.master_candidate = _DecideSelfPromotion(self)
3978
      if self.op.master_candidate:
3979
        self.LogInfo("Autopromoting node to master candidate")
3980

    
3981
    return
3982

    
3983
  def Exec(self, feedback_fn):
3984
    """Modifies a node.
3985

3986
    """
3987
    node = self.node
3988

    
3989
    result = []
3990
    changed_mc = False
3991

    
3992
    if self.op.offline is not None:
3993
      node.offline = self.op.offline
3994
      result.append(("offline", str(self.op.offline)))
3995
      if self.op.offline == True:
3996
        if node.master_candidate:
3997
          node.master_candidate = False
3998
          changed_mc = True
3999
          result.append(("master_candidate", "auto-demotion due to offline"))
4000
        if node.drained:
4001
          node.drained = False
4002
          result.append(("drained", "clear drained status due to offline"))
4003

    
4004
    if self.op.master_candidate is not None:
4005
      node.master_candidate = self.op.master_candidate
4006
      changed_mc = True
4007
      result.append(("master_candidate", str(self.op.master_candidate)))
4008
      if self.op.master_candidate == False:
4009
        rrc = self.rpc.call_node_demote_from_mc(node.name)
4010
        msg = rrc.fail_msg
4011
        if msg:
4012
          self.LogWarning("Node failed to demote itself: %s" % msg)
4013

    
4014
    if self.op.drained is not None:
4015
      node.drained = self.op.drained
4016
      result.append(("drained", str(self.op.drained)))
4017
      if self.op.drained == True:
4018
        if node.master_candidate:
4019
          node.master_candidate = False
4020
          changed_mc = True
4021
          result.append(("master_candidate", "auto-demotion due to drain"))
4022
          rrc = self.rpc.call_node_demote_from_mc(node.name)
4023
          msg = rrc.fail_msg
4024
          if msg:
4025
            self.LogWarning("Node failed to demote itself: %s" % msg)
4026
        if node.offline:
4027
          node.offline = False
4028
          result.append(("offline", "clear offline status due to drain"))
4029

    
4030
    # we locked all nodes, we adjust the CP before updating this node
4031
    if self.lock_all:
4032
      _AdjustCandidatePool(self, [node.name])
4033

    
4034
    # this will trigger configuration file update, if needed
4035
    self.cfg.Update(node, feedback_fn)
4036

    
4037
    # this will trigger job queue propagation or cleanup
4038
    if changed_mc:
4039
      self.context.ReaddNode(node)
4040

    
4041
    return result
4042

    
4043

    
4044
class LUPowercycleNode(NoHooksLU):
4045
  """Powercycles a node.
4046

4047
  """
4048
  _OP_PARAMS = [
4049
    _PNodeName,
4050
    _PForce,
4051
    ]
4052
  REQ_BGL = False
4053

    
4054
  def CheckArguments(self):
4055
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4056
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4057
      raise errors.OpPrereqError("The node is the master and the force"
4058
                                 " parameter was not set",
4059
                                 errors.ECODE_INVAL)
4060

    
4061
  def ExpandNames(self):
4062
    """Locking for PowercycleNode.
4063

4064
    This is a last-resort option and shouldn't block on other
4065
    jobs. Therefore, we grab no locks.
4066

4067
    """
4068
    self.needed_locks = {}
4069

    
4070
  def Exec(self, feedback_fn):
4071
    """Reboots a node.
4072

4073
    """
4074
    result = self.rpc.call_node_powercycle(self.op.node_name,
4075
                                           self.cfg.GetHypervisorType())
4076
    result.Raise("Failed to schedule the reboot")
4077
    return result.payload
4078

    
4079

    
4080
class LUQueryClusterInfo(NoHooksLU):
4081
  """Query cluster configuration.
4082

4083
  """
4084
  REQ_BGL = False
4085

    
4086
  def ExpandNames(self):
4087
    self.needed_locks = {}
4088

    
4089
  def Exec(self, feedback_fn):
4090
    """Return cluster config.
4091

4092
    """
4093
    cluster = self.cfg.GetClusterInfo()
4094
    os_hvp = {}
4095

    
4096
    # Filter just for enabled hypervisors
4097
    for os_name, hv_dict in cluster.os_hvp.items():
4098
      os_hvp[os_name] = {}
4099
      for hv_name, hv_params in hv_dict.items():
4100
        if hv_name in cluster.enabled_hypervisors:
4101
          os_hvp[os_name][hv_name] = hv_params
4102

    
4103
    result = {
4104
      "software_version": constants.RELEASE_VERSION,
4105
      "protocol_version": constants.PROTOCOL_VERSION,
4106
      "config_version": constants.CONFIG_VERSION,
4107
      "os_api_version": max(constants.OS_API_VERSIONS),
4108
      "export_version": constants.EXPORT_VERSION,
4109
      "architecture": (platform.architecture()[0], platform.machine()),
4110
      "name": cluster.cluster_name,
4111
      "master": cluster.master_node,
4112
      "default_hypervisor": cluster.enabled_hypervisors[0],
4113
      "enabled_hypervisors": cluster.enabled_hypervisors,
4114
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4115
                        for hypervisor_name in cluster.enabled_hypervisors]),
4116
      "os_hvp": os_hvp,
4117
      "beparams": cluster.beparams,
4118
      "osparams": cluster.osparams,
4119
      "nicparams": cluster.nicparams,
4120
      "candidate_pool_size": cluster.candidate_pool_size,
4121
      "master_netdev": cluster.master_netdev,
4122
      "volume_group_name": cluster.volume_group_name,
4123
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4124
      "file_storage_dir": cluster.file_storage_dir,
4125
      "maintain_node_health": cluster.maintain_node_health,
4126
      "ctime": cluster.ctime,
4127
      "mtime": cluster.mtime,
4128
      "uuid": cluster.uuid,
4129
      "tags": list(cluster.GetTags()),
4130
      "uid_pool": cluster.uid_pool,
4131
      "default_iallocator": cluster.default_iallocator,
4132
      }
4133

    
4134
    return result
4135

    
4136

    
4137
class LUQueryConfigValues(NoHooksLU):
4138
  """Return configuration values.
4139

4140
  """
4141
  _OP_PARAMS = [_POutputFields]
4142
  REQ_BGL = False
4143
  _FIELDS_DYNAMIC = utils.FieldSet()
4144
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4145
                                  "watcher_pause")
4146

    
4147
  def CheckArguments(self):
4148
    _CheckOutputFields(static=self._FIELDS_STATIC,
4149
                       dynamic=self._FIELDS_DYNAMIC,
4150
                       selected=self.op.output_fields)
4151

    
4152
  def ExpandNames(self):
4153
    self.needed_locks = {}
4154

    
4155
  def Exec(self, feedback_fn):
4156
    """Dump a representation of the cluster config to the standard output.
4157

4158
    """
4159
    values = []
4160
    for field in self.op.output_fields:
4161
      if field == "cluster_name":
4162
        entry = self.cfg.GetClusterName()
4163
      elif field == "master_node":
4164
        entry = self.cfg.GetMasterNode()
4165
      elif field == "drain_flag":
4166
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4167
      elif field == "watcher_pause":
4168
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4169
      else:
4170
        raise errors.ParameterError(field)
4171
      values.append(entry)
4172
    return values
4173

    
4174

    
4175
class LUActivateInstanceDisks(NoHooksLU):
4176
  """Bring up an instance's disks.
4177

4178
  """
4179
  _OP_PARAMS = [
4180
    _PInstanceName,
4181
    ("ignore_size", False, _TBool),
4182
    ]
4183
  REQ_BGL = False
4184

    
4185
  def ExpandNames(self):
4186
    self._ExpandAndLockInstance()
4187
    self.needed_locks[locking.LEVEL_NODE] = []
4188
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4189

    
4190
  def DeclareLocks(self, level):
4191
    if level == locking.LEVEL_NODE:
4192
      self._LockInstancesNodes()
4193

    
4194
  def CheckPrereq(self):
4195
    """Check prerequisites.
4196

4197
    This checks that the instance is in the cluster.
4198

4199
    """
4200
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4201
    assert self.instance is not None, \
4202
      "Cannot retrieve locked instance %s" % self.op.instance_name
4203
    _CheckNodeOnline(self, self.instance.primary_node)
4204

    
4205
  def Exec(self, feedback_fn):
4206
    """Activate the disks.
4207

4208
    """
4209
    disks_ok, disks_info = \
4210
              _AssembleInstanceDisks(self, self.instance,
4211
                                     ignore_size=self.op.ignore_size)
4212
    if not disks_ok:
4213
      raise errors.OpExecError("Cannot activate block devices")
4214

    
4215
    return disks_info
4216

    
4217

    
4218
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4219
                           ignore_size=False):
4220
  """Prepare the block devices for an instance.
4221

4222
  This sets up the block devices on all nodes.
4223

4224
  @type lu: L{LogicalUnit}
4225
  @param lu: the logical unit on whose behalf we execute
4226
  @type instance: L{objects.Instance}
4227
  @param instance: the instance for whose disks we assemble
4228
  @type disks: list of L{objects.Disk} or None
4229
  @param disks: which disks to assemble (or all, if None)
4230
  @type ignore_secondaries: boolean
4231
  @param ignore_secondaries: if true, errors on secondary nodes
4232
      won't result in an error return from the function
4233
  @type ignore_size: boolean
4234
  @param ignore_size: if true, the current known size of the disk
4235
      will not be used during the disk activation, useful for cases
4236
      when the size is wrong
4237
  @return: False if the operation failed, otherwise a list of
4238
      (host, instance_visible_name, node_visible_name)
4239
      with the mapping from node devices to instance devices
4240

4241
  """
4242
  device_info = []
4243
  disks_ok = True
4244
  iname = instance.name
4245
  disks = _ExpandCheckDisks(instance, disks)
4246

    
4247
  # With the two passes mechanism we try to reduce the window of
4248
  # opportunity for the race condition of switching DRBD to primary
4249
  # before handshaking occured, but we do not eliminate it
4250

    
4251
  # The proper fix would be to wait (with some limits) until the
4252
  # connection has been made and drbd transitions from WFConnection
4253
  # into any other network-connected state (Connected, SyncTarget,
4254
  # SyncSource, etc.)
4255

    
4256
  # 1st pass, assemble on all nodes in secondary mode
4257
  for inst_disk in disks:
4258
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4259
      if ignore_size:
4260
        node_disk = node_disk.Copy()
4261
        node_disk.UnsetSize()
4262
      lu.cfg.SetDiskID(node_disk, node)
4263
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4264
      msg = result.fail_msg
4265
      if msg:
4266
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4267
                           " (is_primary=False, pass=1): %s",
4268
                           inst_disk.iv_name, node, msg)
4269
        if not ignore_secondaries:
4270
          disks_ok = False
4271

    
4272
  # FIXME: race condition on drbd migration to primary
4273

    
4274
  # 2nd pass, do only the primary node
4275
  for inst_disk in disks:
4276
    dev_path = None
4277

    
4278
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4279
      if node != instance.primary_node:
4280
        continue
4281
      if ignore_size:
4282
        node_disk = node_disk.Copy()
4283
        node_disk.UnsetSize()
4284
      lu.cfg.SetDiskID(node_disk, node)
4285
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4286
      msg = result.fail_msg
4287
      if msg:
4288
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4289
                           " (is_primary=True, pass=2): %s",
4290
                           inst_disk.iv_name, node, msg)
4291
        disks_ok = False
4292
      else:
4293
        dev_path = result.payload
4294

    
4295
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4296

    
4297
  # leave the disks configured for the primary node
4298
  # this is a workaround that would be fixed better by
4299
  # improving the logical/physical id handling
4300
  for disk in disks:
4301
    lu.cfg.SetDiskID(disk, instance.primary_node)
4302

    
4303
  return disks_ok, device_info
4304

    
4305

    
4306
def _StartInstanceDisks(lu, instance, force):
4307
  """Start the disks of an instance.
4308

4309
  """
4310
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4311
                                           ignore_secondaries=force)
4312
  if not disks_ok:
4313
    _ShutdownInstanceDisks(lu, instance)
4314
    if force is not None and not force:
4315
      lu.proc.LogWarning("", hint="If the message above refers to a"
4316
                         " secondary node,"
4317
                         " you can retry the operation using '--force'.")
4318
    raise errors.OpExecError("Disk consistency error")
4319

    
4320

    
4321
class LUDeactivateInstanceDisks(NoHooksLU):
4322
  """Shutdown an instance's disks.
4323

4324
  """
4325
  _OP_PARAMS = [
4326
    _PInstanceName,
4327
    ]
4328
  REQ_BGL = False
4329

    
4330
  def ExpandNames(self):
4331
    self._ExpandAndLockInstance()
4332
    self.needed_locks[locking.LEVEL_NODE] = []
4333
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4334

    
4335
  def DeclareLocks(self, level):
4336
    if level == locking.LEVEL_NODE:
4337
      self._LockInstancesNodes()
4338

    
4339
  def CheckPrereq(self):
4340
    """Check prerequisites.
4341

4342
    This checks that the instance is in the cluster.
4343

4344
    """
4345
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4346
    assert self.instance is not None, \
4347
      "Cannot retrieve locked instance %s" % self.op.instance_name
4348

    
4349
  def Exec(self, feedback_fn):
4350
    """Deactivate the disks
4351

4352
    """
4353
    instance = self.instance
4354
    _SafeShutdownInstanceDisks(self, instance)
4355

    
4356

    
4357
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4358
  """Shutdown block devices of an instance.
4359

4360
  This function checks if an instance is running, before calling
4361
  _ShutdownInstanceDisks.
4362

4363
  """
4364
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4365
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4366

    
4367

    
4368
def _ExpandCheckDisks(instance, disks):
4369
  """Return the instance disks selected by the disks list
4370

4371
  @type disks: list of L{objects.Disk} or None
4372
  @param disks: selected disks
4373
  @rtype: list of L{objects.Disk}
4374
  @return: selected instance disks to act on
4375

4376
  """
4377
  if disks is None:
4378
    return instance.disks
4379
  else:
4380
    if not set(disks).issubset(instance.disks):
4381
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4382
                                   " target instance")
4383
    return disks
4384

    
4385

    
4386
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4387
  """Shutdown block devices of an instance.
4388

4389
  This does the shutdown on all nodes of the instance.
4390

4391
  If the ignore_primary is false, errors on the primary node are
4392
  ignored.
4393

4394
  """
4395
  all_result = True
4396
  disks = _ExpandCheckDisks(instance, disks)
4397

    
4398
  for disk in disks:
4399
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4400
      lu.cfg.SetDiskID(top_disk, node)
4401
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4402
      msg = result.fail_msg
4403
      if msg:
4404
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4405
                      disk.iv_name, node, msg)
4406
        if not ignore_primary or node != instance.primary_node:
4407
          all_result = False
4408
  return all_result
4409

    
4410

    
4411
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4412
  """Checks if a node has enough free memory.
4413

4414
  This function check if a given node has the needed amount of free
4415
  memory. In case the node has less memory or we cannot get the
4416
  information from the node, this function raise an OpPrereqError
4417
  exception.
4418

4419
  @type lu: C{LogicalUnit}
4420
  @param lu: a logical unit from which we get configuration data
4421
  @type node: C{str}
4422
  @param node: the node to check
4423
  @type reason: C{str}
4424
  @param reason: string to use in the error message
4425
  @type requested: C{int}
4426
  @param requested: the amount of memory in MiB to check for
4427
  @type hypervisor_name: C{str}
4428
  @param hypervisor_name: the hypervisor to ask for memory stats
4429
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4430
      we cannot check the node
4431

4432
  """
4433
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4434
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4435
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4436
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4437
  if not isinstance(free_mem, int):
4438
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4439
                               " was '%s'" % (node, free_mem),
4440
                               errors.ECODE_ENVIRON)
4441
  if requested > free_mem:
4442
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4443
                               " needed %s MiB, available %s MiB" %
4444
                               (node, reason, requested, free_mem),
4445
                               errors.ECODE_NORES)
4446

    
4447

    
4448
def _CheckNodesFreeDisk(lu, nodenames, requested):
4449
  """Checks if nodes have enough free disk space in the default VG.
4450

4451
  This function check if all given nodes have the needed amount of
4452
  free disk. In case any node has less disk or we cannot get the
4453
  information from the node, this function raise an OpPrereqError
4454
  exception.
4455

4456
  @type lu: C{LogicalUnit}
4457
  @param lu: a logical unit from which we get configuration data
4458
  @type nodenames: C{list}
4459
  @param nodenames: the list of node names to check
4460
  @type requested: C{int}
4461
  @param requested: the amount of disk in MiB to check for
4462
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4463
      we cannot check the node
4464

4465
  """
4466
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4467
                                   lu.cfg.GetHypervisorType())
4468
  for node in nodenames:
4469
    info = nodeinfo[node]
4470
    info.Raise("Cannot get current information from node %s" % node,
4471
               prereq=True, ecode=errors.ECODE_ENVIRON)
4472
    vg_free = info.payload.get("vg_free", None)
4473
    if not isinstance(vg_free, int):
4474
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4475
                                 " result was '%s'" % (node, vg_free),
4476
                                 errors.ECODE_ENVIRON)
4477
    if requested > vg_free:
4478
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4479
                                 " required %d MiB, available %d MiB" %
4480
                                 (node, requested, vg_free),
4481
                                 errors.ECODE_NORES)
4482

    
4483

    
4484
class LUStartupInstance(LogicalUnit):
4485
  """Starts an instance.
4486

4487
  """
4488
  HPATH = "instance-start"
4489
  HTYPE = constants.HTYPE_INSTANCE
4490
  _OP_PARAMS = [
4491
    _PInstanceName,
4492
    _PForce,
4493
    ("hvparams", _EmptyDict, _TDict),
4494
    ("beparams", _EmptyDict, _TDict),
4495
    ]
4496
  REQ_BGL = False
4497

    
4498
  def CheckArguments(self):
4499
    # extra beparams
4500
    if self.op.beparams:
4501
      # fill the beparams dict
4502
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4503

    
4504
  def ExpandNames(self):
4505
    self._ExpandAndLockInstance()
4506

    
4507
  def BuildHooksEnv(self):
4508
    """Build hooks env.
4509

4510
    This runs on master, primary and secondary nodes of the instance.
4511

4512
    """
4513
    env = {
4514
      "FORCE": self.op.force,
4515
      }
4516
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4517
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4518
    return env, nl, nl
4519

    
4520
  def CheckPrereq(self):
4521
    """Check prerequisites.
4522

4523
    This checks that the instance is in the cluster.
4524

4525
    """
4526
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4527
    assert self.instance is not None, \
4528
      "Cannot retrieve locked instance %s" % self.op.instance_name
4529

    
4530
    # extra hvparams
4531
    if self.op.hvparams:
4532
      # check hypervisor parameter syntax (locally)
4533
      cluster = self.cfg.GetClusterInfo()
4534
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4535
      filled_hvp = cluster.FillHV(instance)
4536
      filled_hvp.update(self.op.hvparams)
4537
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4538
      hv_type.CheckParameterSyntax(filled_hvp)
4539
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4540

    
4541
    _CheckNodeOnline(self, instance.primary_node)
4542

    
4543
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4544
    # check bridges existence
4545
    _CheckInstanceBridgesExist(self, instance)
4546

    
4547
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4548
                                              instance.name,
4549
                                              instance.hypervisor)
4550
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4551
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4552
    if not remote_info.payload: # not running already
4553
      _CheckNodeFreeMemory(self, instance.primary_node,
4554
                           "starting instance %s" % instance.name,
4555
                           bep[constants.BE_MEMORY], instance.hypervisor)
4556

    
4557
  def Exec(self, feedback_fn):
4558
    """Start the instance.
4559

4560
    """
4561
    instance = self.instance
4562
    force = self.op.force
4563

    
4564
    self.cfg.MarkInstanceUp(instance.name)
4565

    
4566
    node_current = instance.primary_node
4567

    
4568
    _StartInstanceDisks(self, instance, force)
4569

    
4570
    result = self.rpc.call_instance_start(node_current, instance,
4571
                                          self.op.hvparams, self.op.beparams)
4572
    msg = result.fail_msg
4573
    if msg:
4574
      _ShutdownInstanceDisks(self, instance)
4575
      raise errors.OpExecError("Could not start instance: %s" % msg)
4576

    
4577

    
4578
class LURebootInstance(LogicalUnit):
4579
  """Reboot an instance.
4580

4581
  """
4582
  HPATH = "instance-reboot"
4583
  HTYPE = constants.HTYPE_INSTANCE
4584
  _OP_PARAMS = [
4585
    _PInstanceName,
4586
    ("ignore_secondaries", False, _TBool),
4587
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4588
    _PShutdownTimeout,
4589
    ]
4590
  REQ_BGL = False
4591

    
4592
  def ExpandNames(self):
4593
    self._ExpandAndLockInstance()
4594

    
4595
  def BuildHooksEnv(self):
4596
    """Build hooks env.
4597

4598
    This runs on master, primary and secondary nodes of the instance.
4599

4600
    """
4601
    env = {
4602
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4603
      "REBOOT_TYPE": self.op.reboot_type,
4604
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4605
      }
4606
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4607
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4608
    return env, nl, nl
4609

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

4613
    This checks that the instance is in the cluster.
4614

4615
    """
4616
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4617
    assert self.instance is not None, \
4618
      "Cannot retrieve locked instance %s" % self.op.instance_name
4619

    
4620
    _CheckNodeOnline(self, instance.primary_node)
4621

    
4622
    # check bridges existence
4623
    _CheckInstanceBridgesExist(self, instance)
4624

    
4625
  def Exec(self, feedback_fn):
4626
    """Reboot the instance.
4627

4628
    """
4629
    instance = self.instance
4630
    ignore_secondaries = self.op.ignore_secondaries
4631
    reboot_type = self.op.reboot_type
4632

    
4633
    node_current = instance.primary_node
4634

    
4635
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4636
                       constants.INSTANCE_REBOOT_HARD]:
4637
      for disk in instance.disks:
4638
        self.cfg.SetDiskID(disk, node_current)
4639
      result = self.rpc.call_instance_reboot(node_current, instance,
4640
                                             reboot_type,
4641
                                             self.op.shutdown_timeout)
4642
      result.Raise("Could not reboot instance")
4643
    else:
4644
      result = self.rpc.call_instance_shutdown(node_current, instance,
4645
                                               self.op.shutdown_timeout)
4646
      result.Raise("Could not shutdown instance for full reboot")
4647
      _ShutdownInstanceDisks(self, instance)
4648
      _StartInstanceDisks(self, instance, ignore_secondaries)
4649
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4650
      msg = result.fail_msg
4651
      if msg:
4652
        _ShutdownInstanceDisks(self, instance)
4653
        raise errors.OpExecError("Could not start instance for"
4654
                                 " full reboot: %s" % msg)
4655

    
4656
    self.cfg.MarkInstanceUp(instance.name)
4657

    
4658

    
4659
class LUShutdownInstance(LogicalUnit):
4660
  """Shutdown an instance.
4661

4662
  """
4663
  HPATH = "instance-stop"
4664
  HTYPE = constants.HTYPE_INSTANCE
4665
  _OP_PARAMS = [
4666
    _PInstanceName,
4667
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4668
    ]
4669
  REQ_BGL = False
4670

    
4671
  def ExpandNames(self):
4672
    self._ExpandAndLockInstance()
4673

    
4674
  def BuildHooksEnv(self):
4675
    """Build hooks env.
4676

4677
    This runs on master, primary and secondary nodes of the instance.
4678

4679
    """
4680
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4681
    env["TIMEOUT"] = self.op.timeout
4682
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4683
    return env, nl, nl
4684

    
4685
  def CheckPrereq(self):
4686
    """Check prerequisites.
4687

4688
    This checks that the instance is in the cluster.
4689

4690
    """
4691
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4692
    assert self.instance is not None, \
4693
      "Cannot retrieve locked instance %s" % self.op.instance_name
4694
    _CheckNodeOnline(self, self.instance.primary_node)
4695

    
4696
  def Exec(self, feedback_fn):
4697
    """Shutdown the instance.
4698

4699
    """
4700
    instance = self.instance
4701
    node_current = instance.primary_node
4702
    timeout = self.op.timeout
4703
    self.cfg.MarkInstanceDown(instance.name)
4704
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4705
    msg = result.fail_msg
4706
    if msg:
4707
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4708

    
4709
    _ShutdownInstanceDisks(self, instance)
4710

    
4711

    
4712
class LUReinstallInstance(LogicalUnit):
4713
  """Reinstall an instance.
4714

4715
  """
4716
  HPATH = "instance-reinstall"
4717
  HTYPE = constants.HTYPE_INSTANCE
4718
  _OP_PARAMS = [
4719
    _PInstanceName,
4720
    ("os_type", None, _TMaybeString),
4721
    ("force_variant", False, _TBool),
4722
    ]
4723
  REQ_BGL = False
4724

    
4725
  def ExpandNames(self):
4726
    self._ExpandAndLockInstance()
4727

    
4728
  def BuildHooksEnv(self):
4729
    """Build hooks env.
4730

4731
    This runs on master, primary and secondary nodes of the instance.
4732

4733
    """
4734
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4735
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4736
    return env, nl, nl
4737

    
4738
  def CheckPrereq(self):
4739
    """Check prerequisites.
4740

4741
    This checks that the instance is in the cluster and is not running.
4742

4743
    """
4744
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4745
    assert instance is not None, \
4746
      "Cannot retrieve locked instance %s" % self.op.instance_name
4747
    _CheckNodeOnline(self, instance.primary_node)
4748

    
4749
    if instance.disk_template == constants.DT_DISKLESS:
4750
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4751
                                 self.op.instance_name,
4752
                                 errors.ECODE_INVAL)
4753
    _CheckInstanceDown(self, instance, "cannot reinstall")
4754

    
4755
    if self.op.os_type is not None:
4756
      # OS verification
4757
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4758
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4759

    
4760
    self.instance = instance
4761

    
4762
  def Exec(self, feedback_fn):
4763
    """Reinstall the instance.
4764

4765
    """
4766
    inst = self.instance
4767

    
4768
    if self.op.os_type is not None:
4769
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4770
      inst.os = self.op.os_type
4771
      self.cfg.Update(inst, feedback_fn)
4772

    
4773
    _StartInstanceDisks(self, inst, None)
4774
    try:
4775
      feedback_fn("Running the instance OS create scripts...")
4776
      # FIXME: pass debug option from opcode to backend
4777
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4778
                                             self.op.debug_level)
4779
      result.Raise("Could not install OS for instance %s on node %s" %
4780
                   (inst.name, inst.primary_node))
4781
    finally:
4782
      _ShutdownInstanceDisks(self, inst)
4783

    
4784

    
4785
class LURecreateInstanceDisks(LogicalUnit):
4786
  """Recreate an instance's missing disks.
4787

4788
  """
4789
  HPATH = "instance-recreate-disks"
4790
  HTYPE = constants.HTYPE_INSTANCE
4791
  _OP_PARAMS = [
4792
    _PInstanceName,
4793
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4794
    ]
4795
  REQ_BGL = False
4796

    
4797
  def ExpandNames(self):
4798
    self._ExpandAndLockInstance()
4799

    
4800
  def BuildHooksEnv(self):
4801
    """Build hooks env.
4802

4803
    This runs on master, primary and secondary nodes of the instance.
4804

4805
    """
4806
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4807
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4808
    return env, nl, nl
4809

    
4810
  def CheckPrereq(self):
4811
    """Check prerequisites.
4812

4813
    This checks that the instance is in the cluster and is not running.
4814

4815
    """
4816
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4817
    assert instance is not None, \
4818
      "Cannot retrieve locked instance %s" % self.op.instance_name
4819
    _CheckNodeOnline(self, instance.primary_node)
4820

    
4821
    if instance.disk_template == constants.DT_DISKLESS:
4822
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4823
                                 self.op.instance_name, errors.ECODE_INVAL)
4824
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4825

    
4826
    if not self.op.disks:
4827
      self.op.disks = range(len(instance.disks))
4828
    else:
4829
      for idx in self.op.disks:
4830
        if idx >= len(instance.disks):
4831
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4832
                                     errors.ECODE_INVAL)
4833

    
4834
    self.instance = instance
4835

    
4836
  def Exec(self, feedback_fn):
4837
    """Recreate the disks.
4838

4839
    """
4840
    to_skip = []
4841
    for idx, _ in enumerate(self.instance.disks):
4842
      if idx not in self.op.disks: # disk idx has not been passed in
4843
        to_skip.append(idx)
4844
        continue
4845

    
4846
    _CreateDisks(self, self.instance, to_skip=to_skip)
4847

    
4848

    
4849
class LURenameInstance(LogicalUnit):
4850
  """Rename an instance.
4851

4852
  """
4853
  HPATH = "instance-rename"
4854
  HTYPE = constants.HTYPE_INSTANCE
4855
  _OP_PARAMS = [
4856
    _PInstanceName,
4857
    ("new_name", _NoDefault, _TNonEmptyString),
4858
    ("ignore_ip", False, _TBool),
4859
    ("check_name", True, _TBool),
4860
    ]
4861

    
4862
  def BuildHooksEnv(self):
4863
    """Build hooks env.
4864

4865
    This runs on master, primary and secondary nodes of the instance.
4866

4867
    """
4868
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4869
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4870
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4871
    return env, nl, nl
4872

    
4873
  def CheckPrereq(self):
4874
    """Check prerequisites.
4875

4876
    This checks that the instance is in the cluster and is not running.
4877

4878
    """
4879
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4880
                                                self.op.instance_name)
4881
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4882
    assert instance is not None
4883
    _CheckNodeOnline(self, instance.primary_node)
4884
    _CheckInstanceDown(self, instance, "cannot rename")
4885
    self.instance = instance
4886

    
4887
    # new name verification
4888
    if self.op.check_name:
4889
      name_info = netutils.GetHostInfo(self.op.new_name)
4890
      self.op.new_name = name_info.name
4891

    
4892
    new_name = self.op.new_name
4893

    
4894
    instance_list = self.cfg.GetInstanceList()
4895
    if new_name in instance_list:
4896
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4897
                                 new_name, errors.ECODE_EXISTS)
4898

    
4899
    if not self.op.ignore_ip:
4900
      if netutils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4901
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4902
                                   (name_info.ip, new_name),
4903
                                   errors.ECODE_NOTUNIQUE)
4904

    
4905
  def Exec(self, feedback_fn):
4906
    """Reinstall the instance.
4907

4908
    """
4909
    inst = self.instance
4910
    old_name = inst.name
4911

    
4912
    if inst.disk_template == constants.DT_FILE:
4913
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4914

    
4915
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4916
    # Change the instance lock. This is definitely safe while we hold the BGL
4917
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4918
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4919

    
4920
    # re-read the instance from the configuration after rename
4921
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4922

    
4923
    if inst.disk_template == constants.DT_FILE:
4924
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4925
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4926
                                                     old_file_storage_dir,
4927
                                                     new_file_storage_dir)
4928
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4929
                   " (but the instance has been renamed in Ganeti)" %
4930
                   (inst.primary_node, old_file_storage_dir,
4931
                    new_file_storage_dir))
4932

    
4933
    _StartInstanceDisks(self, inst, None)
4934
    try:
4935
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4936
                                                 old_name, self.op.debug_level)
4937
      msg = result.fail_msg
4938
      if msg:
4939
        msg = ("Could not run OS rename script for instance %s on node %s"
4940
               " (but the instance has been renamed in Ganeti): %s" %
4941
               (inst.name, inst.primary_node, msg))
4942
        self.proc.LogWarning(msg)
4943
    finally:
4944
      _ShutdownInstanceDisks(self, inst)
4945

    
4946

    
4947
class LURemoveInstance(LogicalUnit):
4948
  """Remove an instance.
4949

4950
  """
4951
  HPATH = "instance-remove"
4952
  HTYPE = constants.HTYPE_INSTANCE
4953
  _OP_PARAMS = [
4954
    _PInstanceName,
4955
    ("ignore_failures", False, _TBool),
4956
    _PShutdownTimeout,
4957
    ]
4958
  REQ_BGL = False
4959

    
4960
  def ExpandNames(self):
4961
    self._ExpandAndLockInstance()
4962
    self.needed_locks[locking.LEVEL_NODE] = []
4963
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4964

    
4965
  def DeclareLocks(self, level):
4966
    if level == locking.LEVEL_NODE:
4967
      self._LockInstancesNodes()
4968

    
4969
  def BuildHooksEnv(self):
4970
    """Build hooks env.
4971

4972
    This runs on master, primary and secondary nodes of the instance.
4973

4974
    """
4975
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4976
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4977
    nl = [self.cfg.GetMasterNode()]
4978
    nl_post = list(self.instance.all_nodes) + nl
4979
    return env, nl, nl_post
4980

    
4981
  def CheckPrereq(self):
4982
    """Check prerequisites.
4983

4984
    This checks that the instance is in the cluster.
4985

4986
    """
4987
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4988
    assert self.instance is not None, \
4989
      "Cannot retrieve locked instance %s" % self.op.instance_name
4990

    
4991
  def Exec(self, feedback_fn):
4992
    """Remove the instance.
4993

4994
    """
4995
    instance = self.instance
4996
    logging.info("Shutting down instance %s on node %s",
4997
                 instance.name, instance.primary_node)
4998

    
4999
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5000
                                             self.op.shutdown_timeout)
5001
    msg = result.fail_msg
5002
    if msg:
5003
      if self.op.ignore_failures:
5004
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5005
      else:
5006
        raise errors.OpExecError("Could not shutdown instance %s on"
5007
                                 " node %s: %s" %
5008
                                 (instance.name, instance.primary_node, msg))
5009

    
5010
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5011

    
5012

    
5013
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5014
  """Utility function to remove an instance.
5015

5016
  """
5017
  logging.info("Removing block devices for instance %s", instance.name)
5018

    
5019
  if not _RemoveDisks(lu, instance):
5020
    if not ignore_failures:
5021
      raise errors.OpExecError("Can't remove instance's disks")
5022
    feedback_fn("Warning: can't remove instance's disks")
5023

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

    
5026
  lu.cfg.RemoveInstance(instance.name)
5027

    
5028
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5029
    "Instance lock removal conflict"
5030

    
5031
  # Remove lock for the instance
5032
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5033

    
5034

    
5035
class LUQueryInstances(NoHooksLU):
5036
  """Logical unit for querying instances.
5037

5038
  """
5039
  # pylint: disable-msg=W0142
5040
  _OP_PARAMS = [
5041
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
5042
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
5043
    ("use_locking", False, _TBool),
5044
    ]
5045
  REQ_BGL = False
5046
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5047
                    "serial_no", "ctime", "mtime", "uuid"]
5048
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5049
                                    "admin_state",
5050
                                    "disk_template", "ip", "mac", "bridge",
5051
                                    "nic_mode", "nic_link",
5052
                                    "sda_size", "sdb_size", "vcpus", "tags",
5053
                                    "network_port", "beparams",
5054
                                    r"(disk)\.(size)/([0-9]+)",
5055
                                    r"(disk)\.(sizes)", "disk_usage",
5056
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5057
                                    r"(nic)\.(bridge)/([0-9]+)",
5058
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5059
                                    r"(disk|nic)\.(count)",
5060
                                    "hvparams",
5061
                                    ] + _SIMPLE_FIELDS +
5062
                                  ["hv/%s" % name
5063
                                   for name in constants.HVS_PARAMETERS
5064
                                   if name not in constants.HVC_GLOBALS] +
5065
                                  ["be/%s" % name
5066
                                   for name in constants.BES_PARAMETERS])
5067
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5068
                                   "oper_ram",
5069
                                   "oper_vcpus",
5070
                                   "status")
5071

    
5072

    
5073
  def CheckArguments(self):
5074
    _CheckOutputFields(static=self._FIELDS_STATIC,
5075
                       dynamic=self._FIELDS_DYNAMIC,
5076
                       selected=self.op.output_fields)
5077

    
5078
  def ExpandNames(self):
5079
    self.needed_locks = {}
5080
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5081
    self.share_locks[locking.LEVEL_NODE] = 1
5082

    
5083
    if self.op.names:
5084
      self.wanted = _GetWantedInstances(self, self.op.names)
5085
    else:
5086
      self.wanted = locking.ALL_SET
5087

    
5088
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5089
    self.do_locking = self.do_node_query and self.op.use_locking
5090
    if self.do_locking:
5091
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5092
      self.needed_locks[locking.LEVEL_NODE] = []
5093
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5094

    
5095
  def DeclareLocks(self, level):
5096
    if level == locking.LEVEL_NODE and self.do_locking:
5097
      self._LockInstancesNodes()
5098

    
5099
  def Exec(self, feedback_fn):
5100
    """Computes the list of nodes and their attributes.
5101

5102
    """
5103
    # pylint: disable-msg=R0912
5104
    # way too many branches here
5105
    all_info = self.cfg.GetAllInstancesInfo()
5106
    if self.wanted == locking.ALL_SET:
5107
      # caller didn't specify instance names, so ordering is not important
5108
      if self.do_locking:
5109
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5110
      else:
5111
        instance_names = all_info.keys()
5112
      instance_names = utils.NiceSort(instance_names)
5113
    else:
5114
      # caller did specify names, so we must keep the ordering
5115
      if self.do_locking:
5116
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5117
      else:
5118
        tgt_set = all_info.keys()
5119
      missing = set(self.wanted).difference(tgt_set)
5120
      if missing:
5121
        raise errors.OpExecError("Some instances were removed before"
5122
                                 " retrieving their data: %s" % missing)
5123
      instance_names = self.wanted
5124

    
5125
    instance_list = [all_info[iname] for iname in instance_names]
5126

    
5127
    # begin data gathering
5128

    
5129
    nodes = frozenset([inst.primary_node for inst in instance_list])
5130
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5131

    
5132
    bad_nodes = []
5133
    off_nodes = []
5134
    if self.do_node_query:
5135
      live_data = {}
5136
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5137
      for name in nodes:
5138
        result = node_data[name]
5139
        if result.offline:
5140
          # offline nodes will be in both lists
5141
          off_nodes.append(name)
5142
        if result.fail_msg:
5143
          bad_nodes.append(name)
5144
        else:
5145
          if result.payload:
5146
            live_data.update(result.payload)
5147
          # else no instance is alive
5148
    else:
5149
      live_data = dict([(name, {}) for name in instance_names])
5150

    
5151
    # end data gathering
5152

    
5153
    HVPREFIX = "hv/"
5154
    BEPREFIX = "be/"
5155
    output = []
5156
    cluster = self.cfg.GetClusterInfo()
5157
    for instance in instance_list:
5158
      iout = []
5159
      i_hv = cluster.FillHV(instance, skip_globals=True)
5160
      i_be = cluster.FillBE(instance)
5161
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5162
      for field in self.op.output_fields:
5163
        st_match = self._FIELDS_STATIC.Matches(field)
5164
        if field in self._SIMPLE_FIELDS:
5165
          val = getattr(instance, field)
5166
        elif field == "pnode":
5167
          val = instance.primary_node
5168
        elif field == "snodes":
5169
          val = list(instance.secondary_nodes)
5170
        elif field == "admin_state":
5171
          val = instance.admin_up
5172
        elif field == "oper_state":
5173
          if instance.primary_node in bad_nodes:
5174
            val = None
5175
          else:
5176
            val = bool(live_data.get(instance.name))
5177
        elif field == "status":
5178
          if instance.primary_node in off_nodes:
5179
            val = "ERROR_nodeoffline"
5180
          elif instance.primary_node in bad_nodes:
5181
            val = "ERROR_nodedown"
5182
          else:
5183
            running = bool(live_data.get(instance.name))
5184
            if running:
5185
              if instance.admin_up:
5186
                val = "running"
5187
              else:
5188
                val = "ERROR_up"
5189
            else:
5190
              if instance.admin_up:
5191
                val = "ERROR_down"
5192
              else:
5193
                val = "ADMIN_down"
5194
        elif field == "oper_ram":
5195
          if instance.primary_node in bad_nodes:
5196
            val = None
5197
          elif instance.name in live_data:
5198
            val = live_data[instance.name].get("memory", "?")
5199
          else:
5200
            val = "-"
5201
        elif field == "oper_vcpus":
5202
          if instance.primary_node in bad_nodes:
5203
            val = None
5204
          elif instance.name in live_data:
5205
            val = live_data[instance.name].get("vcpus", "?")
5206
          else:
5207
            val = "-"
5208
        elif field == "vcpus":
5209
          val = i_be[constants.BE_VCPUS]
5210
        elif field == "disk_template":
5211
          val = instance.disk_template
5212
        elif field == "ip":
5213
          if instance.nics:
5214
            val = instance.nics[0].ip
5215
          else:
5216
            val = None
5217
        elif field == "nic_mode":
5218
          if instance.nics:
5219
            val = i_nicp[0][constants.NIC_MODE]
5220
          else:
5221
            val = None
5222
        elif field == "nic_link":
5223
          if instance.nics:
5224
            val = i_nicp[0][constants.NIC_LINK]
5225
          else:
5226
            val = None
5227
        elif field == "bridge":
5228
          if (instance.nics and
5229
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5230
            val = i_nicp[0][constants.NIC_LINK]
5231
          else:
5232
            val = None
5233
        elif field == "mac":
5234
          if instance.nics:
5235
            val = instance.nics[0].mac
5236
          else:
5237
            val = None
5238
        elif field == "sda_size" or field == "sdb_size":
5239
          idx = ord(field[2]) - ord('a')
5240
          try:
5241
            val = instance.FindDisk(idx).size
5242
          except errors.OpPrereqError:
5243
            val = None
5244
        elif field == "disk_usage": # total disk usage per node
5245
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5246
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5247
        elif field == "tags":
5248
          val = list(instance.GetTags())
5249
        elif field == "hvparams":
5250
          val = i_hv
5251
        elif (field.startswith(HVPREFIX) and
5252
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5253
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5254
          val = i_hv.get(field[len(HVPREFIX):], None)
5255
        elif field == "beparams":
5256
          val = i_be
5257
        elif (field.startswith(BEPREFIX) and
5258
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5259
          val = i_be.get(field[len(BEPREFIX):], None)
5260
        elif st_match and st_match.groups():
5261
          # matches a variable list
5262
          st_groups = st_match.groups()
5263
          if st_groups and st_groups[0] == "disk":
5264
            if st_groups[1] == "count":
5265
              val = len(instance.disks)
5266
            elif st_groups[1] == "sizes":
5267
              val = [disk.size for disk in instance.disks]
5268
            elif st_groups[1] == "size":
5269
              try:
5270
                val = instance.FindDisk(st_groups[2]).size
5271
              except errors.OpPrereqError:
5272
                val = None
5273
            else:
5274
              assert False, "Unhandled disk parameter"
5275
          elif st_groups[0] == "nic":
5276
            if st_groups[1] == "count":
5277
              val = len(instance.nics)
5278
            elif st_groups[1] == "macs":
5279
              val = [nic.mac for nic in instance.nics]
5280
            elif st_groups[1] == "ips":
5281
              val = [nic.ip for nic in instance.nics]
5282
            elif st_groups[1] == "modes":
5283
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5284
            elif st_groups[1] == "links":
5285
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5286
            elif st_groups[1] == "bridges":
5287
              val = []
5288
              for nicp in i_nicp:
5289
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5290
                  val.append(nicp[constants.NIC_LINK])
5291
                else:
5292
                  val.append(None)
5293
            else:
5294
              # index-based item
5295
              nic_idx = int(st_groups[2])
5296
              if nic_idx >= len(instance.nics):
5297
                val = None
5298
              else:
5299
                if st_groups[1] == "mac":
5300
                  val = instance.nics[nic_idx].mac
5301
                elif st_groups[1] == "ip":
5302
                  val = instance.nics[nic_idx].ip
5303
                elif st_groups[1] == "mode":
5304
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5305
                elif st_groups[1] == "link":
5306
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5307
                elif st_groups[1] == "bridge":
5308
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5309
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5310
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5311
                  else:
5312
                    val = None
5313
                else:
5314
                  assert False, "Unhandled NIC parameter"
5315
          else:
5316
            assert False, ("Declared but unhandled variable parameter '%s'" %
5317
                           field)
5318
        else:
5319
          assert False, "Declared but unhandled parameter '%s'" % field
5320
        iout.append(val)
5321
      output.append(iout)
5322

    
5323
    return output
5324

    
5325

    
5326
class LUFailoverInstance(LogicalUnit):
5327
  """Failover an instance.
5328

5329
  """
5330
  HPATH = "instance-failover"
5331
  HTYPE = constants.HTYPE_INSTANCE
5332
  _OP_PARAMS = [
5333
    _PInstanceName,
5334
    ("ignore_consistency", False, _TBool),
5335
    _PShutdownTimeout,
5336
    ]
5337
  REQ_BGL = False
5338

    
5339
  def ExpandNames(self):
5340
    self._ExpandAndLockInstance()
5341
    self.needed_locks[locking.LEVEL_NODE] = []
5342
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5343

    
5344
  def DeclareLocks(self, level):
5345
    if level == locking.LEVEL_NODE:
5346
      self._LockInstancesNodes()
5347

    
5348
  def BuildHooksEnv(self):
5349
    """Build hooks env.
5350

5351
    This runs on master, primary and secondary nodes of the instance.
5352

5353
    """
5354
    instance = self.instance
5355
    source_node = instance.primary_node
5356
    target_node = instance.secondary_nodes[0]
5357
    env = {
5358
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5359
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5360
      "OLD_PRIMARY": source_node,
5361
      "OLD_SECONDARY": target_node,
5362
      "NEW_PRIMARY": target_node,
5363
      "NEW_SECONDARY": source_node,
5364
      }
5365
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5366
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5367
    nl_post = list(nl)
5368
    nl_post.append(source_node)
5369
    return env, nl, nl_post
5370

    
5371
  def CheckPrereq(self):
5372
    """Check prerequisites.
5373

5374
    This checks that the instance is in the cluster.
5375

5376
    """
5377
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5378
    assert self.instance is not None, \
5379
      "Cannot retrieve locked instance %s" % self.op.instance_name
5380

    
5381
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5382
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5383
      raise errors.OpPrereqError("Instance's disk layout is not"
5384
                                 " network mirrored, cannot failover.",
5385
                                 errors.ECODE_STATE)
5386

    
5387
    secondary_nodes = instance.secondary_nodes
5388
    if not secondary_nodes:
5389
      raise errors.ProgrammerError("no secondary node but using "
5390
                                   "a mirrored disk template")
5391

    
5392
    target_node = secondary_nodes[0]
5393
    _CheckNodeOnline(self, target_node)
5394
    _CheckNodeNotDrained(self, target_node)
5395
    if instance.admin_up:
5396
      # check memory requirements on the secondary node
5397
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5398
                           instance.name, bep[constants.BE_MEMORY],
5399
                           instance.hypervisor)
5400
    else:
5401
      self.LogInfo("Not checking memory on the secondary node as"
5402
                   " instance will not be started")
5403

    
5404
    # check bridge existance
5405
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5406

    
5407
  def Exec(self, feedback_fn):
5408
    """Failover an instance.
5409

5410
    The failover is done by shutting it down on its present node and
5411
    starting it on the secondary.
5412

5413
    """
5414
    instance = self.instance
5415

    
5416
    source_node = instance.primary_node
5417
    target_node = instance.secondary_nodes[0]
5418

    
5419
    if instance.admin_up:
5420
      feedback_fn("* checking disk consistency between source and target")
5421
      for dev in instance.disks:
5422
        # for drbd, these are drbd over lvm
5423
        if not _CheckDiskConsistency(self, dev, target_node, False):
5424
          if not self.op.ignore_consistency:
5425
            raise errors.OpExecError("Disk %s is degraded on target node,"
5426
                                     " aborting failover." % dev.iv_name)
5427
    else:
5428
      feedback_fn("* not checking disk consistency as instance is not running")
5429

    
5430
    feedback_fn("* shutting down instance on source node")
5431
    logging.info("Shutting down instance %s on node %s",
5432
                 instance.name, source_node)
5433

    
5434
    result = self.rpc.call_instance_shutdown(source_node, instance,
5435
                                             self.op.shutdown_timeout)
5436
    msg = result.fail_msg
5437
    if msg:
5438
      if self.op.ignore_consistency:
5439
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5440
                             " Proceeding anyway. Please make sure node"
5441
                             " %s is down. Error details: %s",
5442
                             instance.name, source_node, source_node, msg)
5443
      else:
5444
        raise errors.OpExecError("Could not shutdown instance %s on"
5445
                                 " node %s: %s" %
5446
                                 (instance.name, source_node, msg))
5447

    
5448
    feedback_fn("* deactivating the instance's disks on source node")
5449
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5450
      raise errors.OpExecError("Can't shut down the instance's disks.")
5451

    
5452
    instance.primary_node = target_node
5453
    # distribute new instance config to the other nodes
5454
    self.cfg.Update(instance, feedback_fn)
5455

    
5456
    # Only start the instance if it's marked as up
5457
    if instance.admin_up:
5458
      feedback_fn("* activating the instance's disks on target node")
5459
      logging.info("Starting instance %s on node %s",
5460
                   instance.name, target_node)
5461

    
5462
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5463
                                           ignore_secondaries=True)
5464
      if not disks_ok:
5465
        _ShutdownInstanceDisks(self, instance)
5466
        raise errors.OpExecError("Can't activate the instance's disks")
5467

    
5468
      feedback_fn("* starting the instance on the target node")
5469
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5470
      msg = result.fail_msg
5471
      if msg:
5472
        _ShutdownInstanceDisks(self, instance)
5473
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5474
                                 (instance.name, target_node, msg))
5475

    
5476

    
5477
class LUMigrateInstance(LogicalUnit):
5478
  """Migrate an instance.
5479

5480
  This is migration without shutting down, compared to the failover,
5481
  which is done with shutdown.
5482

5483
  """
5484
  HPATH = "instance-migrate"
5485
  HTYPE = constants.HTYPE_INSTANCE
5486
  _OP_PARAMS = [
5487
    _PInstanceName,
5488
    ("live", True, _TBool),
5489
    ("cleanup", False, _TBool),
5490
    ]
5491

    
5492
  REQ_BGL = False
5493

    
5494
  def ExpandNames(self):
5495
    self._ExpandAndLockInstance()
5496

    
5497
    self.needed_locks[locking.LEVEL_NODE] = []
5498
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5499

    
5500
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5501
                                       self.op.live, self.op.cleanup)
5502
    self.tasklets = [self._migrater]
5503

    
5504
  def DeclareLocks(self, level):
5505
    if level == locking.LEVEL_NODE:
5506
      self._LockInstancesNodes()
5507

    
5508
  def BuildHooksEnv(self):
5509
    """Build hooks env.
5510

5511
    This runs on master, primary and secondary nodes of the instance.
5512

5513
    """
5514
    instance = self._migrater.instance
5515
    source_node = instance.primary_node
5516
    target_node = instance.secondary_nodes[0]
5517
    env = _BuildInstanceHookEnvByObject(self, instance)
5518
    env["MIGRATE_LIVE"] = self.op.live
5519
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5520
    env.update({
5521
        "OLD_PRIMARY": source_node,
5522
        "OLD_SECONDARY": target_node,
5523
        "NEW_PRIMARY": target_node,
5524
        "NEW_SECONDARY": source_node,
5525
        })
5526
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5527
    nl_post = list(nl)
5528
    nl_post.append(source_node)
5529
    return env, nl, nl_post
5530

    
5531

    
5532
class LUMoveInstance(LogicalUnit):
5533
  """Move an instance by data-copying.
5534

5535
  """
5536
  HPATH = "instance-move"
5537
  HTYPE = constants.HTYPE_INSTANCE
5538
  _OP_PARAMS = [
5539
    _PInstanceName,
5540
    ("target_node", _NoDefault, _TNonEmptyString),
5541
    _PShutdownTimeout,
5542
    ]
5543
  REQ_BGL = False
5544

    
5545
  def ExpandNames(self):
5546
    self._ExpandAndLockInstance()
5547
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5548
    self.op.target_node = target_node
5549
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5550
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5551

    
5552
  def DeclareLocks(self, level):
5553
    if level == locking.LEVEL_NODE:
5554
      self._LockInstancesNodes(primary_only=True)
5555

    
5556
  def BuildHooksEnv(self):
5557
    """Build hooks env.
5558

5559
    This runs on master, primary and secondary nodes of the instance.
5560

5561
    """
5562
    env = {
5563
      "TARGET_NODE": self.op.target_node,
5564
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5565
      }
5566
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5567
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5568
                                       self.op.target_node]
5569
    return env, nl, nl
5570

    
5571
  def CheckPrereq(self):
5572
    """Check prerequisites.
5573

5574
    This checks that the instance is in the cluster.
5575

5576
    """
5577
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5578
    assert self.instance is not None, \
5579
      "Cannot retrieve locked instance %s" % self.op.instance_name
5580

    
5581
    node = self.cfg.GetNodeInfo(self.op.target_node)
5582
    assert node is not None, \
5583
      "Cannot retrieve locked node %s" % self.op.target_node
5584

    
5585
    self.target_node = target_node = node.name
5586

    
5587
    if target_node == instance.primary_node:
5588
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5589
                                 (instance.name, target_node),
5590
                                 errors.ECODE_STATE)
5591

    
5592
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5593

    
5594
    for idx, dsk in enumerate(instance.disks):
5595
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5596
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5597
                                   " cannot copy" % idx, errors.ECODE_STATE)
5598

    
5599
    _CheckNodeOnline(self, target_node)
5600
    _CheckNodeNotDrained(self, target_node)
5601

    
5602
    if instance.admin_up:
5603
      # check memory requirements on the secondary node
5604
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5605
                           instance.name, bep[constants.BE_MEMORY],
5606
                           instance.hypervisor)
5607
    else:
5608
      self.LogInfo("Not checking memory on the secondary node as"
5609
                   " instance will not be started")
5610

    
5611
    # check bridge existance
5612
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5613

    
5614
  def Exec(self, feedback_fn):
5615
    """Move an instance.
5616

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

5620
    """
5621
    instance = self.instance
5622

    
5623
    source_node = instance.primary_node
5624
    target_node = self.target_node
5625

    
5626
    self.LogInfo("Shutting down instance %s on source node %s",
5627
                 instance.name, source_node)
5628

    
5629
    result = self.rpc.call_instance_shutdown(source_node, instance,
5630
                                             self.op.shutdown_timeout)
5631
    msg = result.fail_msg
5632
    if msg:
5633
      if self.op.ignore_consistency:
5634
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5635
                             " Proceeding anyway. Please make sure node"
5636
                             " %s is down. Error details: %s",
5637
                             instance.name, source_node, source_node, msg)
5638
      else:
5639
        raise errors.OpExecError("Could not shutdown instance %s on"
5640
                                 " node %s: %s" %
5641
                                 (instance.name, source_node, msg))
5642

    
5643
    # create the target disks
5644
    try:
5645
      _CreateDisks(self, instance, target_node=target_node)
5646
    except errors.OpExecError:
5647
      self.LogWarning("Device creation failed, reverting...")
5648
      try:
5649
        _RemoveDisks(self, instance, target_node=target_node)
5650
      finally:
5651
        self.cfg.ReleaseDRBDMinors(instance.name)
5652
        raise
5653

    
5654
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5655

    
5656
    errs = []
5657
    # activate, get path, copy the data over
5658
    for idx, disk in enumerate(instance.disks):
5659
      self.LogInfo("Copying data for disk %d", idx)
5660
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5661
                                               instance.name, True)
5662
      if result.fail_msg:
5663
        self.LogWarning("Can't assemble newly created disk %d: %s",
5664
                        idx, result.fail_msg)
5665
        errs.append(result.fail_msg)
5666
        break
5667
      dev_path = result.payload
5668
      result = self.rpc.call_blockdev_export(source_node, disk,
5669
                                             target_node, dev_path,
5670
                                             cluster_name)
5671
      if result.fail_msg:
5672
        self.LogWarning("Can't copy data over for disk %d: %s",
5673
                        idx, result.fail_msg)
5674
        errs.append(result.fail_msg)
5675
        break
5676

    
5677
    if errs:
5678
      self.LogWarning("Some disks failed to copy, aborting")
5679
      try:
5680
        _RemoveDisks(self, instance, target_node=target_node)
5681
      finally:
5682
        self.cfg.ReleaseDRBDMinors(instance.name)
5683
        raise errors.OpExecError("Errors during disk copy: %s" %
5684
                                 (",".join(errs),))
5685

    
5686
    instance.primary_node = target_node
5687
    self.cfg.Update(instance, feedback_fn)
5688

    
5689
    self.LogInfo("Removing the disks on the original node")
5690
    _RemoveDisks(self, instance, target_node=source_node)
5691

    
5692
    # Only start the instance if it's marked as up
5693
    if instance.admin_up:
5694
      self.LogInfo("Starting instance %s on node %s",
5695
                   instance.name, target_node)
5696

    
5697
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5698
                                           ignore_secondaries=True)
5699
      if not disks_ok:
5700
        _ShutdownInstanceDisks(self, instance)
5701
        raise errors.OpExecError("Can't activate the instance's disks")
5702

    
5703
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5704
      msg = result.fail_msg
5705
      if msg:
5706
        _ShutdownInstanceDisks(self, instance)
5707
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5708
                                 (instance.name, target_node, msg))
5709

    
5710

    
5711
class LUMigrateNode(LogicalUnit):
5712
  """Migrate all instances from a node.
5713

5714
  """
5715
  HPATH = "node-migrate"
5716
  HTYPE = constants.HTYPE_NODE
5717
  _OP_PARAMS = [
5718
    _PNodeName,
5719
    ("live", False, _TBool),
5720
    ]
5721
  REQ_BGL = False
5722

    
5723
  def ExpandNames(self):
5724
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5725

    
5726
    self.needed_locks = {
5727
      locking.LEVEL_NODE: [self.op.node_name],
5728
      }
5729

    
5730
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5731

    
5732
    # Create tasklets for migrating instances for all instances on this node
5733
    names = []
5734
    tasklets = []
5735

    
5736
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5737
      logging.debug("Migrating instance %s", inst.name)
5738
      names.append(inst.name)
5739

    
5740
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5741

    
5742
    self.tasklets = tasklets
5743

    
5744
    # Declare instance locks
5745
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5746

    
5747
  def DeclareLocks(self, level):
5748
    if level == locking.LEVEL_NODE:
5749
      self._LockInstancesNodes()
5750

    
5751
  def BuildHooksEnv(self):
5752
    """Build hooks env.
5753

5754
    This runs on the master, the primary and all the secondaries.
5755

5756
    """
5757
    env = {
5758
      "NODE_NAME": self.op.node_name,
5759
      }
5760

    
5761
    nl = [self.cfg.GetMasterNode()]
5762

    
5763
    return (env, nl, nl)
5764

    
5765

    
5766
class TLMigrateInstance(Tasklet):
5767
  def __init__(self, lu, instance_name, live, cleanup):
5768
    """Initializes this class.
5769

5770
    """
5771
    Tasklet.__init__(self, lu)
5772

    
5773
    # Parameters
5774
    self.instance_name = instance_name
5775
    self.live = live
5776
    self.cleanup = cleanup
5777

    
5778
  def CheckPrereq(self):
5779
    """Check prerequisites.
5780

5781
    This checks that the instance is in the cluster.
5782

5783
    """
5784
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5785
    instance = self.cfg.GetInstanceInfo(instance_name)
5786
    assert instance is not None
5787

    
5788
    if instance.disk_template != constants.DT_DRBD8:
5789
      raise errors.OpPrereqError("Instance's disk layout is not"
5790
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5791

    
5792
    secondary_nodes = instance.secondary_nodes
5793
    if not secondary_nodes:
5794
      raise errors.ConfigurationError("No secondary node but using"
5795
                                      " drbd8 disk template")
5796

    
5797
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5798

    
5799
    target_node = secondary_nodes[0]
5800
    # check memory requirements on the secondary node
5801
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5802
                         instance.name, i_be[constants.BE_MEMORY],
5803
                         instance.hypervisor)
5804

    
5805
    # check bridge existance
5806
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5807

    
5808
    if not self.cleanup:
5809
      _CheckNodeNotDrained(self.lu, target_node)
5810
      result = self.rpc.call_instance_migratable(instance.primary_node,
5811
                                                 instance)
5812
      result.Raise("Can't migrate, please use failover",
5813
                   prereq=True, ecode=errors.ECODE_STATE)
5814

    
5815
    self.instance = instance
5816

    
5817
  def _WaitUntilSync(self):
5818
    """Poll with custom rpc for disk sync.
5819

5820
    This uses our own step-based rpc call.
5821

5822
    """
5823
    self.feedback_fn("* wait until resync is done")
5824
    all_done = False
5825
    while not all_done:
5826
      all_done = True
5827
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5828
                                            self.nodes_ip,
5829
                                            self.instance.disks)
5830
      min_percent = 100
5831
      for node, nres in result.items():
5832
        nres.Raise("Cannot resync disks on node %s" % node)
5833
        node_done, node_percent = nres.payload
5834
        all_done = all_done and node_done
5835
        if node_percent is not None:
5836
          min_percent = min(min_percent, node_percent)
5837
      if not all_done:
5838
        if min_percent < 100:
5839
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5840
        time.sleep(2)
5841

    
5842
  def _EnsureSecondary(self, node):
5843
    """Demote a node to secondary.
5844

5845
    """
5846
    self.feedback_fn("* switching node %s to secondary mode" % node)
5847

    
5848
    for dev in self.instance.disks:
5849
      self.cfg.SetDiskID(dev, node)
5850

    
5851
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5852
                                          self.instance.disks)
5853
    result.Raise("Cannot change disk to secondary on node %s" % node)
5854

    
5855
  def _GoStandalone(self):
5856
    """Disconnect from the network.
5857

5858
    """
5859
    self.feedback_fn("* changing into standalone mode")
5860
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5861
                                               self.instance.disks)
5862
    for node, nres in result.items():
5863
      nres.Raise("Cannot disconnect disks node %s" % node)
5864

    
5865
  def _GoReconnect(self, multimaster):
5866
    """Reconnect to the network.
5867

5868
    """
5869
    if multimaster:
5870
      msg = "dual-master"
5871
    else:
5872
      msg = "single-master"
5873
    self.feedback_fn("* changing disks into %s mode" % msg)
5874
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5875
                                           self.instance.disks,
5876
                                           self.instance.name, multimaster)
5877
    for node, nres in result.items():
5878
      nres.Raise("Cannot change disks config on node %s" % node)
5879

    
5880
  def _ExecCleanup(self):
5881
    """Try to cleanup after a failed migration.
5882

5883
    The cleanup is done by:
5884
      - check that the instance is running only on one node
5885
        (and update the config if needed)
5886
      - change disks on its secondary node to secondary
5887
      - wait until disks are fully synchronized
5888
      - disconnect from the network
5889
      - change disks into single-master mode
5890
      - wait again until disks are fully synchronized
5891

5892
    """
5893
    instance = self.instance
5894
    target_node = self.target_node
5895
    source_node = self.source_node
5896

    
5897
    # check running on only one node
5898
    self.feedback_fn("* checking where the instance actually runs"
5899
                     " (if this hangs, the hypervisor might be in"
5900
                     " a bad state)")
5901
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5902
    for node, result in ins_l.items():
5903
      result.Raise("Can't contact node %s" % node)
5904

    
5905
    runningon_source = instance.name in ins_l[source_node].payload
5906
    runningon_target = instance.name in ins_l[target_node].payload
5907

    
5908
    if runningon_source and runningon_target:
5909
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5910
                               " or the hypervisor is confused. You will have"
5911
                               " to ensure manually that it runs only on one"
5912
                               " and restart this operation.")
5913

    
5914
    if not (runningon_source or runningon_target):
5915
      raise errors.OpExecError("Instance does not seem to be running at all."
5916
                               " In this case, it's safer to repair by"
5917
                               " running 'gnt-instance stop' to ensure disk"
5918
                               " shutdown, and then restarting it.")
5919

    
5920
    if runningon_target:
5921
      # the migration has actually succeeded, we need to update the config
5922
      self.feedback_fn("* instance running on secondary node (%s),"
5923
                       " updating config" % target_node)
5924
      instance.primary_node = target_node
5925
      self.cfg.Update(instance, self.feedback_fn)
5926
      demoted_node = source_node
5927
    else:
5928
      self.feedback_fn("* instance confirmed to be running on its"
5929
                       " primary node (%s)" % source_node)
5930
      demoted_node = target_node
5931

    
5932
    self._EnsureSecondary(demoted_node)
5933
    try:
5934
      self._WaitUntilSync()
5935
    except errors.OpExecError:
5936
      # we ignore here errors, since if the device is standalone, it
5937
      # won't be able to sync
5938
      pass
5939
    self._GoStandalone()
5940
    self._GoReconnect(False)
5941
    self._WaitUntilSync()
5942

    
5943
    self.feedback_fn("* done")
5944

    
5945
  def _RevertDiskStatus(self):
5946
    """Try to revert the disk status after a failed migration.
5947

5948
    """
5949
    target_node = self.target_node
5950
    try:
5951
      self._EnsureSecondary(target_node)
5952
      self._GoStandalone()
5953
      self._GoReconnect(False)
5954
      self._WaitUntilSync()
5955
    except errors.OpExecError, err:
5956
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5957
                         " drives: error '%s'\n"
5958
                         "Please look and recover the instance status" %
5959
                         str(err))
5960

    
5961
  def _AbortMigration(self):
5962
    """Call the hypervisor code to abort a started migration.
5963

5964
    """
5965
    instance = self.instance
5966
    target_node = self.target_node
5967
    migration_info = self.migration_info
5968

    
5969
    abort_result = self.rpc.call_finalize_migration(target_node,
5970
                                                    instance,
5971
                                                    migration_info,
5972
                                                    False)
5973
    abort_msg = abort_result.fail_msg
5974
    if abort_msg:
5975
      logging.error("Aborting migration failed on target node %s: %s",
5976
                    target_node, abort_msg)
5977
      # Don't raise an exception here, as we stil have to try to revert the
5978
      # disk status, even if this step failed.
5979

    
5980
  def _ExecMigration(self):
5981
    """Migrate an instance.
5982

5983
    The migrate is done by:
5984
      - change the disks into dual-master mode
5985
      - wait until disks are fully synchronized again
5986
      - migrate the instance
5987
      - change disks on the new secondary node (the old primary) to secondary
5988
      - wait until disks are fully synchronized
5989
      - change disks into single-master mode
5990

5991
    """
5992
    instance = self.instance
5993
    target_node = self.target_node
5994
    source_node = self.source_node
5995

    
5996
    self.feedback_fn("* checking disk consistency between source and target")
5997
    for dev in instance.disks:
5998
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5999
        raise errors.OpExecError("Disk %s is degraded or not fully"
6000
                                 " synchronized on target node,"
6001
                                 " aborting migrate." % dev.iv_name)
6002

    
6003
    # First get the migration information from the remote node
6004
    result = self.rpc.call_migration_info(source_node, instance)
6005
    msg = result.fail_msg
6006
    if msg:
6007
      log_err = ("Failed fetching source migration information from %s: %s" %
6008
                 (source_node, msg))
6009
      logging.error(log_err)
6010
      raise errors.OpExecError(log_err)
6011

    
6012
    self.migration_info = migration_info = result.payload
6013

    
6014
    # Then switch the disks to master/master mode
6015
    self._EnsureSecondary(target_node)
6016
    self._GoStandalone()
6017
    self._GoReconnect(True)
6018
    self._WaitUntilSync()
6019

    
6020
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6021
    result = self.rpc.call_accept_instance(target_node,
6022
                                           instance,
6023
                                           migration_info,
6024
                                           self.nodes_ip[target_node])
6025

    
6026
    msg = result.fail_msg
6027
    if msg:
6028
      logging.error("Instance pre-migration failed, trying to revert"
6029
                    " disk status: %s", msg)
6030
      self.feedback_fn("Pre-migration failed, aborting")
6031
      self._AbortMigration()
6032
      self._RevertDiskStatus()
6033
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6034
                               (instance.name, msg))
6035

    
6036
    self.feedback_fn("* migrating instance to %s" % target_node)
6037
    time.sleep(10)
6038
    result = self.rpc.call_instance_migrate(source_node, instance,
6039
                                            self.nodes_ip[target_node],
6040
                                            self.live)
6041
    msg = result.fail_msg
6042
    if msg:
6043
      logging.error("Instance migration failed, trying to revert"
6044
                    " disk status: %s", msg)
6045
      self.feedback_fn("Migration failed, aborting")
6046
      self._AbortMigration()
6047
      self._RevertDiskStatus()
6048
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6049
                               (instance.name, msg))
6050
    time.sleep(10)
6051

    
6052
    instance.primary_node = target_node
6053
    # distribute new instance config to the other nodes
6054
    self.cfg.Update(instance, self.feedback_fn)
6055

    
6056
    result = self.rpc.call_finalize_migration(target_node,
6057
                                              instance,
6058
                                              migration_info,
6059
                                              True)
6060
    msg = result.fail_msg
6061
    if msg:
6062
      logging.error("Instance migration succeeded, but finalization failed:"
6063
                    " %s", msg)
6064
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6065
                               msg)
6066

    
6067
    self._EnsureSecondary(source_node)
6068
    self._WaitUntilSync()
6069
    self._GoStandalone()
6070
    self._GoReconnect(False)
6071
    self._WaitUntilSync()
6072

    
6073
    self.feedback_fn("* done")
6074

    
6075
  def Exec(self, feedback_fn):
6076
    """Perform the migration.
6077

6078
    """
6079
    feedback_fn("Migrating instance %s" % self.instance.name)
6080

    
6081
    self.feedback_fn = feedback_fn
6082

    
6083
    self.source_node = self.instance.primary_node
6084
    self.target_node = self.instance.secondary_nodes[0]
6085
    self.all_nodes = [self.source_node, self.target_node]
6086
    self.nodes_ip = {
6087
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6088
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6089
      }
6090

    
6091
    if self.cleanup:
6092
      return self._ExecCleanup()
6093
    else:
6094
      return self._ExecMigration()
6095

    
6096

    
6097
def _CreateBlockDev(lu, node, instance, device, force_create,
6098
                    info, force_open):
6099
  """Create a tree of block devices on a given node.
6100

6101
  If this device type has to be created on secondaries, create it and
6102
  all its children.
6103

6104
  If not, just recurse to children keeping the same 'force' value.
6105

6106
  @param lu: the lu on whose behalf we execute
6107
  @param node: the node on which to create the device
6108
  @type instance: L{objects.Instance}
6109
  @param instance: the instance which owns the device
6110
  @type device: L{objects.Disk}
6111
  @param device: the device to create
6112
  @type force_create: boolean
6113
  @param force_create: whether to force creation of this device; this
6114
      will be change to True whenever we find a device which has
6115
      CreateOnSecondary() attribute
6116
  @param info: the extra 'metadata' we should attach to the device
6117
      (this will be represented as a LVM tag)
6118
  @type force_open: boolean
6119
  @param force_open: this parameter will be passes to the
6120
      L{backend.BlockdevCreate} function where it specifies
6121
      whether we run on primary or not, and it affects both
6122
      the child assembly and the device own Open() execution
6123

6124
  """
6125
  if device.CreateOnSecondary():
6126
    force_create = True
6127

    
6128
  if device.children:
6129
    for child in device.children:
6130
      _CreateBlockDev(lu, node, instance, child, force_create,
6131
                      info, force_open)
6132

    
6133
  if not force_create:
6134
    return
6135

    
6136
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6137

    
6138

    
6139
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6140
  """Create a single block device on a given node.
6141

6142
  This will not recurse over children of the device, so they must be
6143
  created in advance.
6144

6145
  @param lu: the lu on whose behalf we execute
6146
  @param node: the node on which to create the device
6147
  @type instance: L{objects.Instance}
6148
  @param instance: the instance which owns the device
6149
  @type device: L{objects.Disk}
6150
  @param device: the device to create
6151
  @param info: the extra 'metadata' we should attach to the device
6152
      (this will be represented as a LVM tag)
6153
  @type force_open: boolean
6154
  @param force_open: this parameter will be passes to the
6155
      L{backend.BlockdevCreate} function where it specifies
6156
      whether we run on primary or not, and it affects both
6157
      the child assembly and the device own Open() execution
6158

6159
  """
6160
  lu.cfg.SetDiskID(device, node)
6161
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6162
                                       instance.name, force_open, info)
6163
  result.Raise("Can't create block device %s on"
6164
               " node %s for instance %s" % (device, node, instance.name))
6165
  if device.physical_id is None:
6166
    device.physical_id = result.payload
6167

    
6168

    
6169
def _GenerateUniqueNames(lu, exts):
6170
  """Generate a suitable LV name.
6171

6172
  This will generate a logical volume name for the given instance.
6173

6174
  """
6175
  results = []
6176
  for val in exts:
6177
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6178
    results.append("%s%s" % (new_id, val))
6179
  return results
6180

    
6181

    
6182
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6183
                         p_minor, s_minor):
6184
  """Generate a drbd8 device complete with its children.
6185

6186
  """
6187
  port = lu.cfg.AllocatePort()
6188
  vgname = lu.cfg.GetVGName()
6189
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6190
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6191
                          logical_id=(vgname, names[0]))
6192
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6193
                          logical_id=(vgname, names[1]))
6194
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6195
                          logical_id=(primary, secondary, port,
6196
                                      p_minor, s_minor,
6197
                                      shared_secret),
6198
                          children=[dev_data, dev_meta],
6199
                          iv_name=iv_name)
6200
  return drbd_dev
6201

    
6202

    
6203
def _GenerateDiskTemplate(lu, template_name,
6204
                          instance_name, primary_node,
6205
                          secondary_nodes, disk_info,
6206
                          file_storage_dir, file_driver,
6207
                          base_index):
6208
  """Generate the entire disk layout for a given template type.
6209

6210
  """
6211
  #TODO: compute space requirements
6212

    
6213
  vgname = lu.cfg.GetVGName()
6214
  disk_count = len(disk_info)
6215
  disks = []
6216
  if template_name == constants.DT_DISKLESS:
6217
    pass
6218
  elif template_name == constants.DT_PLAIN:
6219
    if len(secondary_nodes) != 0:
6220
      raise errors.ProgrammerError("Wrong template configuration")
6221

    
6222
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6223
                                      for i in range(disk_count)])
6224
    for idx, disk in enumerate(disk_info):
6225
      disk_index = idx + base_index
6226
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6227
                              logical_id=(vgname, names[idx]),
6228
                              iv_name="disk/%d" % disk_index,
6229
                              mode=disk["mode"])
6230
      disks.append(disk_dev)
6231
  elif template_name == constants.DT_DRBD8:
6232
    if len(secondary_nodes) != 1:
6233
      raise errors.ProgrammerError("Wrong template configuration")
6234
    remote_node = secondary_nodes[0]
6235
    minors = lu.cfg.AllocateDRBDMinor(
6236
      [primary_node, remote_node] * len(disk_info), instance_name)
6237

    
6238
    names = []
6239
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6240
                                               for i in range(disk_count)]):
6241
      names.append(lv_prefix + "_data")
6242
      names.append(lv_prefix + "_meta")
6243
    for idx, disk in enumerate(disk_info):
6244
      disk_index = idx + base_index
6245
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6246
                                      disk["size"], names[idx*2:idx*2+2],
6247
                                      "disk/%d" % disk_index,
6248
                                      minors[idx*2], minors[idx*2+1])
6249
      disk_dev.mode = disk["mode"]
6250
      disks.append(disk_dev)
6251
  elif template_name == constants.DT_FILE:
6252
    if len(secondary_nodes) != 0:
6253
      raise errors.ProgrammerError("Wrong template configuration")
6254

    
6255
    _RequireFileStorage()
6256

    
6257
    for idx, disk in enumerate(disk_info):
6258
      disk_index = idx + base_index
6259
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6260
                              iv_name="disk/%d" % disk_index,
6261
                              logical_id=(file_driver,
6262
                                          "%s/disk%d" % (file_storage_dir,
6263
                                                         disk_index)),
6264
                              mode=disk["mode"])
6265
      disks.append(disk_dev)
6266
  else:
6267
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6268
  return disks
6269

    
6270

    
6271
def _GetInstanceInfoText(instance):
6272
  """Compute that text that should be added to the disk's metadata.
6273

6274
  """
6275
  return "originstname+%s" % instance.name
6276

    
6277

    
6278
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6279
  """Create all disks for an instance.
6280

6281
  This abstracts away some work from AddInstance.
6282

6283
  @type lu: L{LogicalUnit}
6284
  @param lu: the logical unit on whose behalf we execute
6285
  @type instance: L{objects.Instance}
6286
  @param instance: the instance whose disks we should create
6287
  @type to_skip: list
6288
  @param to_skip: list of indices to skip
6289
  @type target_node: string
6290
  @param target_node: if passed, overrides the target node for creation
6291
  @rtype: boolean
6292
  @return: the success of the creation
6293

6294
  """
6295
  info = _GetInstanceInfoText(instance)
6296
  if target_node is None:
6297
    pnode = instance.primary_node
6298
    all_nodes = instance.all_nodes
6299
  else:
6300
    pnode = target_node
6301
    all_nodes = [pnode]
6302

    
6303
  if instance.disk_template == constants.DT_FILE:
6304
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6305
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6306

    
6307
    result.Raise("Failed to create directory '%s' on"
6308
                 " node %s" % (file_storage_dir, pnode))
6309

    
6310
  # Note: this needs to be kept in sync with adding of disks in
6311
  # LUSetInstanceParams
6312
  for idx, device in enumerate(instance.disks):
6313
    if to_skip and idx in to_skip:
6314
      continue
6315
    logging.info("Creating volume %s for instance %s",
6316
                 device.iv_name, instance.name)
6317
    #HARDCODE
6318
    for node in all_nodes:
6319
      f_create = node == pnode
6320
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6321

    
6322

    
6323
def _RemoveDisks(lu, instance, target_node=None):
6324
  """Remove all disks for an instance.
6325

6326
  This abstracts away some work from `AddInstance()` and
6327
  `RemoveInstance()`. Note that in case some of the devices couldn't
6328
  be removed, the removal will continue with the other ones (compare
6329
  with `_CreateDisks()`).
6330

6331
  @type lu: L{LogicalUnit}
6332
  @param lu: the logical unit on whose behalf we execute
6333
  @type instance: L{objects.Instance}
6334
  @param instance: the instance whose disks we should remove
6335
  @type target_node: string
6336
  @param target_node: used to override the node on which to remove the disks
6337
  @rtype: boolean
6338
  @return: the success of the removal
6339

6340
  """
6341
  logging.info("Removing block devices for instance %s", instance.name)
6342

    
6343
  all_result = True
6344
  for device in instance.disks:
6345
    if target_node:
6346
      edata = [(target_node, device)]
6347
    else:
6348
      edata = device.ComputeNodeTree(instance.primary_node)
6349
    for node, disk in edata:
6350
      lu.cfg.SetDiskID(disk, node)
6351
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6352
      if msg:
6353
        lu.LogWarning("Could not remove block device %s on node %s,"
6354
                      " continuing anyway: %s", device.iv_name, node, msg)
6355
        all_result = False
6356

    
6357
  if instance.disk_template == constants.DT_FILE:
6358
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6359
    if target_node:
6360
      tgt = target_node
6361
    else:
6362
      tgt = instance.primary_node
6363
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6364
    if result.fail_msg:
6365
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6366
                    file_storage_dir, instance.primary_node, result.fail_msg)
6367
      all_result = False
6368

    
6369
  return all_result
6370

    
6371

    
6372
def _ComputeDiskSize(disk_template, disks):
6373
  """Compute disk size requirements in the volume group
6374

6375
  """
6376
  # Required free disk space as a function of disk and swap space
6377
  req_size_dict = {
6378
    constants.DT_DISKLESS: None,
6379
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6380
    # 128 MB are added for drbd metadata for each disk
6381
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6382
    constants.DT_FILE: None,
6383
  }
6384

    
6385
  if disk_template not in req_size_dict:
6386
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6387
                                 " is unknown" %  disk_template)
6388

    
6389
  return req_size_dict[disk_template]
6390

    
6391

    
6392
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6393
  """Hypervisor parameter validation.
6394

6395
  This function abstract the hypervisor parameter validation to be
6396
  used in both instance create and instance modify.
6397

6398
  @type lu: L{LogicalUnit}
6399
  @param lu: the logical unit for which we check
6400
  @type nodenames: list
6401
  @param nodenames: the list of nodes on which we should check
6402
  @type hvname: string
6403
  @param hvname: the name of the hypervisor we should use
6404
  @type hvparams: dict
6405
  @param hvparams: the parameters which we need to check
6406
  @raise errors.OpPrereqError: if the parameters are not valid
6407

6408
  """
6409
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6410
                                                  hvname,
6411
                                                  hvparams)
6412
  for node in nodenames:
6413
    info = hvinfo[node]
6414
    if info.offline:
6415
      continue
6416
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6417

    
6418

    
6419
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6420
  """OS parameters validation.
6421

6422
  @type lu: L{LogicalUnit}
6423
  @param lu: the logical unit for which we check
6424
  @type required: boolean
6425
  @param required: whether the validation should fail if the OS is not
6426
      found
6427
  @type nodenames: list
6428
  @param nodenames: the list of nodes on which we should check
6429
  @type osname: string
6430
  @param osname: the name of the hypervisor we should use
6431
  @type osparams: dict
6432
  @param osparams: the parameters which we need to check
6433
  @raise errors.OpPrereqError: if the parameters are not valid
6434

6435
  """
6436
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6437
                                   [constants.OS_VALIDATE_PARAMETERS],
6438
                                   osparams)
6439
  for node, nres in result.items():
6440
    # we don't check for offline cases since this should be run only
6441
    # against the master node and/or an instance's nodes
6442
    nres.Raise("OS Parameters validation failed on node %s" % node)
6443
    if not nres.payload:
6444
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6445
                 osname, node)
6446

    
6447

    
6448
class LUCreateInstance(LogicalUnit):
6449
  """Create an instance.
6450

6451
  """
6452
  HPATH = "instance-add"
6453
  HTYPE = constants.HTYPE_INSTANCE
6454
  _OP_PARAMS = [
6455
    _PInstanceName,
6456
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6457
    ("start", True, _TBool),
6458
    ("wait_for_sync", True, _TBool),
6459
    ("ip_check", True, _TBool),
6460
    ("name_check", True, _TBool),
6461
    ("disks", _NoDefault, _TListOf(_TDict)),
6462
    ("nics", _NoDefault, _TListOf(_TDict)),
6463
    ("hvparams", _EmptyDict, _TDict),
6464
    ("beparams", _EmptyDict, _TDict),
6465
    ("osparams", _EmptyDict, _TDict),
6466
    ("no_install", None, _TMaybeBool),
6467
    ("os_type", None, _TMaybeString),
6468
    ("force_variant", False, _TBool),
6469
    ("source_handshake", None, _TOr(_TList, _TNone)),
6470
    ("source_x509_ca", None, _TOr(_TList, _TNone)),
6471
    ("source_instance_name", None, _TMaybeString),
6472
    ("src_node", None, _TMaybeString),
6473
    ("src_path", None, _TMaybeString),
6474
    ("pnode", None, _TMaybeString),
6475
    ("snode", None, _TMaybeString),
6476
    ("iallocator", None, _TMaybeString),
6477
    ("hypervisor", None, _TMaybeString),
6478
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6479
    ("identify_defaults", False, _TBool),
6480
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6481
    ("file_storage_dir", None, _TMaybeString),
6482
    ("dry_run", False, _TBool),
6483
    ]
6484
  REQ_BGL = False
6485

    
6486
  def CheckArguments(self):
6487
    """Check arguments.
6488

6489
    """
6490
    # do not require name_check to ease forward/backward compatibility
6491
    # for tools
6492
    if self.op.no_install and self.op.start:
6493
      self.LogInfo("No-installation mode selected, disabling startup")
6494
      self.op.start = False
6495
    # validate/normalize the instance name
6496
    self.op.instance_name = \
6497
      netutils.HostInfo.NormalizeName(self.op.instance_name)
6498

    
6499
    if self.op.ip_check and not self.op.name_check:
6500
      # TODO: make the ip check more flexible and not depend on the name check
6501
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6502
                                 errors.ECODE_INVAL)
6503

    
6504
    # check nics' parameter names
6505
    for nic in self.op.nics:
6506
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6507

    
6508
    # check disks. parameter names and consistent adopt/no-adopt strategy
6509
    has_adopt = has_no_adopt = False
6510
    for disk in self.op.disks:
6511
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6512
      if "adopt" in disk:
6513
        has_adopt = True
6514
      else:
6515
        has_no_adopt = True
6516
    if has_adopt and has_no_adopt:
6517
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6518
                                 errors.ECODE_INVAL)
6519
    if has_adopt:
6520
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6521
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6522
                                   " '%s' disk template" %
6523
                                   self.op.disk_template,
6524
                                   errors.ECODE_INVAL)
6525
      if self.op.iallocator is not None:
6526
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6527
                                   " iallocator script", errors.ECODE_INVAL)
6528
      if self.op.mode == constants.INSTANCE_IMPORT:
6529
        raise errors.OpPrereqError("Disk adoption not allowed for"
6530
                                   " instance import", errors.ECODE_INVAL)
6531

    
6532
    self.adopt_disks = has_adopt
6533

    
6534
    # instance name verification
6535
    if self.op.name_check:
6536
      self.hostname1 = netutils.GetHostInfo(self.op.instance_name)
6537
      self.op.instance_name = self.hostname1.name
6538
      # used in CheckPrereq for ip ping check
6539
      self.check_ip = self.hostname1.ip
6540
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6541
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6542
                                 errors.ECODE_INVAL)
6543
    else:
6544
      self.check_ip = None
6545

    
6546
    # file storage checks
6547
    if (self.op.file_driver and
6548
        not self.op.file_driver in constants.FILE_DRIVER):
6549
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6550
                                 self.op.file_driver, errors.ECODE_INVAL)
6551

    
6552
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6553
      raise errors.OpPrereqError("File storage directory path not absolute",
6554
                                 errors.ECODE_INVAL)
6555

    
6556
    ### Node/iallocator related checks
6557
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6558

    
6559
    self._cds = _GetClusterDomainSecret()
6560

    
6561
    if self.op.mode == constants.INSTANCE_IMPORT:
6562
      # On import force_variant must be True, because if we forced it at
6563
      # initial install, our only chance when importing it back is that it
6564
      # works again!
6565
      self.op.force_variant = True
6566

    
6567
      if self.op.no_install:
6568
        self.LogInfo("No-installation mode has no effect during import")
6569

    
6570
    elif self.op.mode == constants.INSTANCE_CREATE:
6571
      if self.op.os_type is None:
6572
        raise errors.OpPrereqError("No guest OS specified",
6573
                                   errors.ECODE_INVAL)
6574
      if self.op.disk_template is None:
6575
        raise errors.OpPrereqError("No disk template specified",
6576
                                   errors.ECODE_INVAL)
6577

    
6578
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6579
      # Check handshake to ensure both clusters have the same domain secret
6580
      src_handshake = self.op.source_handshake
6581
      if not src_handshake:
6582
        raise errors.OpPrereqError("Missing source handshake",
6583
                                   errors.ECODE_INVAL)
6584

    
6585
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6586
                                                           src_handshake)
6587
      if errmsg:
6588
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6589
                                   errors.ECODE_INVAL)
6590

    
6591
      # Load and check source CA
6592
      self.source_x509_ca_pem = self.op.source_x509_ca
6593
      if not self.source_x509_ca_pem:
6594
        raise errors.OpPrereqError("Missing source X509 CA",
6595
                                   errors.ECODE_INVAL)
6596

    
6597
      try:
6598
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6599
                                                    self._cds)
6600
      except OpenSSL.crypto.Error, err:
6601
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6602
                                   (err, ), errors.ECODE_INVAL)
6603

    
6604
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6605
      if errcode is not None:
6606
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6607
                                   errors.ECODE_INVAL)
6608

    
6609
      self.source_x509_ca = cert
6610

    
6611
      src_instance_name = self.op.source_instance_name
6612
      if not src_instance_name:
6613
        raise errors.OpPrereqError("Missing source instance name",
6614
                                   errors.ECODE_INVAL)
6615

    
6616
      norm_name = netutils.HostInfo.NormalizeName(src_instance_name)
6617
      self.source_instance_name = netutils.GetHostInfo(norm_name).name
6618

    
6619
    else:
6620
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6621
                                 self.op.mode, errors.ECODE_INVAL)
6622

    
6623
  def ExpandNames(self):
6624
    """ExpandNames for CreateInstance.
6625

6626
    Figure out the right locks for instance creation.
6627

6628
    """
6629
    self.needed_locks = {}
6630

    
6631
    instance_name = self.op.instance_name
6632
    # this is just a preventive check, but someone might still add this
6633
    # instance in the meantime, and creation will fail at lock-add time
6634
    if instance_name in self.cfg.GetInstanceList():
6635
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6636
                                 instance_name, errors.ECODE_EXISTS)
6637

    
6638
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6639

    
6640
    if self.op.iallocator:
6641
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6642
    else:
6643
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6644
      nodelist = [self.op.pnode]
6645
      if self.op.snode is not None:
6646
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6647
        nodelist.append(self.op.snode)
6648
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6649

    
6650
    # in case of import lock the source node too
6651
    if self.op.mode == constants.INSTANCE_IMPORT:
6652
      src_node = self.op.src_node
6653
      src_path = self.op.src_path
6654

    
6655
      if src_path is None:
6656
        self.op.src_path = src_path = self.op.instance_name
6657

    
6658
      if src_node is None:
6659
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6660
        self.op.src_node = None
6661
        if os.path.isabs(src_path):
6662
          raise errors.OpPrereqError("Importing an instance from an absolute"
6663
                                     " path requires a source node option.",
6664
                                     errors.ECODE_INVAL)
6665
      else:
6666
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6667
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6668
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6669
        if not os.path.isabs(src_path):
6670
          self.op.src_path = src_path = \
6671
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6672

    
6673
  def _RunAllocator(self):
6674
    """Run the allocator based on input opcode.
6675

6676
    """
6677
    nics = [n.ToDict() for n in self.nics]
6678
    ial = IAllocator(self.cfg, self.rpc,
6679
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6680
                     name=self.op.instance_name,
6681
                     disk_template=self.op.disk_template,
6682
                     tags=[],
6683
                     os=self.op.os_type,
6684
                     vcpus=self.be_full[constants.BE_VCPUS],
6685
                     mem_size=self.be_full[constants.BE_MEMORY],
6686
                     disks=self.disks,
6687
                     nics=nics,
6688
                     hypervisor=self.op.hypervisor,
6689
                     )
6690

    
6691
    ial.Run(self.op.iallocator)
6692

    
6693
    if not ial.success:
6694
      raise errors.OpPrereqError("Can't compute nodes using"
6695
                                 " iallocator '%s': %s" %
6696
                                 (self.op.iallocator, ial.info),
6697
                                 errors.ECODE_NORES)
6698
    if len(ial.result) != ial.required_nodes:
6699
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6700
                                 " of nodes (%s), required %s" %
6701
                                 (self.op.iallocator, len(ial.result),
6702
                                  ial.required_nodes), errors.ECODE_FAULT)
6703
    self.op.pnode = ial.result[0]
6704
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6705
                 self.op.instance_name, self.op.iallocator,
6706
                 utils.CommaJoin(ial.result))
6707
    if ial.required_nodes == 2:
6708
      self.op.snode = ial.result[1]
6709

    
6710
  def BuildHooksEnv(self):
6711
    """Build hooks env.
6712

6713
    This runs on master, primary and secondary nodes of the instance.
6714

6715
    """
6716
    env = {
6717
      "ADD_MODE": self.op.mode,
6718
      }
6719
    if self.op.mode == constants.INSTANCE_IMPORT:
6720
      env["SRC_NODE"] = self.op.src_node
6721
      env["SRC_PATH"] = self.op.src_path
6722
      env["SRC_IMAGES"] = self.src_images
6723

    
6724
    env.update(_BuildInstanceHookEnv(
6725
      name=self.op.instance_name,
6726
      primary_node=self.op.pnode,
6727
      secondary_nodes=self.secondaries,
6728
      status=self.op.start,
6729
      os_type=self.op.os_type,
6730
      memory=self.be_full[constants.BE_MEMORY],
6731
      vcpus=self.be_full[constants.BE_VCPUS],
6732
      nics=_NICListToTuple(self, self.nics),
6733
      disk_template=self.op.disk_template,
6734
      disks=[(d["size"], d["mode"]) for d in self.disks],
6735
      bep=self.be_full,
6736
      hvp=self.hv_full,
6737
      hypervisor_name=self.op.hypervisor,
6738
    ))
6739

    
6740
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6741
          self.secondaries)
6742
    return env, nl, nl
6743

    
6744
  def _ReadExportInfo(self):
6745
    """Reads the export information from disk.
6746

6747
    It will override the opcode source node and path with the actual
6748
    information, if these two were not specified before.
6749

6750
    @return: the export information
6751

6752
    """
6753
    assert self.op.mode == constants.INSTANCE_IMPORT
6754

    
6755
    src_node = self.op.src_node
6756
    src_path = self.op.src_path
6757

    
6758
    if src_node is None:
6759
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6760
      exp_list = self.rpc.call_export_list(locked_nodes)
6761
      found = False
6762
      for node in exp_list:
6763
        if exp_list[node].fail_msg:
6764
          continue
6765
        if src_path in exp_list[node].payload:
6766
          found = True
6767
          self.op.src_node = src_node = node
6768
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6769
                                                       src_path)
6770
          break
6771
      if not found:
6772
        raise errors.OpPrereqError("No export found for relative path %s" %
6773
                                    src_path, errors.ECODE_INVAL)
6774

    
6775
    _CheckNodeOnline(self, src_node)
6776
    result = self.rpc.call_export_info(src_node, src_path)
6777
    result.Raise("No export or invalid export found in dir %s" % src_path)
6778

    
6779
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6780
    if not export_info.has_section(constants.INISECT_EXP):
6781
      raise errors.ProgrammerError("Corrupted export config",
6782
                                   errors.ECODE_ENVIRON)
6783

    
6784
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6785
    if (int(ei_version) != constants.EXPORT_VERSION):
6786
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6787
                                 (ei_version, constants.EXPORT_VERSION),
6788
                                 errors.ECODE_ENVIRON)
6789
    return export_info
6790

    
6791
  def _ReadExportParams(self, einfo):
6792
    """Use export parameters as defaults.
6793

6794
    In case the opcode doesn't specify (as in override) some instance
6795
    parameters, then try to use them from the export information, if
6796
    that declares them.
6797

6798
    """
6799
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6800

    
6801
    if self.op.disk_template is None:
6802
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6803
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6804
                                          "disk_template")
6805
      else:
6806
        raise errors.OpPrereqError("No disk template specified and the export"
6807
                                   " is missing the disk_template information",
6808
                                   errors.ECODE_INVAL)
6809

    
6810
    if not self.op.disks:
6811
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6812
        disks = []
6813
        # TODO: import the disk iv_name too
6814
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6815
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6816
          disks.append({"size": disk_sz})
6817
        self.op.disks = disks
6818
      else:
6819
        raise errors.OpPrereqError("No disk info specified and the export"
6820
                                   " is missing the disk information",
6821
                                   errors.ECODE_INVAL)
6822

    
6823
    if (not self.op.nics and
6824
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6825
      nics = []
6826
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6827
        ndict = {}
6828
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6829
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6830
          ndict[name] = v
6831
        nics.append(ndict)
6832
      self.op.nics = nics
6833

    
6834
    if (self.op.hypervisor is None and
6835
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6836
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6837
    if einfo.has_section(constants.INISECT_HYP):
6838
      # use the export parameters but do not override the ones
6839
      # specified by the user
6840
      for name, value in einfo.items(constants.INISECT_HYP):
6841
        if name not in self.op.hvparams:
6842
          self.op.hvparams[name] = value
6843

    
6844
    if einfo.has_section(constants.INISECT_BEP):
6845
      # use the parameters, without overriding
6846
      for name, value in einfo.items(constants.INISECT_BEP):
6847
        if name not in self.op.beparams:
6848
          self.op.beparams[name] = value
6849
    else:
6850
      # try to read the parameters old style, from the main section
6851
      for name in constants.BES_PARAMETERS:
6852
        if (name not in self.op.beparams and
6853
            einfo.has_option(constants.INISECT_INS, name)):
6854
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6855

    
6856
    if einfo.has_section(constants.INISECT_OSP):
6857
      # use the parameters, without overriding
6858
      for name, value in einfo.items(constants.INISECT_OSP):
6859
        if name not in self.op.osparams:
6860
          self.op.osparams[name] = value
6861

    
6862
  def _RevertToDefaults(self, cluster):
6863
    """Revert the instance parameters to the default values.
6864

6865
    """
6866
    # hvparams
6867
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6868
    for name in self.op.hvparams.keys():
6869
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6870
        del self.op.hvparams[name]
6871
    # beparams
6872
    be_defs = cluster.SimpleFillBE({})
6873
    for name in self.op.beparams.keys():
6874
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6875
        del self.op.beparams[name]
6876
    # nic params
6877
    nic_defs = cluster.SimpleFillNIC({})
6878
    for nic in self.op.nics:
6879
      for name in constants.NICS_PARAMETERS:
6880
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6881
          del nic[name]
6882
    # osparams
6883
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6884
    for name in self.op.osparams.keys():
6885
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6886
        del self.op.osparams[name]
6887

    
6888
  def CheckPrereq(self):
6889
    """Check prerequisites.
6890

6891
    """
6892
    if self.op.mode == constants.INSTANCE_IMPORT:
6893
      export_info = self._ReadExportInfo()
6894
      self._ReadExportParams(export_info)
6895

    
6896
    _CheckDiskTemplate(self.op.disk_template)
6897

    
6898
    if (not self.cfg.GetVGName() and
6899
        self.op.disk_template not in constants.DTS_NOT_LVM):
6900
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6901
                                 " instances", errors.ECODE_STATE)
6902

    
6903
    if self.op.hypervisor is None:
6904
      self.op.hypervisor = self.cfg.GetHypervisorType()
6905

    
6906
    cluster = self.cfg.GetClusterInfo()
6907
    enabled_hvs = cluster.enabled_hypervisors
6908
    if self.op.hypervisor not in enabled_hvs:
6909
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6910
                                 " cluster (%s)" % (self.op.hypervisor,
6911
                                  ",".join(enabled_hvs)),
6912
                                 errors.ECODE_STATE)
6913

    
6914
    # check hypervisor parameter syntax (locally)
6915
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6916
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6917
                                      self.op.hvparams)
6918
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6919
    hv_type.CheckParameterSyntax(filled_hvp)
6920
    self.hv_full = filled_hvp
6921
    # check that we don't specify global parameters on an instance
6922
    _CheckGlobalHvParams(self.op.hvparams)
6923

    
6924
    # fill and remember the beparams dict
6925
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6926
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6927

    
6928
    # build os parameters
6929
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6930

    
6931
    # now that hvp/bep are in final format, let's reset to defaults,
6932
    # if told to do so
6933
    if self.op.identify_defaults:
6934
      self._RevertToDefaults(cluster)
6935

    
6936
    # NIC buildup
6937
    self.nics = []
6938
    for idx, nic in enumerate(self.op.nics):
6939
      nic_mode_req = nic.get("mode", None)
6940
      nic_mode = nic_mode_req
6941
      if nic_mode is None:
6942
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6943

    
6944
      # in routed mode, for the first nic, the default ip is 'auto'
6945
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6946
        default_ip_mode = constants.VALUE_AUTO
6947
      else:
6948
        default_ip_mode = constants.VALUE_NONE
6949

    
6950
      # ip validity checks
6951
      ip = nic.get("ip", default_ip_mode)
6952
      if ip is None or ip.lower() == constants.VALUE_NONE:
6953
        nic_ip = None
6954
      elif ip.lower() == constants.VALUE_AUTO:
6955
        if not self.op.name_check:
6956
          raise errors.OpPrereqError("IP address set to auto but name checks"
6957
                                     " have been skipped. Aborting.",
6958
                                     errors.ECODE_INVAL)
6959
        nic_ip = self.hostname1.ip
6960
      else:
6961
        if not netutils.IsValidIP4(ip):
6962
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6963
                                     " like a valid IP" % ip,
6964
                                     errors.ECODE_INVAL)
6965
        nic_ip = ip
6966

    
6967
      # TODO: check the ip address for uniqueness
6968
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6969
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6970
                                   errors.ECODE_INVAL)
6971

    
6972
      # MAC address verification
6973
      mac = nic.get("mac", constants.VALUE_AUTO)
6974
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6975
        mac = utils.NormalizeAndValidateMac(mac)
6976

    
6977
        try:
6978
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6979
        except errors.ReservationError:
6980
          raise errors.OpPrereqError("MAC address %s already in use"
6981
                                     " in cluster" % mac,
6982
                                     errors.ECODE_NOTUNIQUE)
6983

    
6984
      # bridge verification
6985
      bridge = nic.get("bridge", None)
6986
      link = nic.get("link", None)
6987
      if bridge and link:
6988
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6989
                                   " at the same time", errors.ECODE_INVAL)
6990
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6991
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6992
                                   errors.ECODE_INVAL)
6993
      elif bridge:
6994
        link = bridge
6995

    
6996
      nicparams = {}
6997
      if nic_mode_req:
6998
        nicparams[constants.NIC_MODE] = nic_mode_req
6999
      if link:
7000
        nicparams[constants.NIC_LINK] = link
7001

    
7002
      check_params = cluster.SimpleFillNIC(nicparams)
7003
      objects.NIC.CheckParameterSyntax(check_params)
7004
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7005

    
7006
    # disk checks/pre-build
7007
    self.disks = []
7008
    for disk in self.op.disks:
7009
      mode = disk.get("mode", constants.DISK_RDWR)
7010
      if mode not in constants.DISK_ACCESS_SET:
7011
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7012
                                   mode, errors.ECODE_INVAL)
7013
      size = disk.get("size", None)
7014
      if size is None:
7015
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7016
      try:
7017
        size = int(size)
7018
      except (TypeError, ValueError):
7019
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7020
                                   errors.ECODE_INVAL)
7021
      new_disk = {"size": size, "mode": mode}
7022
      if "adopt" in disk:
7023
        new_disk["adopt"] = disk["adopt"]
7024
      self.disks.append(new_disk)
7025

    
7026
    if self.op.mode == constants.INSTANCE_IMPORT:
7027

    
7028
      # Check that the new instance doesn't have less disks than the export
7029
      instance_disks = len(self.disks)
7030
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7031
      if instance_disks < export_disks:
7032
        raise errors.OpPrereqError("Not enough disks to import."
7033
                                   " (instance: %d, export: %d)" %
7034
                                   (instance_disks, export_disks),
7035
                                   errors.ECODE_INVAL)
7036

    
7037
      disk_images = []
7038
      for idx in range(export_disks):
7039
        option = 'disk%d_dump' % idx
7040
        if export_info.has_option(constants.INISECT_INS, option):
7041
          # FIXME: are the old os-es, disk sizes, etc. useful?
7042
          export_name = export_info.get(constants.INISECT_INS, option)
7043
          image = utils.PathJoin(self.op.src_path, export_name)
7044
          disk_images.append(image)
7045
        else:
7046
          disk_images.append(False)
7047

    
7048
      self.src_images = disk_images
7049

    
7050
      old_name = export_info.get(constants.INISECT_INS, 'name')
7051
      try:
7052
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7053
      except (TypeError, ValueError), err:
7054
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7055
                                   " an integer: %s" % str(err),
7056
                                   errors.ECODE_STATE)
7057
      if self.op.instance_name == old_name:
7058
        for idx, nic in enumerate(self.nics):
7059
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7060
            nic_mac_ini = 'nic%d_mac' % idx
7061
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7062

    
7063
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7064

    
7065
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7066
    if self.op.ip_check:
7067
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7068
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7069
                                   (self.check_ip, self.op.instance_name),
7070
                                   errors.ECODE_NOTUNIQUE)
7071

    
7072
    #### mac address generation
7073
    # By generating here the mac address both the allocator and the hooks get
7074
    # the real final mac address rather than the 'auto' or 'generate' value.
7075
    # There is a race condition between the generation and the instance object
7076
    # creation, which means that we know the mac is valid now, but we're not
7077
    # sure it will be when we actually add the instance. If things go bad
7078
    # adding the instance will abort because of a duplicate mac, and the
7079
    # creation job will fail.
7080
    for nic in self.nics:
7081
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7082
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7083

    
7084
    #### allocator run
7085

    
7086
    if self.op.iallocator is not None:
7087
      self._RunAllocator()
7088

    
7089
    #### node related checks
7090

    
7091
    # check primary node
7092
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7093
    assert self.pnode is not None, \
7094
      "Cannot retrieve locked node %s" % self.op.pnode
7095
    if pnode.offline:
7096
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7097
                                 pnode.name, errors.ECODE_STATE)
7098
    if pnode.drained:
7099
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7100
                                 pnode.name, errors.ECODE_STATE)
7101

    
7102
    self.secondaries = []
7103

    
7104
    # mirror node verification
7105
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7106
      if self.op.snode is None:
7107
        raise errors.OpPrereqError("The networked disk templates need"
7108
                                   " a mirror node", errors.ECODE_INVAL)
7109
      if self.op.snode == pnode.name:
7110
        raise errors.OpPrereqError("The secondary node cannot be the"
7111
                                   " primary node.", errors.ECODE_INVAL)
7112
      _CheckNodeOnline(self, self.op.snode)
7113
      _CheckNodeNotDrained(self, self.op.snode)
7114
      self.secondaries.append(self.op.snode)
7115

    
7116
    nodenames = [pnode.name] + self.secondaries
7117

    
7118
    req_size = _ComputeDiskSize(self.op.disk_template,
7119
                                self.disks)
7120

    
7121
    # Check lv size requirements, if not adopting
7122
    if req_size is not None and not self.adopt_disks:
7123
      _CheckNodesFreeDisk(self, nodenames, req_size)
7124

    
7125
    if self.adopt_disks: # instead, we must check the adoption data
7126
      all_lvs = set([i["adopt"] for i in self.disks])
7127
      if len(all_lvs) != len(self.disks):
7128
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7129
                                   errors.ECODE_INVAL)
7130
      for lv_name in all_lvs:
7131
        try:
7132
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7133
        except errors.ReservationError:
7134
          raise errors.OpPrereqError("LV named %s used by another instance" %
7135
                                     lv_name, errors.ECODE_NOTUNIQUE)
7136

    
7137
      node_lvs = self.rpc.call_lv_list([pnode.name],
7138
                                       self.cfg.GetVGName())[pnode.name]
7139
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7140
      node_lvs = node_lvs.payload
7141
      delta = all_lvs.difference(node_lvs.keys())
7142
      if delta:
7143
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7144
                                   utils.CommaJoin(delta),
7145
                                   errors.ECODE_INVAL)
7146
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7147
      if online_lvs:
7148
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7149
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7150
                                   errors.ECODE_STATE)
7151
      # update the size of disk based on what is found
7152
      for dsk in self.disks:
7153
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7154

    
7155
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7156

    
7157
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7158
    # check OS parameters (remotely)
7159
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7160

    
7161
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7162

    
7163
    # memory check on primary node
7164
    if self.op.start:
7165
      _CheckNodeFreeMemory(self, self.pnode.name,
7166
                           "creating instance %s" % self.op.instance_name,
7167
                           self.be_full[constants.BE_MEMORY],
7168
                           self.op.hypervisor)
7169

    
7170
    self.dry_run_result = list(nodenames)
7171

    
7172
  def Exec(self, feedback_fn):
7173
    """Create and add the instance to the cluster.
7174

7175
    """
7176
    instance = self.op.instance_name
7177
    pnode_name = self.pnode.name
7178

    
7179
    ht_kind = self.op.hypervisor
7180
    if ht_kind in constants.HTS_REQ_PORT:
7181
      network_port = self.cfg.AllocatePort()
7182
    else:
7183
      network_port = None
7184

    
7185
    if constants.ENABLE_FILE_STORAGE:
7186
      # this is needed because os.path.join does not accept None arguments
7187
      if self.op.file_storage_dir is None:
7188
        string_file_storage_dir = ""
7189
      else:
7190
        string_file_storage_dir = self.op.file_storage_dir
7191

    
7192
      # build the full file storage dir path
7193
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7194
                                        string_file_storage_dir, instance)
7195
    else:
7196
      file_storage_dir = ""
7197

    
7198
    disks = _GenerateDiskTemplate(self,
7199
                                  self.op.disk_template,
7200
                                  instance, pnode_name,
7201
                                  self.secondaries,
7202
                                  self.disks,
7203
                                  file_storage_dir,
7204
                                  self.op.file_driver,
7205
                                  0)
7206

    
7207
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7208
                            primary_node=pnode_name,
7209
                            nics=self.nics, disks=disks,
7210
                            disk_template=self.op.disk_template,
7211
                            admin_up=False,
7212
                            network_port=network_port,
7213
                            beparams=self.op.beparams,
7214
                            hvparams=self.op.hvparams,
7215
                            hypervisor=self.op.hypervisor,
7216
                            osparams=self.op.osparams,
7217
                            )
7218

    
7219
    if self.adopt_disks:
7220
      # rename LVs to the newly-generated names; we need to construct
7221
      # 'fake' LV disks with the old data, plus the new unique_id
7222
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7223
      rename_to = []
7224
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7225
        rename_to.append(t_dsk.logical_id)
7226
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7227
        self.cfg.SetDiskID(t_dsk, pnode_name)
7228
      result = self.rpc.call_blockdev_rename(pnode_name,
7229
                                             zip(tmp_disks, rename_to))
7230
      result.Raise("Failed to rename adoped LVs")
7231
    else:
7232
      feedback_fn("* creating instance disks...")
7233
      try:
7234
        _CreateDisks(self, iobj)
7235
      except errors.OpExecError:
7236
        self.LogWarning("Device creation failed, reverting...")
7237
        try:
7238
          _RemoveDisks(self, iobj)
7239
        finally:
7240
          self.cfg.ReleaseDRBDMinors(instance)
7241
          raise
7242

    
7243
    feedback_fn("adding instance %s to cluster config" % instance)
7244

    
7245
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7246

    
7247
    # Declare that we don't want to remove the instance lock anymore, as we've
7248
    # added the instance to the config
7249
    del self.remove_locks[locking.LEVEL_INSTANCE]
7250
    # Unlock all the nodes
7251
    if self.op.mode == constants.INSTANCE_IMPORT:
7252
      nodes_keep = [self.op.src_node]
7253
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7254
                       if node != self.op.src_node]
7255
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7256
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7257
    else:
7258
      self.context.glm.release(locking.LEVEL_NODE)
7259
      del self.acquired_locks[locking.LEVEL_NODE]
7260

    
7261
    if self.op.wait_for_sync:
7262
      disk_abort = not _WaitForSync(self, iobj)
7263
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7264
      # make sure the disks are not degraded (still sync-ing is ok)
7265
      time.sleep(15)
7266
      feedback_fn("* checking mirrors status")
7267
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7268
    else:
7269
      disk_abort = False
7270

    
7271
    if disk_abort:
7272
      _RemoveDisks(self, iobj)
7273
      self.cfg.RemoveInstance(iobj.name)
7274
      # Make sure the instance lock gets removed
7275
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7276
      raise errors.OpExecError("There are some degraded disks for"
7277
                               " this instance")
7278

    
7279
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7280
      if self.op.mode == constants.INSTANCE_CREATE:
7281
        if not self.op.no_install:
7282
          feedback_fn("* running the instance OS create scripts...")
7283
          # FIXME: pass debug option from opcode to backend
7284
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7285
                                                 self.op.debug_level)
7286
          result.Raise("Could not add os for instance %s"
7287
                       " on node %s" % (instance, pnode_name))
7288

    
7289
      elif self.op.mode == constants.INSTANCE_IMPORT:
7290
        feedback_fn("* running the instance OS import scripts...")
7291

    
7292
        transfers = []
7293

    
7294
        for idx, image in enumerate(self.src_images):
7295
          if not image:
7296
            continue
7297

    
7298
          # FIXME: pass debug option from opcode to backend
7299
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7300
                                             constants.IEIO_FILE, (image, ),
7301
                                             constants.IEIO_SCRIPT,
7302
                                             (iobj.disks[idx], idx),
7303
                                             None)
7304
          transfers.append(dt)
7305

    
7306
        import_result = \
7307
          masterd.instance.TransferInstanceData(self, feedback_fn,
7308
                                                self.op.src_node, pnode_name,
7309
                                                self.pnode.secondary_ip,
7310
                                                iobj, transfers)
7311
        if not compat.all(import_result):
7312
          self.LogWarning("Some disks for instance %s on node %s were not"
7313
                          " imported successfully" % (instance, pnode_name))
7314

    
7315
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7316
        feedback_fn("* preparing remote import...")
7317
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7318
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7319

    
7320
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7321
                                                     self.source_x509_ca,
7322
                                                     self._cds, timeouts)
7323
        if not compat.all(disk_results):
7324
          # TODO: Should the instance still be started, even if some disks
7325
          # failed to import (valid for local imports, too)?
7326
          self.LogWarning("Some disks for instance %s on node %s were not"
7327
                          " imported successfully" % (instance, pnode_name))
7328

    
7329
        # Run rename script on newly imported instance
7330
        assert iobj.name == instance
7331
        feedback_fn("Running rename script for %s" % instance)
7332
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7333
                                                   self.source_instance_name,
7334
                                                   self.op.debug_level)
7335
        if result.fail_msg:
7336
          self.LogWarning("Failed to run rename script for %s on node"
7337
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7338

    
7339
      else:
7340
        # also checked in the prereq part
7341
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7342
                                     % self.op.mode)
7343

    
7344
    if self.op.start:
7345
      iobj.admin_up = True
7346
      self.cfg.Update(iobj, feedback_fn)
7347
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7348
      feedback_fn("* starting instance...")
7349
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7350
      result.Raise("Could not start instance")
7351

    
7352
    return list(iobj.all_nodes)
7353

    
7354

    
7355
class LUConnectConsole(NoHooksLU):
7356
  """Connect to an instance's console.
7357

7358
  This is somewhat special in that it returns the command line that
7359
  you need to run on the master node in order to connect to the
7360
  console.
7361

7362
  """
7363
  _OP_PARAMS = [
7364
    _PInstanceName
7365
    ]
7366
  REQ_BGL = False
7367

    
7368
  def ExpandNames(self):
7369
    self._ExpandAndLockInstance()
7370

    
7371
  def CheckPrereq(self):
7372
    """Check prerequisites.
7373

7374
    This checks that the instance is in the cluster.
7375

7376
    """
7377
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7378
    assert self.instance is not None, \
7379
      "Cannot retrieve locked instance %s" % self.op.instance_name
7380
    _CheckNodeOnline(self, self.instance.primary_node)
7381

    
7382
  def Exec(self, feedback_fn):
7383
    """Connect to the console of an instance
7384

7385
    """
7386
    instance = self.instance
7387
    node = instance.primary_node
7388

    
7389
    node_insts = self.rpc.call_instance_list([node],
7390
                                             [instance.hypervisor])[node]
7391
    node_insts.Raise("Can't get node information from %s" % node)
7392

    
7393
    if instance.name not in node_insts.payload:
7394
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7395

    
7396
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7397

    
7398
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7399
    cluster = self.cfg.GetClusterInfo()
7400
    # beparams and hvparams are passed separately, to avoid editing the
7401
    # instance and then saving the defaults in the instance itself.
7402
    hvparams = cluster.FillHV(instance)
7403
    beparams = cluster.FillBE(instance)
7404
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7405

    
7406
    # build ssh cmdline
7407
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7408

    
7409

    
7410
class LUReplaceDisks(LogicalUnit):
7411
  """Replace the disks of an instance.
7412

7413
  """
7414
  HPATH = "mirrors-replace"
7415
  HTYPE = constants.HTYPE_INSTANCE
7416
  _OP_PARAMS = [
7417
    _PInstanceName,
7418
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7419
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7420
    ("remote_node", None, _TMaybeString),
7421
    ("iallocator", None, _TMaybeString),
7422
    ("early_release", False, _TBool),
7423
    ]
7424
  REQ_BGL = False
7425

    
7426
  def CheckArguments(self):
7427
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7428
                                  self.op.iallocator)
7429

    
7430
  def ExpandNames(self):
7431
    self._ExpandAndLockInstance()
7432

    
7433
    if self.op.iallocator is not None:
7434
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7435

    
7436
    elif self.op.remote_node is not None:
7437
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7438
      self.op.remote_node = remote_node
7439

    
7440
      # Warning: do not remove the locking of the new secondary here
7441
      # unless DRBD8.AddChildren is changed to work in parallel;
7442
      # currently it doesn't since parallel invocations of
7443
      # FindUnusedMinor will conflict
7444
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7445
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7446

    
7447
    else:
7448
      self.needed_locks[locking.LEVEL_NODE] = []
7449
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7450

    
7451
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7452
                                   self.op.iallocator, self.op.remote_node,
7453
                                   self.op.disks, False, self.op.early_release)
7454

    
7455
    self.tasklets = [self.replacer]
7456

    
7457
  def DeclareLocks(self, level):
7458
    # If we're not already locking all nodes in the set we have to declare the
7459
    # instance's primary/secondary nodes.
7460
    if (level == locking.LEVEL_NODE and
7461
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7462
      self._LockInstancesNodes()
7463

    
7464
  def BuildHooksEnv(self):
7465
    """Build hooks env.
7466

7467
    This runs on the master, the primary and all the secondaries.
7468

7469
    """
7470
    instance = self.replacer.instance
7471
    env = {
7472
      "MODE": self.op.mode,
7473
      "NEW_SECONDARY": self.op.remote_node,
7474
      "OLD_SECONDARY": instance.secondary_nodes[0],
7475
      }
7476
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7477
    nl = [
7478
      self.cfg.GetMasterNode(),
7479
      instance.primary_node,
7480
      ]
7481
    if self.op.remote_node is not None:
7482
      nl.append(self.op.remote_node)
7483
    return env, nl, nl
7484

    
7485

    
7486
class TLReplaceDisks(Tasklet):
7487
  """Replaces disks for an instance.
7488

7489
  Note: Locking is not within the scope of this class.
7490

7491
  """
7492
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7493
               disks, delay_iallocator, early_release):
7494
    """Initializes this class.
7495

7496
    """
7497
    Tasklet.__init__(self, lu)
7498

    
7499
    # Parameters
7500
    self.instance_name = instance_name
7501
    self.mode = mode
7502
    self.iallocator_name = iallocator_name
7503
    self.remote_node = remote_node
7504
    self.disks = disks
7505
    self.delay_iallocator = delay_iallocator
7506
    self.early_release = early_release
7507

    
7508
    # Runtime data
7509
    self.instance = None
7510
    self.new_node = None
7511
    self.target_node = None
7512
    self.other_node = None
7513
    self.remote_node_info = None
7514
    self.node_secondary_ip = None
7515

    
7516
  @staticmethod
7517
  def CheckArguments(mode, remote_node, iallocator):
7518
    """Helper function for users of this class.
7519

7520
    """
7521
    # check for valid parameter combination
7522
    if mode == constants.REPLACE_DISK_CHG:
7523
      if remote_node is None and iallocator is None:
7524
        raise errors.OpPrereqError("When changing the secondary either an"
7525
                                   " iallocator script must be used or the"
7526
                                   " new node given", errors.ECODE_INVAL)
7527

    
7528
      if remote_node is not None and iallocator is not None:
7529
        raise errors.OpPrereqError("Give either the iallocator or the new"
7530
                                   " secondary, not both", errors.ECODE_INVAL)
7531

    
7532
    elif remote_node is not None or iallocator is not None:
7533
      # Not replacing the secondary
7534
      raise errors.OpPrereqError("The iallocator and new node options can"
7535
                                 " only be used when changing the"
7536
                                 " secondary node", errors.ECODE_INVAL)
7537

    
7538
  @staticmethod
7539
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7540
    """Compute a new secondary node using an IAllocator.
7541

7542
    """
7543
    ial = IAllocator(lu.cfg, lu.rpc,
7544
                     mode=constants.IALLOCATOR_MODE_RELOC,
7545
                     name=instance_name,
7546
                     relocate_from=relocate_from)
7547

    
7548
    ial.Run(iallocator_name)
7549

    
7550
    if not ial.success:
7551
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7552
                                 " %s" % (iallocator_name, ial.info),
7553
                                 errors.ECODE_NORES)
7554

    
7555
    if len(ial.result) != ial.required_nodes:
7556
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7557
                                 " of nodes (%s), required %s" %
7558
                                 (iallocator_name,
7559
                                  len(ial.result), ial.required_nodes),
7560
                                 errors.ECODE_FAULT)
7561

    
7562
    remote_node_name = ial.result[0]
7563

    
7564
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7565
               instance_name, remote_node_name)
7566

    
7567
    return remote_node_name
7568

    
7569
  def _FindFaultyDisks(self, node_name):
7570
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7571
                                    node_name, True)
7572

    
7573
  def CheckPrereq(self):
7574
    """Check prerequisites.
7575

7576
    This checks that the instance is in the cluster.
7577

7578
    """
7579
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7580
    assert instance is not None, \
7581
      "Cannot retrieve locked instance %s" % self.instance_name
7582

    
7583
    if instance.disk_template != constants.DT_DRBD8:
7584
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7585
                                 " instances", errors.ECODE_INVAL)
7586

    
7587
    if len(instance.secondary_nodes) != 1:
7588
      raise errors.OpPrereqError("The instance has a strange layout,"
7589
                                 " expected one secondary but found %d" %
7590
                                 len(instance.secondary_nodes),
7591
                                 errors.ECODE_FAULT)
7592

    
7593
    if not self.delay_iallocator:
7594
      self._CheckPrereq2()
7595

    
7596
  def _CheckPrereq2(self):
7597
    """Check prerequisites, second part.
7598

7599
    This function should always be part of CheckPrereq. It was separated and is
7600
    now called from Exec because during node evacuation iallocator was only
7601
    called with an unmodified cluster model, not taking planned changes into
7602
    account.
7603

7604
    """
7605
    instance = self.instance
7606
    secondary_node = instance.secondary_nodes[0]
7607

    
7608
    if self.iallocator_name is None:
7609
      remote_node = self.remote_node
7610
    else:
7611
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7612
                                       instance.name, instance.secondary_nodes)
7613

    
7614
    if remote_node is not None:
7615
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7616
      assert self.remote_node_info is not None, \
7617
        "Cannot retrieve locked node %s" % remote_node
7618
    else:
7619
      self.remote_node_info = None
7620

    
7621
    if remote_node == self.instance.primary_node:
7622
      raise errors.OpPrereqError("The specified node is the primary node of"
7623
                                 " the instance.", errors.ECODE_INVAL)
7624

    
7625
    if remote_node == secondary_node:
7626
      raise errors.OpPrereqError("The specified node is already the"
7627
                                 " secondary node of the instance.",
7628
                                 errors.ECODE_INVAL)
7629

    
7630
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7631
                                    constants.REPLACE_DISK_CHG):
7632
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7633
                                 errors.ECODE_INVAL)
7634

    
7635
    if self.mode == constants.REPLACE_DISK_AUTO:
7636
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7637
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7638

    
7639
      if faulty_primary and faulty_secondary:
7640
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7641
                                   " one node and can not be repaired"
7642
                                   " automatically" % self.instance_name,
7643
                                   errors.ECODE_STATE)
7644

    
7645
      if faulty_primary:
7646
        self.disks = faulty_primary
7647
        self.target_node = instance.primary_node
7648
        self.other_node = secondary_node
7649
        check_nodes = [self.target_node, self.other_node]
7650
      elif faulty_secondary:
7651
        self.disks = faulty_secondary
7652
        self.target_node = secondary_node
7653
        self.other_node = instance.primary_node
7654
        check_nodes = [self.target_node, self.other_node]
7655
      else:
7656
        self.disks = []
7657
        check_nodes = []
7658

    
7659
    else:
7660
      # Non-automatic modes
7661
      if self.mode == constants.REPLACE_DISK_PRI:
7662
        self.target_node = instance.primary_node
7663
        self.other_node = secondary_node
7664
        check_nodes = [self.target_node, self.other_node]
7665

    
7666
      elif self.mode == constants.REPLACE_DISK_SEC:
7667
        self.target_node = secondary_node
7668
        self.other_node = instance.primary_node
7669
        check_nodes = [self.target_node, self.other_node]
7670

    
7671
      elif self.mode == constants.REPLACE_DISK_CHG:
7672
        self.new_node = remote_node
7673
        self.other_node = instance.primary_node
7674
        self.target_node = secondary_node
7675
        check_nodes = [self.new_node, self.other_node]
7676

    
7677
        _CheckNodeNotDrained(self.lu, remote_node)
7678

    
7679
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7680
        assert old_node_info is not None
7681
        if old_node_info.offline and not self.early_release:
7682
          # doesn't make sense to delay the release
7683
          self.early_release = True
7684
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7685
                          " early-release mode", secondary_node)
7686

    
7687
      else:
7688
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7689
                                     self.mode)
7690

    
7691
      # If not specified all disks should be replaced
7692
      if not self.disks:
7693
        self.disks = range(len(self.instance.disks))
7694

    
7695
    for node in check_nodes:
7696
      _CheckNodeOnline(self.lu, node)
7697

    
7698
    # Check whether disks are valid
7699
    for disk_idx in self.disks:
7700
      instance.FindDisk(disk_idx)
7701

    
7702
    # Get secondary node IP addresses
7703
    node_2nd_ip = {}
7704

    
7705
    for node_name in [self.target_node, self.other_node, self.new_node]:
7706
      if node_name is not None:
7707
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7708

    
7709
    self.node_secondary_ip = node_2nd_ip
7710

    
7711
  def Exec(self, feedback_fn):
7712
    """Execute disk replacement.
7713

7714
    This dispatches the disk replacement to the appropriate handler.
7715

7716
    """
7717
    if self.delay_iallocator:
7718
      self._CheckPrereq2()
7719

    
7720
    if not self.disks:
7721
      feedback_fn("No disks need replacement")
7722
      return
7723

    
7724
    feedback_fn("Replacing disk(s) %s for %s" %
7725
                (utils.CommaJoin(self.disks), self.instance.name))
7726

    
7727
    activate_disks = (not self.instance.admin_up)
7728

    
7729
    # Activate the instance disks if we're replacing them on a down instance
7730
    if activate_disks:
7731
      _StartInstanceDisks(self.lu, self.instance, True)
7732

    
7733
    try:
7734
      # Should we replace the secondary node?
7735
      if self.new_node is not None:
7736
        fn = self._ExecDrbd8Secondary
7737
      else:
7738
        fn = self._ExecDrbd8DiskOnly
7739

    
7740
      return fn(feedback_fn)
7741

    
7742
    finally:
7743
      # Deactivate the instance disks if we're replacing them on a
7744
      # down instance
7745
      if activate_disks:
7746
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7747

    
7748
  def _CheckVolumeGroup(self, nodes):
7749
    self.lu.LogInfo("Checking volume groups")
7750

    
7751
    vgname = self.cfg.GetVGName()
7752

    
7753
    # Make sure volume group exists on all involved nodes
7754
    results = self.rpc.call_vg_list(nodes)
7755
    if not results:
7756
      raise errors.OpExecError("Can't list volume groups on the nodes")
7757

    
7758
    for node in nodes:
7759
      res = results[node]
7760
      res.Raise("Error checking node %s" % node)
7761
      if vgname not in res.payload:
7762
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7763
                                 (vgname, node))
7764

    
7765
  def _CheckDisksExistence(self, nodes):
7766
    # Check disk existence
7767
    for idx, dev in enumerate(self.instance.disks):
7768
      if idx not in self.disks:
7769
        continue
7770

    
7771
      for node in nodes:
7772
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7773
        self.cfg.SetDiskID(dev, node)
7774

    
7775
        result = self.rpc.call_blockdev_find(node, dev)
7776

    
7777
        msg = result.fail_msg
7778
        if msg or not result.payload:
7779
          if not msg:
7780
            msg = "disk not found"
7781
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7782
                                   (idx, node, msg))
7783

    
7784
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7785
    for idx, dev in enumerate(self.instance.disks):
7786
      if idx not in self.disks:
7787
        continue
7788

    
7789
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7790
                      (idx, node_name))
7791

    
7792
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7793
                                   ldisk=ldisk):
7794
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7795
                                 " replace disks for instance %s" %
7796
                                 (node_name, self.instance.name))
7797

    
7798
  def _CreateNewStorage(self, node_name):
7799
    vgname = self.cfg.GetVGName()
7800
    iv_names = {}
7801

    
7802
    for idx, dev in enumerate(self.instance.disks):
7803
      if idx not in self.disks:
7804
        continue
7805

    
7806
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7807

    
7808
      self.cfg.SetDiskID(dev, node_name)
7809

    
7810
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7811
      names = _GenerateUniqueNames(self.lu, lv_names)
7812

    
7813
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7814
                             logical_id=(vgname, names[0]))
7815
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7816
                             logical_id=(vgname, names[1]))
7817

    
7818
      new_lvs = [lv_data, lv_meta]
7819
      old_lvs = dev.children
7820
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7821

    
7822
      # we pass force_create=True to force the LVM creation
7823
      for new_lv in new_lvs:
7824
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7825
                        _GetInstanceInfoText(self.instance), False)
7826

    
7827
    return iv_names
7828

    
7829
  def _CheckDevices(self, node_name, iv_names):
7830
    for name, (dev, _, _) in iv_names.iteritems():
7831
      self.cfg.SetDiskID(dev, node_name)
7832

    
7833
      result = self.rpc.call_blockdev_find(node_name, dev)
7834

    
7835
      msg = result.fail_msg
7836
      if msg or not result.payload:
7837
        if not msg:
7838
          msg = "disk not found"
7839
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7840
                                 (name, msg))
7841

    
7842
      if result.payload.is_degraded:
7843
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7844

    
7845
  def _RemoveOldStorage(self, node_name, iv_names):
7846
    for name, (_, old_lvs, _) in iv_names.iteritems():
7847
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7848

    
7849
      for lv in old_lvs:
7850
        self.cfg.SetDiskID(lv, node_name)
7851

    
7852
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7853
        if msg:
7854
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7855
                             hint="remove unused LVs manually")
7856

    
7857
  def _ReleaseNodeLock(self, node_name):
7858
    """Releases the lock for a given node."""
7859
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7860

    
7861
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7862
    """Replace a disk on the primary or secondary for DRBD 8.
7863

7864
    The algorithm for replace is quite complicated:
7865

7866
      1. for each disk to be replaced:
7867

7868
        1. create new LVs on the target node with unique names
7869
        1. detach old LVs from the drbd device
7870
        1. rename old LVs to name_replaced.<time_t>
7871
        1. rename new LVs to old LVs
7872
        1. attach the new LVs (with the old names now) to the drbd device
7873

7874
      1. wait for sync across all devices
7875

7876
      1. for each modified disk:
7877

7878
        1. remove old LVs (which have the name name_replaces.<time_t>)
7879

7880
    Failures are not very well handled.
7881

7882
    """
7883
    steps_total = 6
7884

    
7885
    # Step: check device activation
7886
    self.lu.LogStep(1, steps_total, "Check device existence")
7887
    self._CheckDisksExistence([self.other_node, self.target_node])
7888
    self._CheckVolumeGroup([self.target_node, self.other_node])
7889

    
7890
    # Step: check other node consistency
7891
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7892
    self._CheckDisksConsistency(self.other_node,
7893
                                self.other_node == self.instance.primary_node,
7894
                                False)
7895

    
7896
    # Step: create new storage
7897
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7898
    iv_names = self._CreateNewStorage(self.target_node)
7899

    
7900
    # Step: for each lv, detach+rename*2+attach
7901
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7902
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7903
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7904

    
7905
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7906
                                                     old_lvs)
7907
      result.Raise("Can't detach drbd from local storage on node"
7908
                   " %s for device %s" % (self.target_node, dev.iv_name))
7909
      #dev.children = []
7910
      #cfg.Update(instance)
7911

    
7912
      # ok, we created the new LVs, so now we know we have the needed
7913
      # storage; as such, we proceed on the target node to rename
7914
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7915
      # using the assumption that logical_id == physical_id (which in
7916
      # turn is the unique_id on that node)
7917

    
7918
      # FIXME(iustin): use a better name for the replaced LVs
7919
      temp_suffix = int(time.time())
7920
      ren_fn = lambda d, suff: (d.physical_id[0],
7921
                                d.physical_id[1] + "_replaced-%s" % suff)
7922

    
7923
      # Build the rename list based on what LVs exist on the node
7924
      rename_old_to_new = []
7925
      for to_ren in old_lvs:
7926
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7927
        if not result.fail_msg and result.payload:
7928
          # device exists
7929
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7930

    
7931
      self.lu.LogInfo("Renaming the old LVs on the target node")
7932
      result = self.rpc.call_blockdev_rename(self.target_node,
7933
                                             rename_old_to_new)
7934
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7935

    
7936
      # Now we rename the new LVs to the old LVs
7937
      self.lu.LogInfo("Renaming the new LVs on the target node")
7938
      rename_new_to_old = [(new, old.physical_id)
7939
                           for old, new in zip(old_lvs, new_lvs)]
7940
      result = self.rpc.call_blockdev_rename(self.target_node,
7941
                                             rename_new_to_old)
7942
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7943

    
7944
      for old, new in zip(old_lvs, new_lvs):
7945
        new.logical_id = old.logical_id
7946
        self.cfg.SetDiskID(new, self.target_node)
7947

    
7948
      for disk in old_lvs:
7949
        disk.logical_id = ren_fn(disk, temp_suffix)
7950
        self.cfg.SetDiskID(disk, self.target_node)
7951

    
7952
      # Now that the new lvs have the old name, we can add them to the device
7953
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7954
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7955
                                                  new_lvs)
7956
      msg = result.fail_msg
7957
      if msg:
7958
        for new_lv in new_lvs:
7959
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7960
                                               new_lv).fail_msg
7961
          if msg2:
7962
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7963
                               hint=("cleanup manually the unused logical"
7964
                                     "volumes"))
7965
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7966

    
7967
      dev.children = new_lvs
7968

    
7969
      self.cfg.Update(self.instance, feedback_fn)
7970

    
7971
    cstep = 5
7972
    if self.early_release:
7973
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7974
      cstep += 1
7975
      self._RemoveOldStorage(self.target_node, iv_names)
7976
      # WARNING: we release both node locks here, do not do other RPCs
7977
      # than WaitForSync to the primary node
7978
      self._ReleaseNodeLock([self.target_node, self.other_node])
7979

    
7980
    # Wait for sync
7981
    # This can fail as the old devices are degraded and _WaitForSync
7982
    # does a combined result over all disks, so we don't check its return value
7983
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7984
    cstep += 1
7985
    _WaitForSync(self.lu, self.instance)
7986

    
7987
    # Check all devices manually
7988
    self._CheckDevices(self.instance.primary_node, iv_names)
7989

    
7990
    # Step: remove old storage
7991
    if not self.early_release:
7992
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7993
      cstep += 1
7994
      self._RemoveOldStorage(self.target_node, iv_names)
7995

    
7996
  def _ExecDrbd8Secondary(self, feedback_fn):
7997
    """Replace the secondary node for DRBD 8.
7998

7999
    The algorithm for replace is quite complicated:
8000
      - for all disks of the instance:
8001
        - create new LVs on the new node with same names
8002
        - shutdown the drbd device on the old secondary
8003
        - disconnect the drbd network on the primary
8004
        - create the drbd device on the new secondary
8005
        - network attach the drbd on the primary, using an artifice:
8006
          the drbd code for Attach() will connect to the network if it
8007
          finds a device which is connected to the good local disks but
8008
          not network enabled
8009
      - wait for sync across all devices
8010
      - remove all disks from the old secondary
8011

8012
    Failures are not very well handled.
8013

8014
    """
8015
    steps_total = 6
8016

    
8017
    # Step: check device activation
8018
    self.lu.LogStep(1, steps_total, "Check device existence")
8019
    self._CheckDisksExistence([self.instance.primary_node])
8020
    self._CheckVolumeGroup([self.instance.primary_node])
8021

    
8022
    # Step: check other node consistency
8023
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8024
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8025

    
8026
    # Step: create new storage
8027
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8028
    for idx, dev in enumerate(self.instance.disks):
8029
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8030
                      (self.new_node, idx))
8031
      # we pass force_create=True to force LVM creation
8032
      for new_lv in dev.children:
8033
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8034
                        _GetInstanceInfoText(self.instance), False)
8035

    
8036
    # Step 4: dbrd minors and drbd setups changes
8037
    # after this, we must manually remove the drbd minors on both the
8038
    # error and the success paths
8039
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8040
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8041
                                         for dev in self.instance.disks],
8042
                                        self.instance.name)
8043
    logging.debug("Allocated minors %r", minors)
8044

    
8045
    iv_names = {}
8046
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8047
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8048
                      (self.new_node, idx))
8049
      # create new devices on new_node; note that we create two IDs:
8050
      # one without port, so the drbd will be activated without
8051
      # networking information on the new node at this stage, and one
8052
      # with network, for the latter activation in step 4
8053
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8054
      if self.instance.primary_node == o_node1:
8055
        p_minor = o_minor1
8056
      else:
8057
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8058
        p_minor = o_minor2
8059

    
8060
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8061
                      p_minor, new_minor, o_secret)
8062
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8063
                    p_minor, new_minor, o_secret)
8064

    
8065
      iv_names[idx] = (dev, dev.children, new_net_id)
8066
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8067
                    new_net_id)
8068
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8069
                              logical_id=new_alone_id,
8070
                              children=dev.children,
8071
                              size=dev.size)
8072
      try:
8073
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8074
                              _GetInstanceInfoText(self.instance), False)
8075
      except errors.GenericError:
8076
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8077
        raise
8078

    
8079
    # We have new devices, shutdown the drbd on the old secondary
8080
    for idx, dev in enumerate(self.instance.disks):
8081
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8082
      self.cfg.SetDiskID(dev, self.target_node)
8083
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8084
      if msg:
8085
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8086
                           "node: %s" % (idx, msg),
8087
                           hint=("Please cleanup this device manually as"
8088
                                 " soon as possible"))
8089

    
8090
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8091
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8092
                                               self.node_secondary_ip,
8093
                                               self.instance.disks)\
8094
                                              [self.instance.primary_node]
8095

    
8096
    msg = result.fail_msg
8097
    if msg:
8098
      # detaches didn't succeed (unlikely)
8099
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8100
      raise errors.OpExecError("Can't detach the disks from the network on"
8101
                               " old node: %s" % (msg,))
8102

    
8103
    # if we managed to detach at least one, we update all the disks of
8104
    # the instance to point to the new secondary
8105
    self.lu.LogInfo("Updating instance configuration")
8106
    for dev, _, new_logical_id in iv_names.itervalues():
8107
      dev.logical_id = new_logical_id
8108
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8109

    
8110
    self.cfg.Update(self.instance, feedback_fn)
8111

    
8112
    # and now perform the drbd attach
8113
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8114
                    " (standalone => connected)")
8115
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8116
                                            self.new_node],
8117
                                           self.node_secondary_ip,
8118
                                           self.instance.disks,
8119
                                           self.instance.name,
8120
                                           False)
8121
    for to_node, to_result in result.items():
8122
      msg = to_result.fail_msg
8123
      if msg:
8124
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8125
                           to_node, msg,
8126
                           hint=("please do a gnt-instance info to see the"
8127
                                 " status of disks"))
8128
    cstep = 5
8129
    if self.early_release:
8130
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8131
      cstep += 1
8132
      self._RemoveOldStorage(self.target_node, iv_names)
8133
      # WARNING: we release all node locks here, do not do other RPCs
8134
      # than WaitForSync to the primary node
8135
      self._ReleaseNodeLock([self.instance.primary_node,
8136
                             self.target_node,
8137
                             self.new_node])
8138

    
8139
    # Wait for sync
8140
    # This can fail as the old devices are degraded and _WaitForSync
8141
    # does a combined result over all disks, so we don't check its return value
8142
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8143
    cstep += 1
8144
    _WaitForSync(self.lu, self.instance)
8145

    
8146
    # Check all devices manually
8147
    self._CheckDevices(self.instance.primary_node, iv_names)
8148

    
8149
    # Step: remove old storage
8150
    if not self.early_release:
8151
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8152
      self._RemoveOldStorage(self.target_node, iv_names)
8153

    
8154

    
8155
class LURepairNodeStorage(NoHooksLU):
8156
  """Repairs the volume group on a node.
8157

8158
  """
8159
  _OP_PARAMS = [
8160
    _PNodeName,
8161
    ("storage_type", _NoDefault, _CheckStorageType),
8162
    ("name", _NoDefault, _TNonEmptyString),
8163
    ("ignore_consistency", False, _TBool),
8164
    ]
8165
  REQ_BGL = False
8166

    
8167
  def CheckArguments(self):
8168
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8169

    
8170
    storage_type = self.op.storage_type
8171

    
8172
    if (constants.SO_FIX_CONSISTENCY not in
8173
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8174
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8175
                                 " repaired" % storage_type,
8176
                                 errors.ECODE_INVAL)
8177

    
8178
  def ExpandNames(self):
8179
    self.needed_locks = {
8180
      locking.LEVEL_NODE: [self.op.node_name],
8181
      }
8182

    
8183
  def _CheckFaultyDisks(self, instance, node_name):
8184
    """Ensure faulty disks abort the opcode or at least warn."""
8185
    try:
8186
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8187
                                  node_name, True):
8188
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8189
                                   " node '%s'" % (instance.name, node_name),
8190
                                   errors.ECODE_STATE)
8191
    except errors.OpPrereqError, err:
8192
      if self.op.ignore_consistency:
8193
        self.proc.LogWarning(str(err.args[0]))
8194
      else:
8195
        raise
8196

    
8197
  def CheckPrereq(self):
8198
    """Check prerequisites.
8199

8200
    """
8201
    # Check whether any instance on this node has faulty disks
8202
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8203
      if not inst.admin_up:
8204
        continue
8205
      check_nodes = set(inst.all_nodes)
8206
      check_nodes.discard(self.op.node_name)
8207
      for inst_node_name in check_nodes:
8208
        self._CheckFaultyDisks(inst, inst_node_name)
8209

    
8210
  def Exec(self, feedback_fn):
8211
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8212
                (self.op.name, self.op.node_name))
8213

    
8214
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8215
    result = self.rpc.call_storage_execute(self.op.node_name,
8216
                                           self.op.storage_type, st_args,
8217
                                           self.op.name,
8218
                                           constants.SO_FIX_CONSISTENCY)
8219
    result.Raise("Failed to repair storage unit '%s' on %s" %
8220
                 (self.op.name, self.op.node_name))
8221

    
8222

    
8223
class LUNodeEvacuationStrategy(NoHooksLU):
8224
  """Computes the node evacuation strategy.
8225

8226
  """
8227
  _OP_PARAMS = [
8228
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8229
    ("remote_node", None, _TMaybeString),
8230
    ("iallocator", None, _TMaybeString),
8231
    ]
8232
  REQ_BGL = False
8233

    
8234
  def CheckArguments(self):
8235
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8236

    
8237
  def ExpandNames(self):
8238
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8239
    self.needed_locks = locks = {}
8240
    if self.op.remote_node is None:
8241
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8242
    else:
8243
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8244
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8245

    
8246
  def Exec(self, feedback_fn):
8247
    if self.op.remote_node is not None:
8248
      instances = []
8249
      for node in self.op.nodes:
8250
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8251
      result = []
8252
      for i in instances:
8253
        if i.primary_node == self.op.remote_node:
8254
          raise errors.OpPrereqError("Node %s is the primary node of"
8255
                                     " instance %s, cannot use it as"
8256
                                     " secondary" %
8257
                                     (self.op.remote_node, i.name),
8258
                                     errors.ECODE_INVAL)
8259
        result.append([i.name, self.op.remote_node])
8260
    else:
8261
      ial = IAllocator(self.cfg, self.rpc,
8262
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8263
                       evac_nodes=self.op.nodes)
8264
      ial.Run(self.op.iallocator, validate=True)
8265
      if not ial.success:
8266
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8267
                                 errors.ECODE_NORES)
8268
      result = ial.result
8269
    return result
8270

    
8271

    
8272
class LUGrowDisk(LogicalUnit):
8273
  """Grow a disk of an instance.
8274

8275
  """
8276
  HPATH = "disk-grow"
8277
  HTYPE = constants.HTYPE_INSTANCE
8278
  _OP_PARAMS = [
8279
    _PInstanceName,
8280
    ("disk", _NoDefault, _TInt),
8281
    ("amount", _NoDefault, _TInt),
8282
    ("wait_for_sync", True, _TBool),
8283
    ]
8284
  REQ_BGL = False
8285

    
8286
  def ExpandNames(self):
8287
    self._ExpandAndLockInstance()
8288
    self.needed_locks[locking.LEVEL_NODE] = []
8289
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8290

    
8291
  def DeclareLocks(self, level):
8292
    if level == locking.LEVEL_NODE:
8293
      self._LockInstancesNodes()
8294

    
8295
  def BuildHooksEnv(self):
8296
    """Build hooks env.
8297

8298
    This runs on the master, the primary and all the secondaries.
8299

8300
    """
8301
    env = {
8302
      "DISK": self.op.disk,
8303
      "AMOUNT": self.op.amount,
8304
      }
8305
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8306
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8307
    return env, nl, nl
8308

    
8309
  def CheckPrereq(self):
8310
    """Check prerequisites.
8311

8312
    This checks that the instance is in the cluster.
8313

8314
    """
8315
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8316
    assert instance is not None, \
8317
      "Cannot retrieve locked instance %s" % self.op.instance_name
8318
    nodenames = list(instance.all_nodes)
8319
    for node in nodenames:
8320
      _CheckNodeOnline(self, node)
8321

    
8322
    self.instance = instance
8323

    
8324
    if instance.disk_template not in constants.DTS_GROWABLE:
8325
      raise errors.OpPrereqError("Instance's disk layout does not support"
8326
                                 " growing.", errors.ECODE_INVAL)
8327

    
8328
    self.disk = instance.FindDisk(self.op.disk)
8329

    
8330
    if instance.disk_template != constants.DT_FILE:
8331
      # TODO: check the free disk space for file, when that feature will be
8332
      # supported
8333
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8334

    
8335
  def Exec(self, feedback_fn):
8336
    """Execute disk grow.
8337

8338
    """
8339
    instance = self.instance
8340
    disk = self.disk
8341

    
8342
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8343
    if not disks_ok:
8344
      raise errors.OpExecError("Cannot activate block device to grow")
8345

    
8346
    for node in instance.all_nodes:
8347
      self.cfg.SetDiskID(disk, node)
8348
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8349
      result.Raise("Grow request failed to node %s" % node)
8350

    
8351
      # TODO: Rewrite code to work properly
8352
      # DRBD goes into sync mode for a short amount of time after executing the
8353
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8354
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8355
      # time is a work-around.
8356
      time.sleep(5)
8357

    
8358
    disk.RecordGrow(self.op.amount)
8359
    self.cfg.Update(instance, feedback_fn)
8360
    if self.op.wait_for_sync:
8361
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8362
      if disk_abort:
8363
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8364
                             " status.\nPlease check the instance.")
8365
      if not instance.admin_up:
8366
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8367
    elif not instance.admin_up:
8368
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8369
                           " not supposed to be running because no wait for"
8370
                           " sync mode was requested.")
8371

    
8372

    
8373
class LUQueryInstanceData(NoHooksLU):
8374
  """Query runtime instance data.
8375

8376
  """
8377
  _OP_PARAMS = [
8378
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8379
    ("static", False, _TBool),
8380
    ]
8381
  REQ_BGL = False
8382

    
8383
  def ExpandNames(self):
8384
    self.needed_locks = {}
8385
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8386

    
8387
    if self.op.instances:
8388
      self.wanted_names = []
8389
      for name in self.op.instances:
8390
        full_name = _ExpandInstanceName(self.cfg, name)
8391
        self.wanted_names.append(full_name)
8392
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8393
    else:
8394
      self.wanted_names = None
8395
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8396

    
8397
    self.needed_locks[locking.LEVEL_NODE] = []
8398
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8399

    
8400
  def DeclareLocks(self, level):
8401
    if level == locking.LEVEL_NODE:
8402
      self._LockInstancesNodes()
8403

    
8404
  def CheckPrereq(self):
8405
    """Check prerequisites.
8406

8407
    This only checks the optional instance list against the existing names.
8408

8409
    """
8410
    if self.wanted_names is None:
8411
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8412

    
8413
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8414
                             in self.wanted_names]
8415

    
8416
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8417
    """Returns the status of a block device
8418

8419
    """
8420
    if self.op.static or not node:
8421
      return None
8422

    
8423
    self.cfg.SetDiskID(dev, node)
8424

    
8425
    result = self.rpc.call_blockdev_find(node, dev)
8426
    if result.offline:
8427
      return None
8428

    
8429
    result.Raise("Can't compute disk status for %s" % instance_name)
8430

    
8431
    status = result.payload
8432
    if status is None:
8433
      return None
8434

    
8435
    return (status.dev_path, status.major, status.minor,
8436
            status.sync_percent, status.estimated_time,
8437
            status.is_degraded, status.ldisk_status)
8438

    
8439
  def _ComputeDiskStatus(self, instance, snode, dev):
8440
    """Compute block device status.
8441

8442
    """
8443
    if dev.dev_type in constants.LDS_DRBD:
8444
      # we change the snode then (otherwise we use the one passed in)
8445
      if dev.logical_id[0] == instance.primary_node:
8446
        snode = dev.logical_id[1]
8447
      else:
8448
        snode = dev.logical_id[0]
8449

    
8450
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8451
                                              instance.name, dev)
8452
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8453

    
8454
    if dev.children:
8455
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8456
                      for child in dev.children]
8457
    else:
8458
      dev_children = []
8459

    
8460
    data = {
8461
      "iv_name": dev.iv_name,
8462
      "dev_type": dev.dev_type,
8463
      "logical_id": dev.logical_id,
8464
      "physical_id": dev.physical_id,
8465
      "pstatus": dev_pstatus,
8466
      "sstatus": dev_sstatus,
8467
      "children": dev_children,
8468
      "mode": dev.mode,
8469
      "size": dev.size,
8470
      }
8471

    
8472
    return data
8473

    
8474
  def Exec(self, feedback_fn):
8475
    """Gather and return data"""
8476
    result = {}
8477

    
8478
    cluster = self.cfg.GetClusterInfo()
8479

    
8480
    for instance in self.wanted_instances:
8481
      if not self.op.static:
8482
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8483
                                                  instance.name,
8484
                                                  instance.hypervisor)
8485
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8486
        remote_info = remote_info.payload
8487
        if remote_info and "state" in remote_info:
8488
          remote_state = "up"
8489
        else:
8490
          remote_state = "down"
8491
      else:
8492
        remote_state = None
8493
      if instance.admin_up:
8494
        config_state = "up"
8495
      else:
8496
        config_state = "down"
8497

    
8498
      disks = [self._ComputeDiskStatus(instance, None, device)
8499
               for device in instance.disks]
8500

    
8501
      idict = {
8502
        "name": instance.name,
8503
        "config_state": config_state,
8504
        "run_state": remote_state,
8505
        "pnode": instance.primary_node,
8506
        "snodes": instance.secondary_nodes,
8507
        "os": instance.os,
8508
        # this happens to be the same format used for hooks
8509
        "nics": _NICListToTuple(self, instance.nics),
8510
        "disk_template": instance.disk_template,
8511
        "disks": disks,
8512
        "hypervisor": instance.hypervisor,
8513
        "network_port": instance.network_port,
8514
        "hv_instance": instance.hvparams,
8515
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8516
        "be_instance": instance.beparams,
8517
        "be_actual": cluster.FillBE(instance),
8518
        "os_instance": instance.osparams,
8519
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8520
        "serial_no": instance.serial_no,
8521
        "mtime": instance.mtime,
8522
        "ctime": instance.ctime,
8523
        "uuid": instance.uuid,
8524
        }
8525

    
8526
      result[instance.name] = idict
8527

    
8528
    return result
8529

    
8530

    
8531
class LUSetInstanceParams(LogicalUnit):
8532
  """Modifies an instances's parameters.
8533

8534
  """
8535
  HPATH = "instance-modify"
8536
  HTYPE = constants.HTYPE_INSTANCE
8537
  _OP_PARAMS = [
8538
    _PInstanceName,
8539
    ("nics", _EmptyList, _TList),
8540
    ("disks", _EmptyList, _TList),
8541
    ("beparams", _EmptyDict, _TDict),
8542
    ("hvparams", _EmptyDict, _TDict),
8543
    ("disk_template", None, _TMaybeString),
8544
    ("remote_node", None, _TMaybeString),
8545
    ("os_name", None, _TMaybeString),
8546
    ("force_variant", False, _TBool),
8547
    ("osparams", None, _TOr(_TDict, _TNone)),
8548
    _PForce,
8549
    ]
8550
  REQ_BGL = False
8551

    
8552
  def CheckArguments(self):
8553
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8554
            self.op.hvparams or self.op.beparams or self.op.os_name):
8555
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8556

    
8557
    if self.op.hvparams:
8558
      _CheckGlobalHvParams(self.op.hvparams)
8559

    
8560
    # Disk validation
8561
    disk_addremove = 0
8562
    for disk_op, disk_dict in self.op.disks:
8563
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8564
      if disk_op == constants.DDM_REMOVE:
8565
        disk_addremove += 1
8566
        continue
8567
      elif disk_op == constants.DDM_ADD:
8568
        disk_addremove += 1
8569
      else:
8570
        if not isinstance(disk_op, int):
8571
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8572
        if not isinstance(disk_dict, dict):
8573
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8574
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8575

    
8576
      if disk_op == constants.DDM_ADD:
8577
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8578
        if mode not in constants.DISK_ACCESS_SET:
8579
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8580
                                     errors.ECODE_INVAL)
8581
        size = disk_dict.get('size', None)
8582
        if size is None:
8583
          raise errors.OpPrereqError("Required disk parameter size missing",
8584
                                     errors.ECODE_INVAL)
8585
        try:
8586
          size = int(size)
8587
        except (TypeError, ValueError), err:
8588
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8589
                                     str(err), errors.ECODE_INVAL)
8590
        disk_dict['size'] = size
8591
      else:
8592
        # modification of disk
8593
        if 'size' in disk_dict:
8594
          raise errors.OpPrereqError("Disk size change not possible, use"
8595
                                     " grow-disk", errors.ECODE_INVAL)
8596

    
8597
    if disk_addremove > 1:
8598
      raise errors.OpPrereqError("Only one disk add or remove operation"
8599
                                 " supported at a time", errors.ECODE_INVAL)
8600

    
8601
    if self.op.disks and self.op.disk_template is not None:
8602
      raise errors.OpPrereqError("Disk template conversion and other disk"
8603
                                 " changes not supported at the same time",
8604
                                 errors.ECODE_INVAL)
8605

    
8606
    if self.op.disk_template:
8607
      _CheckDiskTemplate(self.op.disk_template)
8608
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8609
          self.op.remote_node is None):
8610
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8611
                                   " one requires specifying a secondary node",
8612
                                   errors.ECODE_INVAL)
8613

    
8614
    # NIC validation
8615
    nic_addremove = 0
8616
    for nic_op, nic_dict in self.op.nics:
8617
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8618
      if nic_op == constants.DDM_REMOVE:
8619
        nic_addremove += 1
8620
        continue
8621
      elif nic_op == constants.DDM_ADD:
8622
        nic_addremove += 1
8623
      else:
8624
        if not isinstance(nic_op, int):
8625
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8626
        if not isinstance(nic_dict, dict):
8627
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8628
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8629

    
8630
      # nic_dict should be a dict
8631
      nic_ip = nic_dict.get('ip', None)
8632
      if nic_ip is not None:
8633
        if nic_ip.lower() == constants.VALUE_NONE:
8634
          nic_dict['ip'] = None
8635
        else:
8636
          if not netutils.IsValidIP4(nic_ip):
8637
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8638
                                       errors.ECODE_INVAL)
8639

    
8640
      nic_bridge = nic_dict.get('bridge', None)
8641
      nic_link = nic_dict.get('link', None)
8642
      if nic_bridge and nic_link:
8643
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8644
                                   " at the same time", errors.ECODE_INVAL)
8645
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8646
        nic_dict['bridge'] = None
8647
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8648
        nic_dict['link'] = None
8649

    
8650
      if nic_op == constants.DDM_ADD:
8651
        nic_mac = nic_dict.get('mac', None)
8652
        if nic_mac is None:
8653
          nic_dict['mac'] = constants.VALUE_AUTO
8654

    
8655
      if 'mac' in nic_dict:
8656
        nic_mac = nic_dict['mac']
8657
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8658
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8659

    
8660
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8661
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8662
                                     " modifying an existing nic",
8663
                                     errors.ECODE_INVAL)
8664

    
8665
    if nic_addremove > 1:
8666
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8667
                                 " supported at a time", errors.ECODE_INVAL)
8668

    
8669
  def ExpandNames(self):
8670
    self._ExpandAndLockInstance()
8671
    self.needed_locks[locking.LEVEL_NODE] = []
8672
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8673

    
8674
  def DeclareLocks(self, level):
8675
    if level == locking.LEVEL_NODE:
8676
      self._LockInstancesNodes()
8677
      if self.op.disk_template and self.op.remote_node:
8678
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8679
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8680

    
8681
  def BuildHooksEnv(self):
8682
    """Build hooks env.
8683

8684
    This runs on the master, primary and secondaries.
8685

8686
    """
8687
    args = dict()
8688
    if constants.BE_MEMORY in self.be_new:
8689
      args['memory'] = self.be_new[constants.BE_MEMORY]
8690
    if constants.BE_VCPUS in self.be_new:
8691
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8692
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8693
    # information at all.
8694
    if self.op.nics:
8695
      args['nics'] = []
8696
      nic_override = dict(self.op.nics)
8697
      for idx, nic in enumerate(self.instance.nics):
8698
        if idx in nic_override:
8699
          this_nic_override = nic_override[idx]
8700
        else:
8701
          this_nic_override = {}
8702
        if 'ip' in this_nic_override:
8703
          ip = this_nic_override['ip']
8704
        else:
8705
          ip = nic.ip
8706
        if 'mac' in this_nic_override:
8707
          mac = this_nic_override['mac']
8708
        else:
8709
          mac = nic.mac
8710
        if idx in self.nic_pnew:
8711
          nicparams = self.nic_pnew[idx]
8712
        else:
8713
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8714
        mode = nicparams[constants.NIC_MODE]
8715
        link = nicparams[constants.NIC_LINK]
8716
        args['nics'].append((ip, mac, mode, link))
8717
      if constants.DDM_ADD in nic_override:
8718
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8719
        mac = nic_override[constants.DDM_ADD]['mac']
8720
        nicparams = self.nic_pnew[constants.DDM_ADD]
8721
        mode = nicparams[constants.NIC_MODE]
8722
        link = nicparams[constants.NIC_LINK]
8723
        args['nics'].append((ip, mac, mode, link))
8724
      elif constants.DDM_REMOVE in nic_override:
8725
        del args['nics'][-1]
8726

    
8727
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8728
    if self.op.disk_template:
8729
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8730
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8731
    return env, nl, nl
8732

    
8733
  def CheckPrereq(self):
8734
    """Check prerequisites.
8735

8736
    This only checks the instance list against the existing names.
8737

8738
    """
8739
    # checking the new params on the primary/secondary nodes
8740

    
8741
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8742
    cluster = self.cluster = self.cfg.GetClusterInfo()
8743
    assert self.instance is not None, \
8744
      "Cannot retrieve locked instance %s" % self.op.instance_name
8745
    pnode = instance.primary_node
8746
    nodelist = list(instance.all_nodes)
8747

    
8748
    # OS change
8749
    if self.op.os_name and not self.op.force:
8750
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8751
                      self.op.force_variant)
8752
      instance_os = self.op.os_name
8753
    else:
8754
      instance_os = instance.os
8755

    
8756
    if self.op.disk_template:
8757
      if instance.disk_template == self.op.disk_template:
8758
        raise errors.OpPrereqError("Instance already has disk template %s" %
8759
                                   instance.disk_template, errors.ECODE_INVAL)
8760

    
8761
      if (instance.disk_template,
8762
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8763
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8764
                                   " %s to %s" % (instance.disk_template,
8765
                                                  self.op.disk_template),
8766
                                   errors.ECODE_INVAL)
8767
      _CheckInstanceDown(self, instance, "cannot change disk template")
8768
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8769
        _CheckNodeOnline(self, self.op.remote_node)
8770
        _CheckNodeNotDrained(self, self.op.remote_node)
8771
        disks = [{"size": d.size} for d in instance.disks]
8772
        required = _ComputeDiskSize(self.op.disk_template, disks)
8773
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8774

    
8775
    # hvparams processing
8776
    if self.op.hvparams:
8777
      hv_type = instance.hypervisor
8778
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8779
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8780
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8781

    
8782
      # local check
8783
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8784
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8785
      self.hv_new = hv_new # the new actual values
8786
      self.hv_inst = i_hvdict # the new dict (without defaults)
8787
    else:
8788
      self.hv_new = self.hv_inst = {}
8789

    
8790
    # beparams processing
8791
    if self.op.beparams:
8792
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8793
                                   use_none=True)
8794
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8795
      be_new = cluster.SimpleFillBE(i_bedict)
8796
      self.be_new = be_new # the new actual values
8797
      self.be_inst = i_bedict # the new dict (without defaults)
8798
    else:
8799
      self.be_new = self.be_inst = {}
8800

    
8801
    # osparams processing
8802
    if self.op.osparams:
8803
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8804
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8805
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8806
      self.os_inst = i_osdict # the new dict (without defaults)
8807
    else:
8808
      self.os_new = self.os_inst = {}
8809

    
8810
    self.warn = []
8811

    
8812
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8813
      mem_check_list = [pnode]
8814
      if be_new[constants.BE_AUTO_BALANCE]:
8815
        # either we changed auto_balance to yes or it was from before
8816
        mem_check_list.extend(instance.secondary_nodes)
8817
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8818
                                                  instance.hypervisor)
8819
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8820
                                         instance.hypervisor)
8821
      pninfo = nodeinfo[pnode]
8822
      msg = pninfo.fail_msg
8823
      if msg:
8824
        # Assume the primary node is unreachable and go ahead
8825
        self.warn.append("Can't get info from primary node %s: %s" %
8826
                         (pnode,  msg))
8827
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8828
        self.warn.append("Node data from primary node %s doesn't contain"
8829
                         " free memory information" % pnode)
8830
      elif instance_info.fail_msg:
8831
        self.warn.append("Can't get instance runtime information: %s" %
8832
                        instance_info.fail_msg)
8833
      else:
8834
        if instance_info.payload:
8835
          current_mem = int(instance_info.payload['memory'])
8836
        else:
8837
          # Assume instance not running
8838
          # (there is a slight race condition here, but it's not very probable,
8839
          # and we have no other way to check)
8840
          current_mem = 0
8841
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8842
                    pninfo.payload['memory_free'])
8843
        if miss_mem > 0:
8844
          raise errors.OpPrereqError("This change will prevent the instance"
8845
                                     " from starting, due to %d MB of memory"
8846
                                     " missing on its primary node" % miss_mem,
8847
                                     errors.ECODE_NORES)
8848

    
8849
      if be_new[constants.BE_AUTO_BALANCE]:
8850
        for node, nres in nodeinfo.items():
8851
          if node not in instance.secondary_nodes:
8852
            continue
8853
          msg = nres.fail_msg
8854
          if msg:
8855
            self.warn.append("Can't get info from secondary node %s: %s" %
8856
                             (node, msg))
8857
          elif not isinstance(nres.payload.get('memory_free', None), int):
8858
            self.warn.append("Secondary node %s didn't return free"
8859
                             " memory information" % node)
8860
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8861
            self.warn.append("Not enough memory to failover instance to"
8862
                             " secondary node %s" % node)
8863

    
8864
    # NIC processing
8865
    self.nic_pnew = {}
8866
    self.nic_pinst = {}
8867
    for nic_op, nic_dict in self.op.nics:
8868
      if nic_op == constants.DDM_REMOVE:
8869
        if not instance.nics:
8870
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8871
                                     errors.ECODE_INVAL)
8872
        continue
8873
      if nic_op != constants.DDM_ADD:
8874
        # an existing nic
8875
        if not instance.nics:
8876
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8877
                                     " no NICs" % nic_op,
8878
                                     errors.ECODE_INVAL)
8879
        if nic_op < 0 or nic_op >= len(instance.nics):
8880
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8881
                                     " are 0 to %d" %
8882
                                     (nic_op, len(instance.nics) - 1),
8883
                                     errors.ECODE_INVAL)
8884
        old_nic_params = instance.nics[nic_op].nicparams
8885
        old_nic_ip = instance.nics[nic_op].ip
8886
      else:
8887
        old_nic_params = {}
8888
        old_nic_ip = None
8889

    
8890
      update_params_dict = dict([(key, nic_dict[key])
8891
                                 for key in constants.NICS_PARAMETERS
8892
                                 if key in nic_dict])
8893

    
8894
      if 'bridge' in nic_dict:
8895
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8896

    
8897
      new_nic_params = _GetUpdatedParams(old_nic_params,
8898
                                         update_params_dict)
8899
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8900
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8901
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8902
      self.nic_pinst[nic_op] = new_nic_params
8903
      self.nic_pnew[nic_op] = new_filled_nic_params
8904
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8905

    
8906
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8907
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8908
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8909
        if msg:
8910
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8911
          if self.op.force:
8912
            self.warn.append(msg)
8913
          else:
8914
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8915
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8916
        if 'ip' in nic_dict:
8917
          nic_ip = nic_dict['ip']
8918
        else:
8919
          nic_ip = old_nic_ip
8920
        if nic_ip is None:
8921
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8922
                                     ' on a routed nic', errors.ECODE_INVAL)
8923
      if 'mac' in nic_dict:
8924
        nic_mac = nic_dict['mac']
8925
        if nic_mac is None:
8926
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8927
                                     errors.ECODE_INVAL)
8928
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8929
          # otherwise generate the mac
8930
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8931
        else:
8932
          # or validate/reserve the current one
8933
          try:
8934
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8935
          except errors.ReservationError:
8936
            raise errors.OpPrereqError("MAC address %s already in use"
8937
                                       " in cluster" % nic_mac,
8938
                                       errors.ECODE_NOTUNIQUE)
8939

    
8940
    # DISK processing
8941
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8942
      raise errors.OpPrereqError("Disk operations not supported for"
8943
                                 " diskless instances",
8944
                                 errors.ECODE_INVAL)
8945
    for disk_op, _ in self.op.disks:
8946
      if disk_op == constants.DDM_REMOVE:
8947
        if len(instance.disks) == 1:
8948
          raise errors.OpPrereqError("Cannot remove the last disk of"
8949
                                     " an instance", errors.ECODE_INVAL)
8950
        _CheckInstanceDown(self, instance, "cannot remove disks")
8951

    
8952
      if (disk_op == constants.DDM_ADD and
8953
          len(instance.nics) >= constants.MAX_DISKS):
8954
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8955
                                   " add more" % constants.MAX_DISKS,
8956
                                   errors.ECODE_STATE)
8957
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8958
        # an existing disk
8959
        if disk_op < 0 or disk_op >= len(instance.disks):
8960
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8961
                                     " are 0 to %d" %
8962
                                     (disk_op, len(instance.disks)),
8963
                                     errors.ECODE_INVAL)
8964

    
8965
    return
8966

    
8967
  def _ConvertPlainToDrbd(self, feedback_fn):
8968
    """Converts an instance from plain to drbd.
8969

8970
    """
8971
    feedback_fn("Converting template to drbd")
8972
    instance = self.instance
8973
    pnode = instance.primary_node
8974
    snode = self.op.remote_node
8975

    
8976
    # create a fake disk info for _GenerateDiskTemplate
8977
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8978
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8979
                                      instance.name, pnode, [snode],
8980
                                      disk_info, None, None, 0)
8981
    info = _GetInstanceInfoText(instance)
8982
    feedback_fn("Creating aditional volumes...")
8983
    # first, create the missing data and meta devices
8984
    for disk in new_disks:
8985
      # unfortunately this is... not too nice
8986
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8987
                            info, True)
8988
      for child in disk.children:
8989
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8990
    # at this stage, all new LVs have been created, we can rename the
8991
    # old ones
8992
    feedback_fn("Renaming original volumes...")
8993
    rename_list = [(o, n.children[0].logical_id)
8994
                   for (o, n) in zip(instance.disks, new_disks)]
8995
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8996
    result.Raise("Failed to rename original LVs")
8997

    
8998
    feedback_fn("Initializing DRBD devices...")
8999
    # all child devices are in place, we can now create the DRBD devices
9000
    for disk in new_disks:
9001
      for node in [pnode, snode]:
9002
        f_create = node == pnode
9003
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9004

    
9005
    # at this point, the instance has been modified
9006
    instance.disk_template = constants.DT_DRBD8
9007
    instance.disks = new_disks
9008
    self.cfg.Update(instance, feedback_fn)
9009

    
9010
    # disks are created, waiting for sync
9011
    disk_abort = not _WaitForSync(self, instance)
9012
    if disk_abort:
9013
      raise errors.OpExecError("There are some degraded disks for"
9014
                               " this instance, please cleanup manually")
9015

    
9016
  def _ConvertDrbdToPlain(self, feedback_fn):
9017
    """Converts an instance from drbd to plain.
9018

9019
    """
9020
    instance = self.instance
9021
    assert len(instance.secondary_nodes) == 1
9022
    pnode = instance.primary_node
9023
    snode = instance.secondary_nodes[0]
9024
    feedback_fn("Converting template to plain")
9025

    
9026
    old_disks = instance.disks
9027
    new_disks = [d.children[0] for d in old_disks]
9028

    
9029
    # copy over size and mode
9030
    for parent, child in zip(old_disks, new_disks):
9031
      child.size = parent.size
9032
      child.mode = parent.mode
9033

    
9034
    # update instance structure
9035
    instance.disks = new_disks
9036
    instance.disk_template = constants.DT_PLAIN
9037
    self.cfg.Update(instance, feedback_fn)
9038

    
9039
    feedback_fn("Removing volumes on the secondary node...")
9040
    for disk in old_disks:
9041
      self.cfg.SetDiskID(disk, snode)
9042
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9043
      if msg:
9044
        self.LogWarning("Could not remove block device %s on node %s,"
9045
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9046

    
9047
    feedback_fn("Removing unneeded volumes on the primary node...")
9048
    for idx, disk in enumerate(old_disks):
9049
      meta = disk.children[1]
9050
      self.cfg.SetDiskID(meta, pnode)
9051
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9052
      if msg:
9053
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9054
                        " continuing anyway: %s", idx, pnode, msg)
9055

    
9056

    
9057
  def Exec(self, feedback_fn):
9058
    """Modifies an instance.
9059

9060
    All parameters take effect only at the next restart of the instance.
9061

9062
    """
9063
    # Process here the warnings from CheckPrereq, as we don't have a
9064
    # feedback_fn there.
9065
    for warn in self.warn:
9066
      feedback_fn("WARNING: %s" % warn)
9067

    
9068
    result = []
9069
    instance = self.instance
9070
    # disk changes
9071
    for disk_op, disk_dict in self.op.disks:
9072
      if disk_op == constants.DDM_REMOVE:
9073
        # remove the last disk
9074
        device = instance.disks.pop()
9075
        device_idx = len(instance.disks)
9076
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9077
          self.cfg.SetDiskID(disk, node)
9078
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9079
          if msg:
9080
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9081
                            " continuing anyway", device_idx, node, msg)
9082
        result.append(("disk/%d" % device_idx, "remove"))
9083
      elif disk_op == constants.DDM_ADD:
9084
        # add a new disk
9085
        if instance.disk_template == constants.DT_FILE:
9086
          file_driver, file_path = instance.disks[0].logical_id
9087
          file_path = os.path.dirname(file_path)
9088
        else:
9089
          file_driver = file_path = None
9090
        disk_idx_base = len(instance.disks)
9091
        new_disk = _GenerateDiskTemplate(self,
9092
                                         instance.disk_template,
9093
                                         instance.name, instance.primary_node,
9094
                                         instance.secondary_nodes,
9095
                                         [disk_dict],
9096
                                         file_path,
9097
                                         file_driver,
9098
                                         disk_idx_base)[0]
9099
        instance.disks.append(new_disk)
9100
        info = _GetInstanceInfoText(instance)
9101

    
9102
        logging.info("Creating volume %s for instance %s",
9103
                     new_disk.iv_name, instance.name)
9104
        # Note: this needs to be kept in sync with _CreateDisks
9105
        #HARDCODE
9106
        for node in instance.all_nodes:
9107
          f_create = node == instance.primary_node
9108
          try:
9109
            _CreateBlockDev(self, node, instance, new_disk,
9110
                            f_create, info, f_create)
9111
          except errors.OpExecError, err:
9112
            self.LogWarning("Failed to create volume %s (%s) on"
9113
                            " node %s: %s",
9114
                            new_disk.iv_name, new_disk, node, err)
9115
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9116
                       (new_disk.size, new_disk.mode)))
9117
      else:
9118
        # change a given disk
9119
        instance.disks[disk_op].mode = disk_dict['mode']
9120
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9121

    
9122
    if self.op.disk_template:
9123
      r_shut = _ShutdownInstanceDisks(self, instance)
9124
      if not r_shut:
9125
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9126
                                 " proceed with disk template conversion")
9127
      mode = (instance.disk_template, self.op.disk_template)
9128
      try:
9129
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9130
      except:
9131
        self.cfg.ReleaseDRBDMinors(instance.name)
9132
        raise
9133
      result.append(("disk_template", self.op.disk_template))
9134

    
9135
    # NIC changes
9136
    for nic_op, nic_dict in self.op.nics:
9137
      if nic_op == constants.DDM_REMOVE:
9138
        # remove the last nic
9139
        del instance.nics[-1]
9140
        result.append(("nic.%d" % len(instance.nics), "remove"))
9141
      elif nic_op == constants.DDM_ADD:
9142
        # mac and bridge should be set, by now
9143
        mac = nic_dict['mac']
9144
        ip = nic_dict.get('ip', None)
9145
        nicparams = self.nic_pinst[constants.DDM_ADD]
9146
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9147
        instance.nics.append(new_nic)
9148
        result.append(("nic.%d" % (len(instance.nics) - 1),
9149
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9150
                       (new_nic.mac, new_nic.ip,
9151
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9152
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9153
                       )))
9154
      else:
9155
        for key in 'mac', 'ip':
9156
          if key in nic_dict:
9157
            setattr(instance.nics[nic_op], key, nic_dict[key])
9158
        if nic_op in self.nic_pinst:
9159
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9160
        for key, val in nic_dict.iteritems():
9161
          result.append(("nic.%s/%d" % (key, nic_op), val))
9162

    
9163
    # hvparams changes
9164
    if self.op.hvparams:
9165
      instance.hvparams = self.hv_inst
9166
      for key, val in self.op.hvparams.iteritems():
9167
        result.append(("hv/%s" % key, val))
9168

    
9169
    # beparams changes
9170
    if self.op.beparams:
9171
      instance.beparams = self.be_inst
9172
      for key, val in self.op.beparams.iteritems():
9173
        result.append(("be/%s" % key, val))
9174

    
9175
    # OS change
9176
    if self.op.os_name:
9177
      instance.os = self.op.os_name
9178

    
9179
    # osparams changes
9180
    if self.op.osparams:
9181
      instance.osparams = self.os_inst
9182
      for key, val in self.op.osparams.iteritems():
9183
        result.append(("os/%s" % key, val))
9184

    
9185
    self.cfg.Update(instance, feedback_fn)
9186

    
9187
    return result
9188

    
9189
  _DISK_CONVERSIONS = {
9190
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9191
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9192
    }
9193

    
9194

    
9195
class LUQueryExports(NoHooksLU):
9196
  """Query the exports list
9197

9198
  """
9199
  _OP_PARAMS = [
9200
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9201
    ("use_locking", False, _TBool),
9202
    ]
9203
  REQ_BGL = False
9204

    
9205
  def ExpandNames(self):
9206
    self.needed_locks = {}
9207
    self.share_locks[locking.LEVEL_NODE] = 1
9208
    if not self.op.nodes:
9209
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9210
    else:
9211
      self.needed_locks[locking.LEVEL_NODE] = \
9212
        _GetWantedNodes(self, self.op.nodes)
9213

    
9214
  def Exec(self, feedback_fn):
9215
    """Compute the list of all the exported system images.
9216

9217
    @rtype: dict
9218
    @return: a dictionary with the structure node->(export-list)
9219
        where export-list is a list of the instances exported on
9220
        that node.
9221

9222
    """
9223
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9224
    rpcresult = self.rpc.call_export_list(self.nodes)
9225
    result = {}
9226
    for node in rpcresult:
9227
      if rpcresult[node].fail_msg:
9228
        result[node] = False
9229
      else:
9230
        result[node] = rpcresult[node].payload
9231

    
9232
    return result
9233

    
9234

    
9235
class LUPrepareExport(NoHooksLU):
9236
  """Prepares an instance for an export and returns useful information.
9237

9238
  """
9239
  _OP_PARAMS = [
9240
    _PInstanceName,
9241
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9242
    ]
9243
  REQ_BGL = False
9244

    
9245
  def ExpandNames(self):
9246
    self._ExpandAndLockInstance()
9247

    
9248
  def CheckPrereq(self):
9249
    """Check prerequisites.
9250

9251
    """
9252
    instance_name = self.op.instance_name
9253

    
9254
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9255
    assert self.instance is not None, \
9256
          "Cannot retrieve locked instance %s" % self.op.instance_name
9257
    _CheckNodeOnline(self, self.instance.primary_node)
9258

    
9259
    self._cds = _GetClusterDomainSecret()
9260

    
9261
  def Exec(self, feedback_fn):
9262
    """Prepares an instance for an export.
9263

9264
    """
9265
    instance = self.instance
9266

    
9267
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9268
      salt = utils.GenerateSecret(8)
9269

    
9270
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9271
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9272
                                              constants.RIE_CERT_VALIDITY)
9273
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9274

    
9275
      (name, cert_pem) = result.payload
9276

    
9277
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9278
                                             cert_pem)
9279

    
9280
      return {
9281
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9282
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9283
                          salt),
9284
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9285
        }
9286

    
9287
    return None
9288

    
9289

    
9290
class LUExportInstance(LogicalUnit):
9291
  """Export an instance to an image in the cluster.
9292

9293
  """
9294
  HPATH = "instance-export"
9295
  HTYPE = constants.HTYPE_INSTANCE
9296
  _OP_PARAMS = [
9297
    _PInstanceName,
9298
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9299
    ("shutdown", True, _TBool),
9300
    _PShutdownTimeout,
9301
    ("remove_instance", False, _TBool),
9302
    ("ignore_remove_failures", False, _TBool),
9303
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9304
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9305
    ("destination_x509_ca", None, _TMaybeString),
9306
    ]
9307
  REQ_BGL = False
9308

    
9309
  def CheckArguments(self):
9310
    """Check the arguments.
9311

9312
    """
9313
    self.x509_key_name = self.op.x509_key_name
9314
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9315

    
9316
    if self.op.remove_instance and not self.op.shutdown:
9317
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9318
                                 " down before")
9319

    
9320
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9321
      if not self.x509_key_name:
9322
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9323
                                   errors.ECODE_INVAL)
9324

    
9325
      if not self.dest_x509_ca_pem:
9326
        raise errors.OpPrereqError("Missing destination X509 CA",
9327
                                   errors.ECODE_INVAL)
9328

    
9329
  def ExpandNames(self):
9330
    self._ExpandAndLockInstance()
9331

    
9332
    # Lock all nodes for local exports
9333
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9334
      # FIXME: lock only instance primary and destination node
9335
      #
9336
      # Sad but true, for now we have do lock all nodes, as we don't know where
9337
      # the previous export might be, and in this LU we search for it and
9338
      # remove it from its current node. In the future we could fix this by:
9339
      #  - making a tasklet to search (share-lock all), then create the
9340
      #    new one, then one to remove, after
9341
      #  - removing the removal operation altogether
9342
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9343

    
9344
  def DeclareLocks(self, level):
9345
    """Last minute lock declaration."""
9346
    # All nodes are locked anyway, so nothing to do here.
9347

    
9348
  def BuildHooksEnv(self):
9349
    """Build hooks env.
9350

9351
    This will run on the master, primary node and target node.
9352

9353
    """
9354
    env = {
9355
      "EXPORT_MODE": self.op.mode,
9356
      "EXPORT_NODE": self.op.target_node,
9357
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9358
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9359
      # TODO: Generic function for boolean env variables
9360
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9361
      }
9362

    
9363
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9364

    
9365
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9366

    
9367
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9368
      nl.append(self.op.target_node)
9369

    
9370
    return env, nl, nl
9371

    
9372
  def CheckPrereq(self):
9373
    """Check prerequisites.
9374

9375
    This checks that the instance and node names are valid.
9376

9377
    """
9378
    instance_name = self.op.instance_name
9379

    
9380
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9381
    assert self.instance is not None, \
9382
          "Cannot retrieve locked instance %s" % self.op.instance_name
9383
    _CheckNodeOnline(self, self.instance.primary_node)
9384

    
9385
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9386
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9387
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9388
      assert self.dst_node is not None
9389

    
9390
      _CheckNodeOnline(self, self.dst_node.name)
9391
      _CheckNodeNotDrained(self, self.dst_node.name)
9392

    
9393
      self._cds = None
9394
      self.dest_disk_info = None
9395
      self.dest_x509_ca = None
9396

    
9397
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9398
      self.dst_node = None
9399

    
9400
      if len(self.op.target_node) != len(self.instance.disks):
9401
        raise errors.OpPrereqError(("Received destination information for %s"
9402
                                    " disks, but instance %s has %s disks") %
9403
                                   (len(self.op.target_node), instance_name,
9404
                                    len(self.instance.disks)),
9405
                                   errors.ECODE_INVAL)
9406

    
9407
      cds = _GetClusterDomainSecret()
9408

    
9409
      # Check X509 key name
9410
      try:
9411
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9412
      except (TypeError, ValueError), err:
9413
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9414

    
9415
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9416
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9417
                                   errors.ECODE_INVAL)
9418

    
9419
      # Load and verify CA
9420
      try:
9421
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9422
      except OpenSSL.crypto.Error, err:
9423
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9424
                                   (err, ), errors.ECODE_INVAL)
9425

    
9426
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9427
      if errcode is not None:
9428
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9429
                                   (msg, ), errors.ECODE_INVAL)
9430

    
9431
      self.dest_x509_ca = cert
9432

    
9433
      # Verify target information
9434
      disk_info = []
9435
      for idx, disk_data in enumerate(self.op.target_node):
9436
        try:
9437
          (host, port, magic) = \
9438
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9439
        except errors.GenericError, err:
9440
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9441
                                     (idx, err), errors.ECODE_INVAL)
9442

    
9443
        disk_info.append((host, port, magic))
9444

    
9445
      assert len(disk_info) == len(self.op.target_node)
9446
      self.dest_disk_info = disk_info
9447

    
9448
    else:
9449
      raise errors.ProgrammerError("Unhandled export mode %r" %
9450
                                   self.op.mode)
9451

    
9452
    # instance disk type verification
9453
    # TODO: Implement export support for file-based disks
9454
    for disk in self.instance.disks:
9455
      if disk.dev_type == constants.LD_FILE:
9456
        raise errors.OpPrereqError("Export not supported for instances with"
9457
                                   " file-based disks", errors.ECODE_INVAL)
9458

    
9459
  def _CleanupExports(self, feedback_fn):
9460
    """Removes exports of current instance from all other nodes.
9461

9462
    If an instance in a cluster with nodes A..D was exported to node C, its
9463
    exports will be removed from the nodes A, B and D.
9464

9465
    """
9466
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9467

    
9468
    nodelist = self.cfg.GetNodeList()
9469
    nodelist.remove(self.dst_node.name)
9470

    
9471
    # on one-node clusters nodelist will be empty after the removal
9472
    # if we proceed the backup would be removed because OpQueryExports
9473
    # substitutes an empty list with the full cluster node list.
9474
    iname = self.instance.name
9475
    if nodelist:
9476
      feedback_fn("Removing old exports for instance %s" % iname)
9477
      exportlist = self.rpc.call_export_list(nodelist)
9478
      for node in exportlist:
9479
        if exportlist[node].fail_msg:
9480
          continue
9481
        if iname in exportlist[node].payload:
9482
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9483
          if msg:
9484
            self.LogWarning("Could not remove older export for instance %s"
9485
                            " on node %s: %s", iname, node, msg)
9486

    
9487
  def Exec(self, feedback_fn):
9488
    """Export an instance to an image in the cluster.
9489

9490
    """
9491
    assert self.op.mode in constants.EXPORT_MODES
9492

    
9493
    instance = self.instance
9494
    src_node = instance.primary_node
9495

    
9496
    if self.op.shutdown:
9497
      # shutdown the instance, but not the disks
9498
      feedback_fn("Shutting down instance %s" % instance.name)
9499
      result = self.rpc.call_instance_shutdown(src_node, instance,
9500
                                               self.op.shutdown_timeout)
9501
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9502
      result.Raise("Could not shutdown instance %s on"
9503
                   " node %s" % (instance.name, src_node))
9504

    
9505
    # set the disks ID correctly since call_instance_start needs the
9506
    # correct drbd minor to create the symlinks
9507
    for disk in instance.disks:
9508
      self.cfg.SetDiskID(disk, src_node)
9509

    
9510
    activate_disks = (not instance.admin_up)
9511

    
9512
    if activate_disks:
9513
      # Activate the instance disks if we'exporting a stopped instance
9514
      feedback_fn("Activating disks for %s" % instance.name)
9515
      _StartInstanceDisks(self, instance, None)
9516

    
9517
    try:
9518
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9519
                                                     instance)
9520

    
9521
      helper.CreateSnapshots()
9522
      try:
9523
        if (self.op.shutdown and instance.admin_up and
9524
            not self.op.remove_instance):
9525
          assert not activate_disks
9526
          feedback_fn("Starting instance %s" % instance.name)
9527
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9528
          msg = result.fail_msg
9529
          if msg:
9530
            feedback_fn("Failed to start instance: %s" % msg)
9531
            _ShutdownInstanceDisks(self, instance)
9532
            raise errors.OpExecError("Could not start instance: %s" % msg)
9533

    
9534
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9535
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9536
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9537
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9538
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9539

    
9540
          (key_name, _, _) = self.x509_key_name
9541

    
9542
          dest_ca_pem = \
9543
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9544
                                            self.dest_x509_ca)
9545

    
9546
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9547
                                                     key_name, dest_ca_pem,
9548
                                                     timeouts)
9549
      finally:
9550
        helper.Cleanup()
9551

    
9552
      # Check for backwards compatibility
9553
      assert len(dresults) == len(instance.disks)
9554
      assert compat.all(isinstance(i, bool) for i in dresults), \
9555
             "Not all results are boolean: %r" % dresults
9556

    
9557
    finally:
9558
      if activate_disks:
9559
        feedback_fn("Deactivating disks for %s" % instance.name)
9560
        _ShutdownInstanceDisks(self, instance)
9561

    
9562
    if not (compat.all(dresults) and fin_resu):
9563
      failures = []
9564
      if not fin_resu:
9565
        failures.append("export finalization")
9566
      if not compat.all(dresults):
9567
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9568
                               if not dsk)
9569
        failures.append("disk export: disk(s) %s" % fdsk)
9570

    
9571
      raise errors.OpExecError("Export failed, errors in %s" %
9572
                               utils.CommaJoin(failures))
9573

    
9574
    # At this point, the export was successful, we can cleanup/finish
9575

    
9576
    # Remove instance if requested
9577
    if self.op.remove_instance:
9578
      feedback_fn("Removing instance %s" % instance.name)
9579
      _RemoveInstance(self, feedback_fn, instance,
9580
                      self.op.ignore_remove_failures)
9581

    
9582
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9583
      self._CleanupExports(feedback_fn)
9584

    
9585
    return fin_resu, dresults
9586

    
9587

    
9588
class LURemoveExport(NoHooksLU):
9589
  """Remove exports related to the named instance.
9590

9591
  """
9592
  _OP_PARAMS = [
9593
    _PInstanceName,
9594
    ]
9595
  REQ_BGL = False
9596

    
9597
  def ExpandNames(self):
9598
    self.needed_locks = {}
9599
    # We need all nodes to be locked in order for RemoveExport to work, but we
9600
    # don't need to lock the instance itself, as nothing will happen to it (and
9601
    # we can remove exports also for a removed instance)
9602
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9603

    
9604
  def Exec(self, feedback_fn):
9605
    """Remove any export.
9606

9607
    """
9608
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9609
    # If the instance was not found we'll try with the name that was passed in.
9610
    # This will only work if it was an FQDN, though.
9611
    fqdn_warn = False
9612
    if not instance_name:
9613
      fqdn_warn = True
9614
      instance_name = self.op.instance_name
9615

    
9616
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9617
    exportlist = self.rpc.call_export_list(locked_nodes)
9618
    found = False
9619
    for node in exportlist:
9620
      msg = exportlist[node].fail_msg
9621
      if msg:
9622
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9623
        continue
9624
      if instance_name in exportlist[node].payload:
9625
        found = True
9626
        result = self.rpc.call_export_remove(node, instance_name)
9627
        msg = result.fail_msg
9628
        if msg:
9629
          logging.error("Could not remove export for instance %s"
9630
                        " on node %s: %s", instance_name, node, msg)
9631

    
9632
    if fqdn_warn and not found:
9633
      feedback_fn("Export not found. If trying to remove an export belonging"
9634
                  " to a deleted instance please use its Fully Qualified"
9635
                  " Domain Name.")
9636

    
9637

    
9638
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9639
  """Generic tags LU.
9640

9641
  This is an abstract class which is the parent of all the other tags LUs.
9642

9643
  """
9644

    
9645
  def ExpandNames(self):
9646
    self.needed_locks = {}
9647
    if self.op.kind == constants.TAG_NODE:
9648
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9649
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9650
    elif self.op.kind == constants.TAG_INSTANCE:
9651
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9652
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9653

    
9654
  def CheckPrereq(self):
9655
    """Check prerequisites.
9656

9657
    """
9658
    if self.op.kind == constants.TAG_CLUSTER:
9659
      self.target = self.cfg.GetClusterInfo()
9660
    elif self.op.kind == constants.TAG_NODE:
9661
      self.target = self.cfg.GetNodeInfo(self.op.name)
9662
    elif self.op.kind == constants.TAG_INSTANCE:
9663
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9664
    else:
9665
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9666
                                 str(self.op.kind), errors.ECODE_INVAL)
9667

    
9668

    
9669
class LUGetTags(TagsLU):
9670
  """Returns the tags of a given object.
9671

9672
  """
9673
  _OP_PARAMS = [
9674
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9675
    ("name", _NoDefault, _TNonEmptyString),
9676
    ]
9677
  REQ_BGL = False
9678

    
9679
  def Exec(self, feedback_fn):
9680
    """Returns the tag list.
9681

9682
    """
9683
    return list(self.target.GetTags())
9684

    
9685

    
9686
class LUSearchTags(NoHooksLU):
9687
  """Searches the tags for a given pattern.
9688

9689
  """
9690
  _OP_PARAMS = [
9691
    ("pattern", _NoDefault, _TNonEmptyString),
9692
    ]
9693
  REQ_BGL = False
9694

    
9695
  def ExpandNames(self):
9696
    self.needed_locks = {}
9697

    
9698
  def CheckPrereq(self):
9699
    """Check prerequisites.
9700

9701
    This checks the pattern passed for validity by compiling it.
9702

9703
    """
9704
    try:
9705
      self.re = re.compile(self.op.pattern)
9706
    except re.error, err:
9707
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9708
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9709

    
9710
  def Exec(self, feedback_fn):
9711
    """Returns the tag list.
9712

9713
    """
9714
    cfg = self.cfg
9715
    tgts = [("/cluster", cfg.GetClusterInfo())]
9716
    ilist = cfg.GetAllInstancesInfo().values()
9717
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9718
    nlist = cfg.GetAllNodesInfo().values()
9719
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9720
    results = []
9721
    for path, target in tgts:
9722
      for tag in target.GetTags():
9723
        if self.re.search(tag):
9724
          results.append((path, tag))
9725
    return results
9726

    
9727

    
9728
class LUAddTags(TagsLU):
9729
  """Sets a tag on a given object.
9730

9731
  """
9732
  _OP_PARAMS = [
9733
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9734
    ("name", _NoDefault, _TNonEmptyString),
9735
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9736
    ]
9737
  REQ_BGL = False
9738

    
9739
  def CheckPrereq(self):
9740
    """Check prerequisites.
9741

9742
    This checks the type and length of the tag name and value.
9743

9744
    """
9745
    TagsLU.CheckPrereq(self)
9746
    for tag in self.op.tags:
9747
      objects.TaggableObject.ValidateTag(tag)
9748

    
9749
  def Exec(self, feedback_fn):
9750
    """Sets the tag.
9751

9752
    """
9753
    try:
9754
      for tag in self.op.tags:
9755
        self.target.AddTag(tag)
9756
    except errors.TagError, err:
9757
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9758
    self.cfg.Update(self.target, feedback_fn)
9759

    
9760

    
9761
class LUDelTags(TagsLU):
9762
  """Delete a list of tags from a given object.
9763

9764
  """
9765
  _OP_PARAMS = [
9766
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9767
    ("name", _NoDefault, _TNonEmptyString),
9768
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9769
    ]
9770
  REQ_BGL = False
9771

    
9772
  def CheckPrereq(self):
9773
    """Check prerequisites.
9774

9775
    This checks that we have the given tag.
9776

9777
    """
9778
    TagsLU.CheckPrereq(self)
9779
    for tag in self.op.tags:
9780
      objects.TaggableObject.ValidateTag(tag)
9781
    del_tags = frozenset(self.op.tags)
9782
    cur_tags = self.target.GetTags()
9783
    if not del_tags <= cur_tags:
9784
      diff_tags = del_tags - cur_tags
9785
      diff_names = ["'%s'" % tag for tag in diff_tags]
9786
      diff_names.sort()
9787
      raise errors.OpPrereqError("Tag(s) %s not found" %
9788
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9789

    
9790
  def Exec(self, feedback_fn):
9791
    """Remove the tag from the object.
9792

9793
    """
9794
    for tag in self.op.tags:
9795
      self.target.RemoveTag(tag)
9796
    self.cfg.Update(self.target, feedback_fn)
9797

    
9798

    
9799
class LUTestDelay(NoHooksLU):
9800
  """Sleep for a specified amount of time.
9801

9802
  This LU sleeps on the master and/or nodes for a specified amount of
9803
  time.
9804

9805
  """
9806
  _OP_PARAMS = [
9807
    ("duration", _NoDefault, _TFloat),
9808
    ("on_master", True, _TBool),
9809
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9810
    ("repeat", 0, _TPositiveInt)
9811
    ]
9812
  REQ_BGL = False
9813

    
9814
  def ExpandNames(self):
9815
    """Expand names and set required locks.
9816

9817
    This expands the node list, if any.
9818

9819
    """
9820
    self.needed_locks = {}
9821
    if self.op.on_nodes:
9822
      # _GetWantedNodes can be used here, but is not always appropriate to use
9823
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9824
      # more information.
9825
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9826
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9827

    
9828
  def _TestDelay(self):
9829
    """Do the actual sleep.
9830

9831
    """
9832
    if self.op.on_master:
9833
      if not utils.TestDelay(self.op.duration):
9834
        raise errors.OpExecError("Error during master delay test")
9835
    if self.op.on_nodes:
9836
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9837
      for node, node_result in result.items():
9838
        node_result.Raise("Failure during rpc call to node %s" % node)
9839

    
9840
  def Exec(self, feedback_fn):
9841
    """Execute the test delay opcode, with the wanted repetitions.
9842

9843
    """
9844
    if self.op.repeat == 0:
9845
      self._TestDelay()
9846
    else:
9847
      top_value = self.op.repeat - 1
9848
      for i in range(self.op.repeat):
9849
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9850
        self._TestDelay()
9851

    
9852

    
9853
class IAllocator(object):
9854
  """IAllocator framework.
9855

9856
  An IAllocator instance has three sets of attributes:
9857
    - cfg that is needed to query the cluster
9858
    - input data (all members of the _KEYS class attribute are required)
9859
    - four buffer attributes (in|out_data|text), that represent the
9860
      input (to the external script) in text and data structure format,
9861
      and the output from it, again in two formats
9862
    - the result variables from the script (success, info, nodes) for
9863
      easy usage
9864

9865
  """
9866
  # pylint: disable-msg=R0902
9867
  # lots of instance attributes
9868
  _ALLO_KEYS = [
9869
    "name", "mem_size", "disks", "disk_template",
9870
    "os", "tags", "nics", "vcpus", "hypervisor",
9871
    ]
9872
  _RELO_KEYS = [
9873
    "name", "relocate_from",
9874
    ]
9875
  _EVAC_KEYS = [
9876
    "evac_nodes",
9877
    ]
9878

    
9879
  def __init__(self, cfg, rpc, mode, **kwargs):
9880
    self.cfg = cfg
9881
    self.rpc = rpc
9882
    # init buffer variables
9883
    self.in_text = self.out_text = self.in_data = self.out_data = None
9884
    # init all input fields so that pylint is happy
9885
    self.mode = mode
9886
    self.mem_size = self.disks = self.disk_template = None
9887
    self.os = self.tags = self.nics = self.vcpus = None
9888
    self.hypervisor = None
9889
    self.relocate_from = None
9890
    self.name = None
9891
    self.evac_nodes = None
9892
    # computed fields
9893
    self.required_nodes = None
9894
    # init result fields
9895
    self.success = self.info = self.result = None
9896
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9897
      keyset = self._ALLO_KEYS
9898
      fn = self._AddNewInstance
9899
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9900
      keyset = self._RELO_KEYS
9901
      fn = self._AddRelocateInstance
9902
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9903
      keyset = self._EVAC_KEYS
9904
      fn = self._AddEvacuateNodes
9905
    else:
9906
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9907
                                   " IAllocator" % self.mode)
9908
    for key in kwargs:
9909
      if key not in keyset:
9910
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9911
                                     " IAllocator" % key)
9912
      setattr(self, key, kwargs[key])
9913

    
9914
    for key in keyset:
9915
      if key not in kwargs:
9916
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9917
                                     " IAllocator" % key)
9918
    self._BuildInputData(fn)
9919

    
9920
  def _ComputeClusterData(self):
9921
    """Compute the generic allocator input data.
9922

9923
    This is the data that is independent of the actual operation.
9924

9925
    """
9926
    cfg = self.cfg
9927
    cluster_info = cfg.GetClusterInfo()
9928
    # cluster data
9929
    data = {
9930
      "version": constants.IALLOCATOR_VERSION,
9931
      "cluster_name": cfg.GetClusterName(),
9932
      "cluster_tags": list(cluster_info.GetTags()),
9933
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9934
      # we don't have job IDs
9935
      }
9936
    iinfo = cfg.GetAllInstancesInfo().values()
9937
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9938

    
9939
    # node data
9940
    node_results = {}
9941
    node_list = cfg.GetNodeList()
9942

    
9943
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9944
      hypervisor_name = self.hypervisor
9945
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9946
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9947
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9948
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9949

    
9950
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9951
                                        hypervisor_name)
9952
    node_iinfo = \
9953
      self.rpc.call_all_instances_info(node_list,
9954
                                       cluster_info.enabled_hypervisors)
9955
    for nname, nresult in node_data.items():
9956
      # first fill in static (config-based) values
9957
      ninfo = cfg.GetNodeInfo(nname)
9958
      pnr = {
9959
        "tags": list(ninfo.GetTags()),
9960
        "primary_ip": ninfo.primary_ip,
9961
        "secondary_ip": ninfo.secondary_ip,
9962
        "offline": ninfo.offline,
9963
        "drained": ninfo.drained,
9964
        "master_candidate": ninfo.master_candidate,
9965
        }
9966

    
9967
      if not (ninfo.offline or ninfo.drained):
9968
        nresult.Raise("Can't get data for node %s" % nname)
9969
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9970
                                nname)
9971
        remote_info = nresult.payload
9972

    
9973
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9974
                     'vg_size', 'vg_free', 'cpu_total']:
9975
          if attr not in remote_info:
9976
            raise errors.OpExecError("Node '%s' didn't return attribute"
9977
                                     " '%s'" % (nname, attr))
9978
          if not isinstance(remote_info[attr], int):
9979
            raise errors.OpExecError("Node '%s' returned invalid value"
9980
                                     " for '%s': %s" %
9981
                                     (nname, attr, remote_info[attr]))
9982
        # compute memory used by primary instances
9983
        i_p_mem = i_p_up_mem = 0
9984
        for iinfo, beinfo in i_list:
9985
          if iinfo.primary_node == nname:
9986
            i_p_mem += beinfo[constants.BE_MEMORY]
9987
            if iinfo.name not in node_iinfo[nname].payload:
9988
              i_used_mem = 0
9989
            else:
9990
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9991
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9992
            remote_info['memory_free'] -= max(0, i_mem_diff)
9993

    
9994
            if iinfo.admin_up:
9995
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9996

    
9997
        # compute memory used by instances
9998
        pnr_dyn = {
9999
          "total_memory": remote_info['memory_total'],
10000
          "reserved_memory": remote_info['memory_dom0'],
10001
          "free_memory": remote_info['memory_free'],
10002
          "total_disk": remote_info['vg_size'],
10003
          "free_disk": remote_info['vg_free'],
10004
          "total_cpus": remote_info['cpu_total'],
10005
          "i_pri_memory": i_p_mem,
10006
          "i_pri_up_memory": i_p_up_mem,
10007
          }
10008
        pnr.update(pnr_dyn)
10009

    
10010
      node_results[nname] = pnr
10011
    data["nodes"] = node_results
10012

    
10013
    # instance data
10014
    instance_data = {}
10015
    for iinfo, beinfo in i_list:
10016
      nic_data = []
10017
      for nic in iinfo.nics:
10018
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10019
        nic_dict = {"mac": nic.mac,
10020
                    "ip": nic.ip,
10021
                    "mode": filled_params[constants.NIC_MODE],
10022
                    "link": filled_params[constants.NIC_LINK],
10023
                   }
10024
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10025
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10026
        nic_data.append(nic_dict)
10027
      pir = {
10028
        "tags": list(iinfo.GetTags()),
10029
        "admin_up": iinfo.admin_up,
10030
        "vcpus": beinfo[constants.BE_VCPUS],
10031
        "memory": beinfo[constants.BE_MEMORY],
10032
        "os": iinfo.os,
10033
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10034
        "nics": nic_data,
10035
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10036
        "disk_template": iinfo.disk_template,
10037
        "hypervisor": iinfo.hypervisor,
10038
        }
10039
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10040
                                                 pir["disks"])
10041
      instance_data[iinfo.name] = pir
10042

    
10043
    data["instances"] = instance_data
10044

    
10045
    self.in_data = data
10046

    
10047
  def _AddNewInstance(self):
10048
    """Add new instance data to allocator structure.
10049

10050
    This in combination with _AllocatorGetClusterData will create the
10051
    correct structure needed as input for the allocator.
10052

10053
    The checks for the completeness of the opcode must have already been
10054
    done.
10055

10056
    """
10057
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10058

    
10059
    if self.disk_template in constants.DTS_NET_MIRROR:
10060
      self.required_nodes = 2
10061
    else:
10062
      self.required_nodes = 1
10063
    request = {
10064
      "name": self.name,
10065
      "disk_template": self.disk_template,
10066
      "tags": self.tags,
10067
      "os": self.os,
10068
      "vcpus": self.vcpus,
10069
      "memory": self.mem_size,
10070
      "disks": self.disks,
10071
      "disk_space_total": disk_space,
10072
      "nics": self.nics,
10073
      "required_nodes": self.required_nodes,
10074
      }
10075
    return request
10076

    
10077
  def _AddRelocateInstance(self):
10078
    """Add relocate instance data to allocator structure.
10079

10080
    This in combination with _IAllocatorGetClusterData will create the
10081
    correct structure needed as input for the allocator.
10082

10083
    The checks for the completeness of the opcode must have already been
10084
    done.
10085

10086
    """
10087
    instance = self.cfg.GetInstanceInfo(self.name)
10088
    if instance is None:
10089
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10090
                                   " IAllocator" % self.name)
10091

    
10092
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10093
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10094
                                 errors.ECODE_INVAL)
10095

    
10096
    if len(instance.secondary_nodes) != 1:
10097
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10098
                                 errors.ECODE_STATE)
10099

    
10100
    self.required_nodes = 1
10101
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10102
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10103

    
10104
    request = {
10105
      "name": self.name,
10106
      "disk_space_total": disk_space,
10107
      "required_nodes": self.required_nodes,
10108
      "relocate_from": self.relocate_from,
10109
      }
10110
    return request
10111

    
10112
  def _AddEvacuateNodes(self):
10113
    """Add evacuate nodes data to allocator structure.
10114

10115
    """
10116
    request = {
10117
      "evac_nodes": self.evac_nodes
10118
      }
10119
    return request
10120

    
10121
  def _BuildInputData(self, fn):
10122
    """Build input data structures.
10123

10124
    """
10125
    self._ComputeClusterData()
10126

    
10127
    request = fn()
10128
    request["type"] = self.mode
10129
    self.in_data["request"] = request
10130

    
10131
    self.in_text = serializer.Dump(self.in_data)
10132

    
10133
  def Run(self, name, validate=True, call_fn=None):
10134
    """Run an instance allocator and return the results.
10135

10136
    """
10137
    if call_fn is None:
10138
      call_fn = self.rpc.call_iallocator_runner
10139

    
10140
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10141
    result.Raise("Failure while running the iallocator script")
10142

    
10143
    self.out_text = result.payload
10144
    if validate:
10145
      self._ValidateResult()
10146

    
10147
  def _ValidateResult(self):
10148
    """Process the allocator results.
10149

10150
    This will process and if successful save the result in
10151
    self.out_data and the other parameters.
10152

10153
    """
10154
    try:
10155
      rdict = serializer.Load(self.out_text)
10156
    except Exception, err:
10157
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10158

    
10159
    if not isinstance(rdict, dict):
10160
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10161

    
10162
    # TODO: remove backwards compatiblity in later versions
10163
    if "nodes" in rdict and "result" not in rdict:
10164
      rdict["result"] = rdict["nodes"]
10165
      del rdict["nodes"]
10166

    
10167
    for key in "success", "info", "result":
10168
      if key not in rdict:
10169
        raise errors.OpExecError("Can't parse iallocator results:"
10170
                                 " missing key '%s'" % key)
10171
      setattr(self, key, rdict[key])
10172

    
10173
    if not isinstance(rdict["result"], list):
10174
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10175
                               " is not a list")
10176
    self.out_data = rdict
10177

    
10178

    
10179
class LUTestAllocator(NoHooksLU):
10180
  """Run allocator tests.
10181

10182
  This LU runs the allocator tests
10183

10184
  """
10185
  _OP_PARAMS = [
10186
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10187
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10188
    ("name", _NoDefault, _TNonEmptyString),
10189
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10190
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10191
               _TOr(_TNone, _TNonEmptyString))))),
10192
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10193
    ("hypervisor", None, _TMaybeString),
10194
    ("allocator", None, _TMaybeString),
10195
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10196
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10197
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10198
    ("os", None, _TMaybeString),
10199
    ("disk_template", None, _TMaybeString),
10200
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10201
    ]
10202

    
10203
  def CheckPrereq(self):
10204
    """Check prerequisites.
10205

10206
    This checks the opcode parameters depending on the director and mode test.
10207

10208
    """
10209
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10210
      for attr in ["mem_size", "disks", "disk_template",
10211
                   "os", "tags", "nics", "vcpus"]:
10212
        if not hasattr(self.op, attr):
10213
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10214
                                     attr, errors.ECODE_INVAL)
10215
      iname = self.cfg.ExpandInstanceName(self.op.name)
10216
      if iname is not None:
10217
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10218
                                   iname, errors.ECODE_EXISTS)
10219
      if not isinstance(self.op.nics, list):
10220
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10221
                                   errors.ECODE_INVAL)
10222
      if not isinstance(self.op.disks, list):
10223
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10224
                                   errors.ECODE_INVAL)
10225
      for row in self.op.disks:
10226
        if (not isinstance(row, dict) or
10227
            "size" not in row or
10228
            not isinstance(row["size"], int) or
10229
            "mode" not in row or
10230
            row["mode"] not in ['r', 'w']):
10231
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10232
                                     " parameter", errors.ECODE_INVAL)
10233
      if self.op.hypervisor is None:
10234
        self.op.hypervisor = self.cfg.GetHypervisorType()
10235
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10236
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10237
      self.op.name = fname
10238
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10239
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10240
      if not hasattr(self.op, "evac_nodes"):
10241
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10242
                                   " opcode input", errors.ECODE_INVAL)
10243
    else:
10244
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10245
                                 self.op.mode, errors.ECODE_INVAL)
10246

    
10247
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10248
      if self.op.allocator is None:
10249
        raise errors.OpPrereqError("Missing allocator name",
10250
                                   errors.ECODE_INVAL)
10251
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10252
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10253
                                 self.op.direction, errors.ECODE_INVAL)
10254

    
10255
  def Exec(self, feedback_fn):
10256
    """Run the allocator test.
10257

10258
    """
10259
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10260
      ial = IAllocator(self.cfg, self.rpc,
10261
                       mode=self.op.mode,
10262
                       name=self.op.name,
10263
                       mem_size=self.op.mem_size,
10264
                       disks=self.op.disks,
10265
                       disk_template=self.op.disk_template,
10266
                       os=self.op.os,
10267
                       tags=self.op.tags,
10268
                       nics=self.op.nics,
10269
                       vcpus=self.op.vcpus,
10270
                       hypervisor=self.op.hypervisor,
10271
                       )
10272
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10273
      ial = IAllocator(self.cfg, self.rpc,
10274
                       mode=self.op.mode,
10275
                       name=self.op.name,
10276
                       relocate_from=list(self.relocate_from),
10277
                       )
10278
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10279
      ial = IAllocator(self.cfg, self.rpc,
10280
                       mode=self.op.mode,
10281
                       evac_nodes=self.op.evac_nodes)
10282
    else:
10283
      raise errors.ProgrammerError("Uncatched mode %s in"
10284
                                   " LUTestAllocator.Exec", self.op.mode)
10285

    
10286
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10287
      result = ial.in_text
10288
    else:
10289
      ial.Run(self.op.allocator, validate=False)
10290
      result = ial.out_text
10291
    return result