Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ cd14c16c

History | View | Annotate | Download (366.8 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

    
43
from ganeti import ssh
44
from ganeti import utils
45
from ganeti import errors
46
from ganeti import hypervisor
47
from ganeti import locking
48
from ganeti import constants
49
from ganeti import objects
50
from ganeti import serializer
51
from ganeti import ssconf
52
from ganeti import uidpool
53
from ganeti import compat
54
from ganeti import masterd
55
from ganeti import netutils
56

    
57
import ganeti.masterd.instance # pylint: disable-msg=W0611
58

    
59

    
60
# Modifiable default values; need to define these here before the
61
# actual LUs
62

    
63
def _EmptyList():
64
  """Returns an empty list.
65

66
  """
67
  return []
68

    
69

    
70
def _EmptyDict():
71
  """Returns an empty dict.
72

73
  """
74
  return {}
75

    
76

    
77
#: The without-default default value
78
_NoDefault = object()
79

    
80

    
81
#: The no-type (value to complex to check it in the type system)
82
_NoType = object()
83

    
84

    
85
# Some basic types
86
def _TNotNone(val):
87
  """Checks if the given value is not None.
88

89
  """
90
  return val is not None
91

    
92

    
93
def _TNone(val):
94
  """Checks if the given value is None.
95

96
  """
97
  return val is None
98

    
99

    
100
def _TBool(val):
101
  """Checks if the given value is a boolean.
102

103
  """
104
  return isinstance(val, bool)
105

    
106

    
107
def _TInt(val):
108
  """Checks if the given value is an integer.
109

110
  """
111
  return isinstance(val, int)
112

    
113

    
114
def _TFloat(val):
115
  """Checks if the given value is a float.
116

117
  """
118
  return isinstance(val, float)
119

    
120

    
121
def _TString(val):
122
  """Checks if the given value is a string.
123

124
  """
125
  return isinstance(val, basestring)
126

    
127

    
128
def _TTrue(val):
129
  """Checks if a given value evaluates to a boolean True value.
130

131
  """
132
  return bool(val)
133

    
134

    
135
def _TElemOf(target_list):
136
  """Builds a function that checks if a given value is a member of a list.
137

138
  """
139
  return lambda val: val in target_list
140

    
141

    
142
# Container types
143
def _TList(val):
144
  """Checks if the given value is a list.
145

146
  """
147
  return isinstance(val, list)
148

    
149

    
150
def _TDict(val):
151
  """Checks if the given value is a dictionary.
152

153
  """
154
  return isinstance(val, dict)
155

    
156

    
157
def _TIsLength(size):
158
  """Check is the given container is of the given size.
159

160
  """
161
  return lambda container: len(container) == size
162

    
163

    
164
# Combinator types
165
def _TAnd(*args):
166
  """Combine multiple functions using an AND operation.
167

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

    
173

    
174
def _TOr(*args):
175
  """Combine multiple functions using an AND operation.
176

177
  """
178
  def fn(val):
179
    return compat.any(t(val) for t in args)
180
  return fn
181

    
182

    
183
def _TMap(fn, test):
184
  """Checks that a modified version of the argument passes the given test.
185

186
  """
187
  return lambda val: test(fn(val))
188

    
189

    
190
# Type aliases
191

    
192
#: a non-empty string
193
_TNonEmptyString = _TAnd(_TString, _TTrue)
194

    
195

    
196
#: a maybe non-empty string
197
_TMaybeString = _TOr(_TNonEmptyString, _TNone)
198

    
199

    
200
#: a maybe boolean (bool or none)
201
_TMaybeBool = _TOr(_TBool, _TNone)
202

    
203

    
204
#: a positive integer
205
_TPositiveInt = _TAnd(_TInt, lambda v: v >= 0)
206

    
207
#: a strictly positive integer
208
_TStrictPositiveInt = _TAnd(_TInt, lambda v: v > 0)
209

    
210

    
211
def _TListOf(my_type):
212
  """Checks if a given value is a list with all elements of the same type.
213

214
  """
215
  return _TAnd(_TList,
216
               lambda lst: compat.all(my_type(v) for v in lst))
217

    
218

    
219
def _TDictOf(key_type, val_type):
220
  """Checks a dict type for the type of its key/values.
221

222
  """
223
  return _TAnd(_TDict,
224
               lambda my_dict: (compat.all(key_type(v) for v in my_dict.keys())
225
                                and compat.all(val_type(v)
226
                                               for v in my_dict.values())))
227

    
228

    
229
# Common opcode attributes
230

    
231
#: output fields for a query operation
232
_POutputFields = ("output_fields", _NoDefault, _TListOf(_TNonEmptyString))
233

    
234

    
235
#: the shutdown timeout
236
_PShutdownTimeout = ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT,
237
                     _TPositiveInt)
238

    
239
#: the force parameter
240
_PForce = ("force", False, _TBool)
241

    
242
#: a required instance name (for single-instance LUs)
243
_PInstanceName = ("instance_name", _NoDefault, _TNonEmptyString)
244

    
245

    
246
#: a required node name (for single-node LUs)
247
_PNodeName = ("node_name", _NoDefault, _TNonEmptyString)
248

    
249
#: the migration type (live/non-live)
250
_PMigrationMode = ("mode", None, _TOr(_TNone,
251
                                      _TElemOf(constants.HT_MIGRATION_MODES)))
252

    
253
#: the obsolete 'live' mode (boolean)
254
_PMigrationLive = ("live", None, _TMaybeBool)
255

    
256

    
257
# End types
258
class LogicalUnit(object):
259
  """Logical Unit base class.
260

261
  Subclasses must follow these rules:
262
    - implement ExpandNames
263
    - implement CheckPrereq (except when tasklets are used)
264
    - implement Exec (except when tasklets are used)
265
    - implement BuildHooksEnv
266
    - redefine HPATH and HTYPE
267
    - optionally redefine their run requirements:
268
        REQ_BGL: the LU needs to hold the Big Ganeti Lock exclusively
269

270
  Note that all commands require root permissions.
271

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

277
  """
278
  HPATH = None
279
  HTYPE = None
280
  _OP_PARAMS = []
281
  REQ_BGL = True
282

    
283
  def __init__(self, processor, op, context, rpc):
284
    """Constructor for LogicalUnit.
285

286
    This needs to be overridden in derived classes in order to check op
287
    validity.
288

289
    """
290
    self.proc = processor
291
    self.op = op
292
    self.cfg = context.cfg
293
    self.context = context
294
    self.rpc = rpc
295
    # Dicts used to declare locking needs to mcpu
296
    self.needed_locks = None
297
    self.acquired_locks = {}
298
    self.share_locks = dict.fromkeys(locking.LEVELS, 0)
299
    self.add_locks = {}
300
    self.remove_locks = {}
301
    # Used to force good behavior when calling helper functions
302
    self.recalculate_locks = {}
303
    self.__ssh = None
304
    # logging
305
    self.Log = processor.Log # pylint: disable-msg=C0103
306
    self.LogWarning = processor.LogWarning # pylint: disable-msg=C0103
307
    self.LogInfo = processor.LogInfo # pylint: disable-msg=C0103
308
    self.LogStep = processor.LogStep # pylint: disable-msg=C0103
309
    # support for dry-run
310
    self.dry_run_result = None
311
    # support for generic debug attribute
312
    if (not hasattr(self.op, "debug_level") or
313
        not isinstance(self.op.debug_level, int)):
314
      self.op.debug_level = 0
315

    
316
    # Tasklets
317
    self.tasklets = None
318

    
319
    # The new kind-of-type-system
320
    op_id = self.op.OP_ID
321
    for attr_name, aval, test in self._OP_PARAMS:
322
      if not hasattr(op, attr_name):
323
        if aval == _NoDefault:
324
          raise errors.OpPrereqError("Required parameter '%s.%s' missing" %
325
                                     (op_id, attr_name), errors.ECODE_INVAL)
326
        else:
327
          if callable(aval):
328
            dval = aval()
329
          else:
330
            dval = aval
331
          setattr(self.op, attr_name, dval)
332
      attr_val = getattr(op, attr_name)
333
      if test == _NoType:
334
        # no tests here
335
        continue
336
      if not callable(test):
337
        raise errors.ProgrammerError("Validation for parameter '%s.%s' failed,"
338
                                     " given type is not a proper type (%s)" %
339
                                     (op_id, attr_name, test))
340
      if not test(attr_val):
341
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
342
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
343
        raise errors.OpPrereqError("Parameter '%s.%s' fails validation" %
344
                                   (op_id, attr_name), errors.ECODE_INVAL)
345

    
346
    self.CheckArguments()
347

    
348
  def __GetSSH(self):
349
    """Returns the SshRunner object
350

351
    """
352
    if not self.__ssh:
353
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
354
    return self.__ssh
355

    
356
  ssh = property(fget=__GetSSH)
357

    
358
  def CheckArguments(self):
359
    """Check syntactic validity for the opcode arguments.
360

361
    This method is for doing a simple syntactic check and ensure
362
    validity of opcode parameters, without any cluster-related
363
    checks. While the same can be accomplished in ExpandNames and/or
364
    CheckPrereq, doing these separate is better because:
365

366
      - ExpandNames is left as as purely a lock-related function
367
      - CheckPrereq is run after we have acquired locks (and possible
368
        waited for them)
369

370
    The function is allowed to change the self.op attribute so that
371
    later methods can no longer worry about missing parameters.
372

373
    """
374
    pass
375

    
376
  def ExpandNames(self):
377
    """Expand names for this LU.
378

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

384
    LUs which implement this method must also populate the self.needed_locks
385
    member, as a dict with lock levels as keys, and a list of needed lock names
386
    as values. Rules:
387

388
      - use an empty dict if you don't need any lock
389
      - if you don't need any lock at a particular level omit that level
390
      - don't put anything for the BGL level
391
      - if you want all locks at a level use locking.ALL_SET as a value
392

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

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

401
    Examples::
402

403
      # Acquire all nodes and one instance
404
      self.needed_locks = {
405
        locking.LEVEL_NODE: locking.ALL_SET,
406
        locking.LEVEL_INSTANCE: ['instance1.example.com'],
407
      }
408
      # Acquire just two nodes
409
      self.needed_locks = {
410
        locking.LEVEL_NODE: ['node1.example.com', 'node2.example.com'],
411
      }
412
      # Acquire no locks
413
      self.needed_locks = {} # No, you can't leave it to the default value None
414

415
    """
416
    # The implementation of this method is mandatory only if the new LU is
417
    # concurrent, so that old LUs don't need to be changed all at the same
418
    # time.
419
    if self.REQ_BGL:
420
      self.needed_locks = {} # Exclusive LUs don't need locks.
421
    else:
422
      raise NotImplementedError
423

    
424
  def DeclareLocks(self, level):
425
    """Declare LU locking needs for a level
426

427
    While most LUs can just declare their locking needs at ExpandNames time,
428
    sometimes there's the need to calculate some locks after having acquired
429
    the ones before. This function is called just before acquiring locks at a
430
    particular level, but after acquiring the ones at lower levels, and permits
431
    such calculations. It can be used to modify self.needed_locks, and by
432
    default it does nothing.
433

434
    This function is only called if you have something already set in
435
    self.needed_locks for the level.
436

437
    @param level: Locking level which is going to be locked
438
    @type level: member of ganeti.locking.LEVELS
439

440
    """
441

    
442
  def CheckPrereq(self):
443
    """Check prerequisites for this LU.
444

445
    This method should check that the prerequisites for the execution
446
    of this LU are fulfilled. It can do internode communication, but
447
    it should be idempotent - no cluster or system changes are
448
    allowed.
449

450
    The method should raise errors.OpPrereqError in case something is
451
    not fulfilled. Its return value is ignored.
452

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

456
    """
457
    if self.tasklets is not None:
458
      for (idx, tl) in enumerate(self.tasklets):
459
        logging.debug("Checking prerequisites for tasklet %s/%s",
460
                      idx + 1, len(self.tasklets))
461
        tl.CheckPrereq()
462
    else:
463
      pass
464

    
465
  def Exec(self, feedback_fn):
466
    """Execute the LU.
467

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

472
    """
473
    if self.tasklets is not None:
474
      for (idx, tl) in enumerate(self.tasklets):
475
        logging.debug("Executing tasklet %s/%s", idx + 1, len(self.tasklets))
476
        tl.Exec(feedback_fn)
477
    else:
478
      raise NotImplementedError
479

    
480
  def BuildHooksEnv(self):
481
    """Build hooks environment for this LU.
482

483
    This method should return a three-node tuple consisting of: a dict
484
    containing the environment that will be used for running the
485
    specific hook for this LU, a list of node names on which the hook
486
    should run before the execution, and a list of node names on which
487
    the hook should run after the execution.
488

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

494
    No nodes should be returned as an empty list (and not None).
495

496
    Note that if the HPATH for a LU class is None, this function will
497
    not be called.
498

499
    """
500
    raise NotImplementedError
501

    
502
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
503
    """Notify the LU about the results of its hooks.
504

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

511
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
512
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
513
    @param hook_results: the results of the multi-node hooks rpc call
514
    @param feedback_fn: function used send feedback back to the caller
515
    @param lu_result: the previous Exec result this LU had, or None
516
        in the PRE phase
517
    @return: the new Exec result, based on the previous result
518
        and hook results
519

520
    """
521
    # API must be kept, thus we ignore the unused argument and could
522
    # be a function warnings
523
    # pylint: disable-msg=W0613,R0201
524
    return lu_result
525

    
526
  def _ExpandAndLockInstance(self):
527
    """Helper function to expand and lock an instance.
528

529
    Many LUs that work on an instance take its name in self.op.instance_name
530
    and need to expand it and then declare the expanded name for locking. This
531
    function does it, and then updates self.op.instance_name to the expanded
532
    name. It also initializes needed_locks as a dict, if this hasn't been done
533
    before.
534

535
    """
536
    if self.needed_locks is None:
537
      self.needed_locks = {}
538
    else:
539
      assert locking.LEVEL_INSTANCE not in self.needed_locks, \
540
        "_ExpandAndLockInstance called with instance-level locks set"
541
    self.op.instance_name = _ExpandInstanceName(self.cfg,
542
                                                self.op.instance_name)
543
    self.needed_locks[locking.LEVEL_INSTANCE] = self.op.instance_name
544

    
545
  def _LockInstancesNodes(self, primary_only=False):
546
    """Helper function to declare instances' nodes for locking.
547

548
    This function should be called after locking one or more instances to lock
549
    their nodes. Its effect is populating self.needed_locks[locking.LEVEL_NODE]
550
    with all primary or secondary nodes for instances already locked and
551
    present in self.needed_locks[locking.LEVEL_INSTANCE].
552

553
    It should be called from DeclareLocks, and for safety only works if
554
    self.recalculate_locks[locking.LEVEL_NODE] is set.
555

556
    In the future it may grow parameters to just lock some instance's nodes, or
557
    to just lock primaries or secondary nodes, if needed.
558

559
    If should be called in DeclareLocks in a way similar to::
560

561
      if level == locking.LEVEL_NODE:
562
        self._LockInstancesNodes()
563

564
    @type primary_only: boolean
565
    @param primary_only: only lock primary nodes of locked instances
566

567
    """
568
    assert locking.LEVEL_NODE in self.recalculate_locks, \
569
      "_LockInstancesNodes helper function called with no nodes to recalculate"
570

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

    
573
    # For now we'll replace self.needed_locks[locking.LEVEL_NODE], but in the
574
    # future we might want to have different behaviors depending on the value
575
    # of self.recalculate_locks[locking.LEVEL_NODE]
576
    wanted_nodes = []
577
    for instance_name in self.acquired_locks[locking.LEVEL_INSTANCE]:
578
      instance = self.context.cfg.GetInstanceInfo(instance_name)
579
      wanted_nodes.append(instance.primary_node)
580
      if not primary_only:
581
        wanted_nodes.extend(instance.secondary_nodes)
582

    
583
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
584
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
585
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
586
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
587

    
588
    del self.recalculate_locks[locking.LEVEL_NODE]
589

    
590

    
591
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
592
  """Simple LU which runs no hooks.
593

594
  This LU is intended as a parent for other LogicalUnits which will
595
  run no hooks, in order to reduce duplicate code.
596

597
  """
598
  HPATH = None
599
  HTYPE = None
600

    
601
  def BuildHooksEnv(self):
602
    """Empty BuildHooksEnv for NoHooksLu.
603

604
    This just raises an error.
605

606
    """
607
    assert False, "BuildHooksEnv called for NoHooksLUs"
608

    
609

    
610
class Tasklet:
611
  """Tasklet base class.
612

613
  Tasklets are subcomponents for LUs. LUs can consist entirely of tasklets or
614
  they can mix legacy code with tasklets. Locking needs to be done in the LU,
615
  tasklets know nothing about locks.
616

617
  Subclasses must follow these rules:
618
    - Implement CheckPrereq
619
    - Implement Exec
620

621
  """
622
  def __init__(self, lu):
623
    self.lu = lu
624

    
625
    # Shortcuts
626
    self.cfg = lu.cfg
627
    self.rpc = lu.rpc
628

    
629
  def CheckPrereq(self):
630
    """Check prerequisites for this tasklets.
631

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

636
    The method should raise errors.OpPrereqError in case something is not
637
    fulfilled. Its return value is ignored.
638

639
    This method should also update all parameters to their canonical form if it
640
    hasn't been done before.
641

642
    """
643
    pass
644

    
645
  def Exec(self, feedback_fn):
646
    """Execute the tasklet.
647

648
    This method should implement the actual work. It should raise
649
    errors.OpExecError for failures that are somewhat dealt with in code, or
650
    expected.
651

652
    """
653
    raise NotImplementedError
654

    
655

    
656
def _GetWantedNodes(lu, nodes):
657
  """Returns list of checked and expanded node names.
658

659
  @type lu: L{LogicalUnit}
660
  @param lu: the logical unit on whose behalf we execute
661
  @type nodes: list
662
  @param nodes: list of node names or None for all nodes
663
  @rtype: list
664
  @return: the list of nodes, sorted
665
  @raise errors.ProgrammerError: if the nodes parameter is wrong type
666

667
  """
668
  if not nodes:
669
    raise errors.ProgrammerError("_GetWantedNodes should only be called with a"
670
      " non-empty list of nodes whose name is to be expanded.")
671

    
672
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
673
  return utils.NiceSort(wanted)
674

    
675

    
676
def _GetWantedInstances(lu, instances):
677
  """Returns list of checked and expanded instance names.
678

679
  @type lu: L{LogicalUnit}
680
  @param lu: the logical unit on whose behalf we execute
681
  @type instances: list
682
  @param instances: list of instance names or None for all instances
683
  @rtype: list
684
  @return: the list of instances, sorted
685
  @raise errors.OpPrereqError: if the instances parameter is wrong type
686
  @raise errors.OpPrereqError: if any of the passed instances is not found
687

688
  """
689
  if instances:
690
    wanted = [_ExpandInstanceName(lu.cfg, name) for name in instances]
691
  else:
692
    wanted = utils.NiceSort(lu.cfg.GetInstanceList())
693
  return wanted
694

    
695

    
696
def _GetUpdatedParams(old_params, update_dict,
697
                      use_default=True, use_none=False):
698
  """Return the new version of a parameter dictionary.
699

700
  @type old_params: dict
701
  @param old_params: old parameters
702
  @type update_dict: dict
703
  @param update_dict: dict containing new parameter values, or
704
      constants.VALUE_DEFAULT to reset the parameter to its default
705
      value
706
  @param use_default: boolean
707
  @type use_default: whether to recognise L{constants.VALUE_DEFAULT}
708
      values as 'to be deleted' values
709
  @param use_none: boolean
710
  @type use_none: whether to recognise C{None} values as 'to be
711
      deleted' values
712
  @rtype: dict
713
  @return: the new parameter dictionary
714

715
  """
716
  params_copy = copy.deepcopy(old_params)
717
  for key, val in update_dict.iteritems():
718
    if ((use_default and val == constants.VALUE_DEFAULT) or
719
        (use_none and val is None)):
720
      try:
721
        del params_copy[key]
722
      except KeyError:
723
        pass
724
    else:
725
      params_copy[key] = val
726
  return params_copy
727

    
728

    
729
def _CheckOutputFields(static, dynamic, selected):
730
  """Checks whether all selected fields are valid.
731

732
  @type static: L{utils.FieldSet}
733
  @param static: static fields set
734
  @type dynamic: L{utils.FieldSet}
735
  @param dynamic: dynamic fields set
736

737
  """
738
  f = utils.FieldSet()
739
  f.Extend(static)
740
  f.Extend(dynamic)
741

    
742
  delta = f.NonMatching(selected)
743
  if delta:
744
    raise errors.OpPrereqError("Unknown output fields selected: %s"
745
                               % ",".join(delta), errors.ECODE_INVAL)
746

    
747

    
748
def _CheckGlobalHvParams(params):
749
  """Validates that given hypervisor params are not global ones.
750

751
  This will ensure that instances don't get customised versions of
752
  global params.
753

754
  """
755
  used_globals = constants.HVC_GLOBALS.intersection(params)
756
  if used_globals:
757
    msg = ("The following hypervisor parameters are global and cannot"
758
           " be customized at instance level, please modify them at"
759
           " cluster level: %s" % utils.CommaJoin(used_globals))
760
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
761

    
762

    
763
def _CheckNodeOnline(lu, node):
764
  """Ensure that a given node is online.
765

766
  @param lu: the LU on behalf of which we make the check
767
  @param node: the node to check
768
  @raise errors.OpPrereqError: if the node is offline
769

770
  """
771
  if lu.cfg.GetNodeInfo(node).offline:
772
    raise errors.OpPrereqError("Can't use offline node %s" % node,
773
                               errors.ECODE_INVAL)
774

    
775

    
776
def _CheckNodeNotDrained(lu, node):
777
  """Ensure that a given node is not drained.
778

779
  @param lu: the LU on behalf of which we make the check
780
  @param node: the node to check
781
  @raise errors.OpPrereqError: if the node is drained
782

783
  """
784
  if lu.cfg.GetNodeInfo(node).drained:
785
    raise errors.OpPrereqError("Can't use drained node %s" % node,
786
                               errors.ECODE_INVAL)
787

    
788

    
789
def _CheckNodeHasOS(lu, node, os_name, force_variant):
790
  """Ensure that a node supports a given OS.
791

792
  @param lu: the LU on behalf of which we make the check
793
  @param node: the node to check
794
  @param os_name: the OS to query about
795
  @param force_variant: whether to ignore variant errors
796
  @raise errors.OpPrereqError: if the node is not supporting the OS
797

798
  """
799
  result = lu.rpc.call_os_get(node, os_name)
800
  result.Raise("OS '%s' not in supported OS list for node %s" %
801
               (os_name, node),
802
               prereq=True, ecode=errors.ECODE_INVAL)
803
  if not force_variant:
804
    _CheckOSVariant(result.payload, os_name)
805

    
806

    
807
def _RequireFileStorage():
808
  """Checks that file storage is enabled.
809

810
  @raise errors.OpPrereqError: when file storage is disabled
811

812
  """
813
  if not constants.ENABLE_FILE_STORAGE:
814
    raise errors.OpPrereqError("File storage disabled at configure time",
815
                               errors.ECODE_INVAL)
816

    
817

    
818
def _CheckDiskTemplate(template):
819
  """Ensure a given disk template is valid.
820

821
  """
822
  if template not in constants.DISK_TEMPLATES:
823
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
824
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
825
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
826
  if template == constants.DT_FILE:
827
    _RequireFileStorage()
828
  return True
829

    
830

    
831
def _CheckStorageType(storage_type):
832
  """Ensure a given storage type is valid.
833

834
  """
835
  if storage_type not in constants.VALID_STORAGE_TYPES:
836
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
837
                               errors.ECODE_INVAL)
838
  if storage_type == constants.ST_FILE:
839
    _RequireFileStorage()
840
  return True
841

    
842

    
843
def _GetClusterDomainSecret():
844
  """Reads the cluster domain secret.
845

846
  """
847
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
848
                               strict=True)
849

    
850

    
851
def _CheckInstanceDown(lu, instance, reason):
852
  """Ensure that an instance is not running."""
853
  if instance.admin_up:
854
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
855
                               (instance.name, reason), errors.ECODE_STATE)
856

    
857
  pnode = instance.primary_node
858
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
859
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
860
              prereq=True, ecode=errors.ECODE_ENVIRON)
861

    
862
  if instance.name in ins_l.payload:
863
    raise errors.OpPrereqError("Instance %s is running, %s" %
864
                               (instance.name, reason), errors.ECODE_STATE)
865

    
866

    
867
def _ExpandItemName(fn, name, kind):
868
  """Expand an item name.
869

870
  @param fn: the function to use for expansion
871
  @param name: requested item name
872
  @param kind: text description ('Node' or 'Instance')
873
  @return: the resolved (full) name
874
  @raise errors.OpPrereqError: if the item is not found
875

876
  """
877
  full_name = fn(name)
878
  if full_name is None:
879
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
880
                               errors.ECODE_NOENT)
881
  return full_name
882

    
883

    
884
def _ExpandNodeName(cfg, name):
885
  """Wrapper over L{_ExpandItemName} for nodes."""
886
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
887

    
888

    
889
def _ExpandInstanceName(cfg, name):
890
  """Wrapper over L{_ExpandItemName} for instance."""
891
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
892

    
893

    
894
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
895
                          memory, vcpus, nics, disk_template, disks,
896
                          bep, hvp, hypervisor_name):
897
  """Builds instance related env variables for hooks
898

899
  This builds the hook environment from individual variables.
900

901
  @type name: string
902
  @param name: the name of the instance
903
  @type primary_node: string
904
  @param primary_node: the name of the instance's primary node
905
  @type secondary_nodes: list
906
  @param secondary_nodes: list of secondary nodes as strings
907
  @type os_type: string
908
  @param os_type: the name of the instance's OS
909
  @type status: boolean
910
  @param status: the should_run status of the instance
911
  @type memory: string
912
  @param memory: the memory size of the instance
913
  @type vcpus: string
914
  @param vcpus: the count of VCPUs the instance has
915
  @type nics: list
916
  @param nics: list of tuples (ip, mac, mode, link) representing
917
      the NICs the instance has
918
  @type disk_template: string
919
  @param disk_template: the disk template of the instance
920
  @type disks: list
921
  @param disks: the list of (size, mode) pairs
922
  @type bep: dict
923
  @param bep: the backend parameters for the instance
924
  @type hvp: dict
925
  @param hvp: the hypervisor parameters for the instance
926
  @type hypervisor_name: string
927
  @param hypervisor_name: the hypervisor for the instance
928
  @rtype: dict
929
  @return: the hook environment for this instance
930

931
  """
932
  if status:
933
    str_status = "up"
934
  else:
935
    str_status = "down"
936
  env = {
937
    "OP_TARGET": name,
938
    "INSTANCE_NAME": name,
939
    "INSTANCE_PRIMARY": primary_node,
940
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
941
    "INSTANCE_OS_TYPE": os_type,
942
    "INSTANCE_STATUS": str_status,
943
    "INSTANCE_MEMORY": memory,
944
    "INSTANCE_VCPUS": vcpus,
945
    "INSTANCE_DISK_TEMPLATE": disk_template,
946
    "INSTANCE_HYPERVISOR": hypervisor_name,
947
  }
948

    
949
  if nics:
950
    nic_count = len(nics)
951
    for idx, (ip, mac, mode, link) in enumerate(nics):
952
      if ip is None:
953
        ip = ""
954
      env["INSTANCE_NIC%d_IP" % idx] = ip
955
      env["INSTANCE_NIC%d_MAC" % idx] = mac
956
      env["INSTANCE_NIC%d_MODE" % idx] = mode
957
      env["INSTANCE_NIC%d_LINK" % idx] = link
958
      if mode == constants.NIC_MODE_BRIDGED:
959
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
960
  else:
961
    nic_count = 0
962

    
963
  env["INSTANCE_NIC_COUNT"] = nic_count
964

    
965
  if disks:
966
    disk_count = len(disks)
967
    for idx, (size, mode) in enumerate(disks):
968
      env["INSTANCE_DISK%d_SIZE" % idx] = size
969
      env["INSTANCE_DISK%d_MODE" % idx] = mode
970
  else:
971
    disk_count = 0
972

    
973
  env["INSTANCE_DISK_COUNT"] = disk_count
974

    
975
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
976
    for key, value in source.items():
977
      env["INSTANCE_%s_%s" % (kind, key)] = value
978

    
979
  return env
980

    
981

    
982
def _NICListToTuple(lu, nics):
983
  """Build a list of nic information tuples.
984

985
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
986
  value in LUQueryInstanceData.
987

988
  @type lu:  L{LogicalUnit}
989
  @param lu: the logical unit on whose behalf we execute
990
  @type nics: list of L{objects.NIC}
991
  @param nics: list of nics to convert to hooks tuples
992

993
  """
994
  hooks_nics = []
995
  cluster = lu.cfg.GetClusterInfo()
996
  for nic in nics:
997
    ip = nic.ip
998
    mac = nic.mac
999
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
1000
    mode = filled_params[constants.NIC_MODE]
1001
    link = filled_params[constants.NIC_LINK]
1002
    hooks_nics.append((ip, mac, mode, link))
1003
  return hooks_nics
1004

    
1005

    
1006
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
1007
  """Builds instance related env variables for hooks from an object.
1008

1009
  @type lu: L{LogicalUnit}
1010
  @param lu: the logical unit on whose behalf we execute
1011
  @type instance: L{objects.Instance}
1012
  @param instance: the instance for which we should build the
1013
      environment
1014
  @type override: dict
1015
  @param override: dictionary with key/values that will override
1016
      our values
1017
  @rtype: dict
1018
  @return: the hook environment dictionary
1019

1020
  """
1021
  cluster = lu.cfg.GetClusterInfo()
1022
  bep = cluster.FillBE(instance)
1023
  hvp = cluster.FillHV(instance)
1024
  args = {
1025
    'name': instance.name,
1026
    'primary_node': instance.primary_node,
1027
    'secondary_nodes': instance.secondary_nodes,
1028
    'os_type': instance.os,
1029
    'status': instance.admin_up,
1030
    'memory': bep[constants.BE_MEMORY],
1031
    'vcpus': bep[constants.BE_VCPUS],
1032
    'nics': _NICListToTuple(lu, instance.nics),
1033
    'disk_template': instance.disk_template,
1034
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
1035
    'bep': bep,
1036
    'hvp': hvp,
1037
    'hypervisor_name': instance.hypervisor,
1038
  }
1039
  if override:
1040
    args.update(override)
1041
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
1042

    
1043

    
1044
def _AdjustCandidatePool(lu, exceptions):
1045
  """Adjust the candidate pool after node operations.
1046

1047
  """
1048
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1049
  if mod_list:
1050
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1051
               utils.CommaJoin(node.name for node in mod_list))
1052
    for name in mod_list:
1053
      lu.context.ReaddNode(name)
1054
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1055
  if mc_now > mc_max:
1056
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1057
               (mc_now, mc_max))
1058

    
1059

    
1060
def _DecideSelfPromotion(lu, exceptions=None):
1061
  """Decide whether I should promote myself as a master candidate.
1062

1063
  """
1064
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1065
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1066
  # the new node will increase mc_max with one, so:
1067
  mc_should = min(mc_should + 1, cp_size)
1068
  return mc_now < mc_should
1069

    
1070

    
1071
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1072
  """Check that the brigdes needed by a list of nics exist.
1073

1074
  """
1075
  cluster = lu.cfg.GetClusterInfo()
1076
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1077
  brlist = [params[constants.NIC_LINK] for params in paramslist
1078
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1079
  if brlist:
1080
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1081
    result.Raise("Error checking bridges on destination node '%s'" %
1082
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1083

    
1084

    
1085
def _CheckInstanceBridgesExist(lu, instance, node=None):
1086
  """Check that the brigdes needed by an instance exist.
1087

1088
  """
1089
  if node is None:
1090
    node = instance.primary_node
1091
  _CheckNicsBridgesExist(lu, instance.nics, node)
1092

    
1093

    
1094
def _CheckOSVariant(os_obj, name):
1095
  """Check whether an OS name conforms to the os variants specification.
1096

1097
  @type os_obj: L{objects.OS}
1098
  @param os_obj: OS object to check
1099
  @type name: string
1100
  @param name: OS name passed by the user, to check for validity
1101

1102
  """
1103
  if not os_obj.supported_variants:
1104
    return
1105
  variant = objects.OS.GetVariant(name)
1106
  if not variant:
1107
    raise errors.OpPrereqError("OS name must include a variant",
1108
                               errors.ECODE_INVAL)
1109

    
1110
  if variant not in os_obj.supported_variants:
1111
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1112

    
1113

    
1114
def _GetNodeInstancesInner(cfg, fn):
1115
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1116

    
1117

    
1118
def _GetNodeInstances(cfg, node_name):
1119
  """Returns a list of all primary and secondary instances on a node.
1120

1121
  """
1122

    
1123
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1124

    
1125

    
1126
def _GetNodePrimaryInstances(cfg, node_name):
1127
  """Returns primary instances on a node.
1128

1129
  """
1130
  return _GetNodeInstancesInner(cfg,
1131
                                lambda inst: node_name == inst.primary_node)
1132

    
1133

    
1134
def _GetNodeSecondaryInstances(cfg, node_name):
1135
  """Returns secondary instances on a node.
1136

1137
  """
1138
  return _GetNodeInstancesInner(cfg,
1139
                                lambda inst: node_name in inst.secondary_nodes)
1140

    
1141

    
1142
def _GetStorageTypeArgs(cfg, storage_type):
1143
  """Returns the arguments for a storage type.
1144

1145
  """
1146
  # Special case for file storage
1147
  if storage_type == constants.ST_FILE:
1148
    # storage.FileStorage wants a list of storage directories
1149
    return [[cfg.GetFileStorageDir()]]
1150

    
1151
  return []
1152

    
1153

    
1154
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1155
  faulty = []
1156

    
1157
  for dev in instance.disks:
1158
    cfg.SetDiskID(dev, node_name)
1159

    
1160
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1161
  result.Raise("Failed to get disk status from node %s" % node_name,
1162
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1163

    
1164
  for idx, bdev_status in enumerate(result.payload):
1165
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1166
      faulty.append(idx)
1167

    
1168
  return faulty
1169

    
1170

    
1171
def _CheckIAllocatorOrNode(lu, iallocator_slot, node_slot):
1172
  """Check the sanity of iallocator and node arguments and use the
1173
  cluster-wide iallocator if appropriate.
1174

1175
  Check that at most one of (iallocator, node) is specified. If none is
1176
  specified, then the LU's opcode's iallocator slot is filled with the
1177
  cluster-wide default iallocator.
1178

1179
  @type iallocator_slot: string
1180
  @param iallocator_slot: the name of the opcode iallocator slot
1181
  @type node_slot: string
1182
  @param node_slot: the name of the opcode target node slot
1183

1184
  """
1185
  node = getattr(lu.op, node_slot, None)
1186
  iallocator = getattr(lu.op, iallocator_slot, None)
1187

    
1188
  if node is not None and iallocator is not None:
1189
    raise errors.OpPrereqError("Do not specify both, iallocator and node.",
1190
                               errors.ECODE_INVAL)
1191
  elif node is None and iallocator is None:
1192
    default_iallocator = lu.cfg.GetDefaultIAllocator()
1193
    if default_iallocator:
1194
      setattr(lu.op, iallocator_slot, default_iallocator)
1195
    else:
1196
      raise errors.OpPrereqError("No iallocator or node given and no"
1197
                                 " cluster-wide default iallocator found."
1198
                                 " Please specify either an iallocator or a"
1199
                                 " node, or set a cluster-wide default"
1200
                                 " iallocator.")
1201

    
1202

    
1203
class LUPostInitCluster(LogicalUnit):
1204
  """Logical unit for running hooks after cluster initialization.
1205

1206
  """
1207
  HPATH = "cluster-init"
1208
  HTYPE = constants.HTYPE_CLUSTER
1209

    
1210
  def BuildHooksEnv(self):
1211
    """Build hooks env.
1212

1213
    """
1214
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1215
    mn = self.cfg.GetMasterNode()
1216
    return env, [], [mn]
1217

    
1218
  def Exec(self, feedback_fn):
1219
    """Nothing to do.
1220

1221
    """
1222
    return True
1223

    
1224

    
1225
class LUDestroyCluster(LogicalUnit):
1226
  """Logical unit for destroying the cluster.
1227

1228
  """
1229
  HPATH = "cluster-destroy"
1230
  HTYPE = constants.HTYPE_CLUSTER
1231

    
1232
  def BuildHooksEnv(self):
1233
    """Build hooks env.
1234

1235
    """
1236
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1237
    return env, [], []
1238

    
1239
  def CheckPrereq(self):
1240
    """Check prerequisites.
1241

1242
    This checks whether the cluster is empty.
1243

1244
    Any errors are signaled by raising errors.OpPrereqError.
1245

1246
    """
1247
    master = self.cfg.GetMasterNode()
1248

    
1249
    nodelist = self.cfg.GetNodeList()
1250
    if len(nodelist) != 1 or nodelist[0] != master:
1251
      raise errors.OpPrereqError("There are still %d node(s) in"
1252
                                 " this cluster." % (len(nodelist) - 1),
1253
                                 errors.ECODE_INVAL)
1254
    instancelist = self.cfg.GetInstanceList()
1255
    if instancelist:
1256
      raise errors.OpPrereqError("There are still %d instance(s) in"
1257
                                 " this cluster." % len(instancelist),
1258
                                 errors.ECODE_INVAL)
1259

    
1260
  def Exec(self, feedback_fn):
1261
    """Destroys the cluster.
1262

1263
    """
1264
    master = self.cfg.GetMasterNode()
1265
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1266

    
1267
    # Run post hooks on master node before it's removed
1268
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1269
    try:
1270
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1271
    except:
1272
      # pylint: disable-msg=W0702
1273
      self.LogWarning("Errors occurred running hooks on %s" % master)
1274

    
1275
    result = self.rpc.call_node_stop_master(master, False)
1276
    result.Raise("Could not disable the master role")
1277

    
1278
    if modify_ssh_setup:
1279
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1280
      utils.CreateBackup(priv_key)
1281
      utils.CreateBackup(pub_key)
1282

    
1283
    return master
1284

    
1285

    
1286
def _VerifyCertificate(filename):
1287
  """Verifies a certificate for LUVerifyCluster.
1288

1289
  @type filename: string
1290
  @param filename: Path to PEM file
1291

1292
  """
1293
  try:
1294
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1295
                                           utils.ReadFile(filename))
1296
  except Exception, err: # pylint: disable-msg=W0703
1297
    return (LUVerifyCluster.ETYPE_ERROR,
1298
            "Failed to load X509 certificate %s: %s" % (filename, err))
1299

    
1300
  (errcode, msg) = \
1301
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1302
                                constants.SSL_CERT_EXPIRATION_ERROR)
1303

    
1304
  if msg:
1305
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1306
  else:
1307
    fnamemsg = None
1308

    
1309
  if errcode is None:
1310
    return (None, fnamemsg)
1311
  elif errcode == utils.CERT_WARNING:
1312
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1313
  elif errcode == utils.CERT_ERROR:
1314
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1315

    
1316
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1317

    
1318

    
1319
class LUVerifyCluster(LogicalUnit):
1320
  """Verifies the cluster status.
1321

1322
  """
1323
  HPATH = "cluster-verify"
1324
  HTYPE = constants.HTYPE_CLUSTER
1325
  _OP_PARAMS = [
1326
    ("skip_checks", _EmptyList,
1327
     _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1328
    ("verbose", False, _TBool),
1329
    ("error_codes", False, _TBool),
1330
    ("debug_simulate_errors", False, _TBool),
1331
    ]
1332
  REQ_BGL = False
1333

    
1334
  TCLUSTER = "cluster"
1335
  TNODE = "node"
1336
  TINSTANCE = "instance"
1337

    
1338
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1339
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1340
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1341
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1342
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1343
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1344
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1345
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1346
  ENODEDRBD = (TNODE, "ENODEDRBD")
1347
  ENODEDRBDHELPER = (TNODE, "ENODEDRBDHELPER")
1348
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1349
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1350
  ENODEHV = (TNODE, "ENODEHV")
1351
  ENODELVM = (TNODE, "ENODELVM")
1352
  ENODEN1 = (TNODE, "ENODEN1")
1353
  ENODENET = (TNODE, "ENODENET")
1354
  ENODEOS = (TNODE, "ENODEOS")
1355
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1356
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1357
  ENODERPC = (TNODE, "ENODERPC")
1358
  ENODESSH = (TNODE, "ENODESSH")
1359
  ENODEVERSION = (TNODE, "ENODEVERSION")
1360
  ENODESETUP = (TNODE, "ENODESETUP")
1361
  ENODETIME = (TNODE, "ENODETIME")
1362

    
1363
  ETYPE_FIELD = "code"
1364
  ETYPE_ERROR = "ERROR"
1365
  ETYPE_WARNING = "WARNING"
1366

    
1367
  class NodeImage(object):
1368
    """A class representing the logical and physical status of a node.
1369

1370
    @type name: string
1371
    @ivar name: the node name to which this object refers
1372
    @ivar volumes: a structure as returned from
1373
        L{ganeti.backend.GetVolumeList} (runtime)
1374
    @ivar instances: a list of running instances (runtime)
1375
    @ivar pinst: list of configured primary instances (config)
1376
    @ivar sinst: list of configured secondary instances (config)
1377
    @ivar sbp: diction of {secondary-node: list of instances} of all peers
1378
        of this node (config)
1379
    @ivar mfree: free memory, as reported by hypervisor (runtime)
1380
    @ivar dfree: free disk, as reported by the node (runtime)
1381
    @ivar offline: the offline status (config)
1382
    @type rpc_fail: boolean
1383
    @ivar rpc_fail: whether the RPC verify call was successfull (overall,
1384
        not whether the individual keys were correct) (runtime)
1385
    @type lvm_fail: boolean
1386
    @ivar lvm_fail: whether the RPC call didn't return valid LVM data
1387
    @type hyp_fail: boolean
1388
    @ivar hyp_fail: whether the RPC call didn't return the instance list
1389
    @type ghost: boolean
1390
    @ivar ghost: whether this is a known node or not (config)
1391
    @type os_fail: boolean
1392
    @ivar os_fail: whether the RPC call didn't return valid OS data
1393
    @type oslist: list
1394
    @ivar oslist: list of OSes as diagnosed by DiagnoseOS
1395

1396
    """
1397
    def __init__(self, offline=False, name=None):
1398
      self.name = name
1399
      self.volumes = {}
1400
      self.instances = []
1401
      self.pinst = []
1402
      self.sinst = []
1403
      self.sbp = {}
1404
      self.mfree = 0
1405
      self.dfree = 0
1406
      self.offline = offline
1407
      self.rpc_fail = False
1408
      self.lvm_fail = False
1409
      self.hyp_fail = False
1410
      self.ghost = False
1411
      self.os_fail = False
1412
      self.oslist = {}
1413

    
1414
  def ExpandNames(self):
1415
    self.needed_locks = {
1416
      locking.LEVEL_NODE: locking.ALL_SET,
1417
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1418
    }
1419
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1420

    
1421
  def _Error(self, ecode, item, msg, *args, **kwargs):
1422
    """Format an error message.
1423

1424
    Based on the opcode's error_codes parameter, either format a
1425
    parseable error code, or a simpler error string.
1426

1427
    This must be called only from Exec and functions called from Exec.
1428

1429
    """
1430
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1431
    itype, etxt = ecode
1432
    # first complete the msg
1433
    if args:
1434
      msg = msg % args
1435
    # then format the whole message
1436
    if self.op.error_codes:
1437
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1438
    else:
1439
      if item:
1440
        item = " " + item
1441
      else:
1442
        item = ""
1443
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1444
    # and finally report it via the feedback_fn
1445
    self._feedback_fn("  - %s" % msg)
1446

    
1447
  def _ErrorIf(self, cond, *args, **kwargs):
1448
    """Log an error message if the passed condition is True.
1449

1450
    """
1451
    cond = bool(cond) or self.op.debug_simulate_errors
1452
    if cond:
1453
      self._Error(*args, **kwargs)
1454
    # do not mark the operation as failed for WARN cases only
1455
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1456
      self.bad = self.bad or cond
1457

    
1458
  def _VerifyNode(self, ninfo, nresult):
1459
    """Perform some basic validation on data returned from a node.
1460

1461
      - check the result data structure is well formed and has all the
1462
        mandatory fields
1463
      - check ganeti version
1464

1465
    @type ninfo: L{objects.Node}
1466
    @param ninfo: the node to check
1467
    @param nresult: the results from the node
1468
    @rtype: boolean
1469
    @return: whether overall this call was successful (and we can expect
1470
         reasonable values in the respose)
1471

1472
    """
1473
    node = ninfo.name
1474
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1475

    
1476
    # main result, nresult should be a non-empty dict
1477
    test = not nresult or not isinstance(nresult, dict)
1478
    _ErrorIf(test, self.ENODERPC, node,
1479
                  "unable to verify node: no data returned")
1480
    if test:
1481
      return False
1482

    
1483
    # compares ganeti version
1484
    local_version = constants.PROTOCOL_VERSION
1485
    remote_version = nresult.get("version", None)
1486
    test = not (remote_version and
1487
                isinstance(remote_version, (list, tuple)) and
1488
                len(remote_version) == 2)
1489
    _ErrorIf(test, self.ENODERPC, node,
1490
             "connection to node returned invalid data")
1491
    if test:
1492
      return False
1493

    
1494
    test = local_version != remote_version[0]
1495
    _ErrorIf(test, self.ENODEVERSION, node,
1496
             "incompatible protocol versions: master %s,"
1497
             " node %s", local_version, remote_version[0])
1498
    if test:
1499
      return False
1500

    
1501
    # node seems compatible, we can actually try to look into its results
1502

    
1503
    # full package version
1504
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1505
                  self.ENODEVERSION, node,
1506
                  "software version mismatch: master %s, node %s",
1507
                  constants.RELEASE_VERSION, remote_version[1],
1508
                  code=self.ETYPE_WARNING)
1509

    
1510
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1511
    if isinstance(hyp_result, dict):
1512
      for hv_name, hv_result in hyp_result.iteritems():
1513
        test = hv_result is not None
1514
        _ErrorIf(test, self.ENODEHV, node,
1515
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1516

    
1517

    
1518
    test = nresult.get(constants.NV_NODESETUP,
1519
                           ["Missing NODESETUP results"])
1520
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1521
             "; ".join(test))
1522

    
1523
    return True
1524

    
1525
  def _VerifyNodeTime(self, ninfo, nresult,
1526
                      nvinfo_starttime, nvinfo_endtime):
1527
    """Check the node time.
1528

1529
    @type ninfo: L{objects.Node}
1530
    @param ninfo: the node to check
1531
    @param nresult: the remote results for the node
1532
    @param nvinfo_starttime: the start time of the RPC call
1533
    @param nvinfo_endtime: the end time of the RPC call
1534

1535
    """
1536
    node = ninfo.name
1537
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1538

    
1539
    ntime = nresult.get(constants.NV_TIME, None)
1540
    try:
1541
      ntime_merged = utils.MergeTime(ntime)
1542
    except (ValueError, TypeError):
1543
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1544
      return
1545

    
1546
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1547
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1548
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1549
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1550
    else:
1551
      ntime_diff = None
1552

    
1553
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1554
             "Node time diverges by at least %s from master node time",
1555
             ntime_diff)
1556

    
1557
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1558
    """Check the node time.
1559

1560
    @type ninfo: L{objects.Node}
1561
    @param ninfo: the node to check
1562
    @param nresult: the remote results for the node
1563
    @param vg_name: the configured VG name
1564

1565
    """
1566
    if vg_name is None:
1567
      return
1568

    
1569
    node = ninfo.name
1570
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1571

    
1572
    # checks vg existence and size > 20G
1573
    vglist = nresult.get(constants.NV_VGLIST, None)
1574
    test = not vglist
1575
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1576
    if not test:
1577
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1578
                                            constants.MIN_VG_SIZE)
1579
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1580

    
1581
    # check pv names
1582
    pvlist = nresult.get(constants.NV_PVLIST, None)
1583
    test = pvlist is None
1584
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1585
    if not test:
1586
      # check that ':' is not present in PV names, since it's a
1587
      # special character for lvcreate (denotes the range of PEs to
1588
      # use on the PV)
1589
      for _, pvname, owner_vg in pvlist:
1590
        test = ":" in pvname
1591
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1592
                 " '%s' of VG '%s'", pvname, owner_vg)
1593

    
1594
  def _VerifyNodeNetwork(self, ninfo, nresult):
1595
    """Check the node time.
1596

1597
    @type ninfo: L{objects.Node}
1598
    @param ninfo: the node to check
1599
    @param nresult: the remote results for the node
1600

1601
    """
1602
    node = ninfo.name
1603
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1604

    
1605
    test = constants.NV_NODELIST not in nresult
1606
    _ErrorIf(test, self.ENODESSH, node,
1607
             "node hasn't returned node ssh connectivity data")
1608
    if not test:
1609
      if nresult[constants.NV_NODELIST]:
1610
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1611
          _ErrorIf(True, self.ENODESSH, node,
1612
                   "ssh communication with node '%s': %s", a_node, a_msg)
1613

    
1614
    test = constants.NV_NODENETTEST not in nresult
1615
    _ErrorIf(test, self.ENODENET, node,
1616
             "node hasn't returned node tcp connectivity data")
1617
    if not test:
1618
      if nresult[constants.NV_NODENETTEST]:
1619
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1620
        for anode in nlist:
1621
          _ErrorIf(True, self.ENODENET, node,
1622
                   "tcp communication with node '%s': %s",
1623
                   anode, nresult[constants.NV_NODENETTEST][anode])
1624

    
1625
    test = constants.NV_MASTERIP not in nresult
1626
    _ErrorIf(test, self.ENODENET, node,
1627
             "node hasn't returned node master IP reachability data")
1628
    if not test:
1629
      if not nresult[constants.NV_MASTERIP]:
1630
        if node == self.master_node:
1631
          msg = "the master node cannot reach the master IP (not configured?)"
1632
        else:
1633
          msg = "cannot reach the master IP"
1634
        _ErrorIf(True, self.ENODENET, node, msg)
1635

    
1636

    
1637
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1638
    """Verify an instance.
1639

1640
    This function checks to see if the required block devices are
1641
    available on the instance's node.
1642

1643
    """
1644
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1645
    node_current = instanceconfig.primary_node
1646

    
1647
    node_vol_should = {}
1648
    instanceconfig.MapLVsByNode(node_vol_should)
1649

    
1650
    for node in node_vol_should:
1651
      n_img = node_image[node]
1652
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1653
        # ignore missing volumes on offline or broken nodes
1654
        continue
1655
      for volume in node_vol_should[node]:
1656
        test = volume not in n_img.volumes
1657
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1658
                 "volume %s missing on node %s", volume, node)
1659

    
1660
    if instanceconfig.admin_up:
1661
      pri_img = node_image[node_current]
1662
      test = instance not in pri_img.instances and not pri_img.offline
1663
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1664
               "instance not running on its primary node %s",
1665
               node_current)
1666

    
1667
    for node, n_img in node_image.items():
1668
      if (not node == node_current):
1669
        test = instance in n_img.instances
1670
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1671
                 "instance should not run on node %s", node)
1672

    
1673
  def _VerifyOrphanVolumes(self, node_vol_should, node_image, reserved):
1674
    """Verify if there are any unknown volumes in the cluster.
1675

1676
    The .os, .swap and backup volumes are ignored. All other volumes are
1677
    reported as unknown.
1678

1679
    @type reserved: L{ganeti.utils.FieldSet}
1680
    @param reserved: a FieldSet of reserved volume names
1681

1682
    """
1683
    for node, n_img in node_image.items():
1684
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1685
        # skip non-healthy nodes
1686
        continue
1687
      for volume in n_img.volumes:
1688
        test = ((node not in node_vol_should or
1689
                volume not in node_vol_should[node]) and
1690
                not reserved.Matches(volume))
1691
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1692
                      "volume %s is unknown", volume)
1693

    
1694
  def _VerifyOrphanInstances(self, instancelist, node_image):
1695
    """Verify the list of running instances.
1696

1697
    This checks what instances are running but unknown to the cluster.
1698

1699
    """
1700
    for node, n_img in node_image.items():
1701
      for o_inst in n_img.instances:
1702
        test = o_inst not in instancelist
1703
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1704
                      "instance %s on node %s should not exist", o_inst, node)
1705

    
1706
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1707
    """Verify N+1 Memory Resilience.
1708

1709
    Check that if one single node dies we can still start all the
1710
    instances it was primary for.
1711

1712
    """
1713
    for node, n_img in node_image.items():
1714
      # This code checks that every node which is now listed as
1715
      # secondary has enough memory to host all instances it is
1716
      # supposed to should a single other node in the cluster fail.
1717
      # FIXME: not ready for failover to an arbitrary node
1718
      # FIXME: does not support file-backed instances
1719
      # WARNING: we currently take into account down instances as well
1720
      # as up ones, considering that even if they're down someone
1721
      # might want to start them even in the event of a node failure.
1722
      for prinode, instances in n_img.sbp.items():
1723
        needed_mem = 0
1724
        for instance in instances:
1725
          bep = self.cfg.GetClusterInfo().FillBE(instance_cfg[instance])
1726
          if bep[constants.BE_AUTO_BALANCE]:
1727
            needed_mem += bep[constants.BE_MEMORY]
1728
        test = n_img.mfree < needed_mem
1729
        self._ErrorIf(test, self.ENODEN1, node,
1730
                      "not enough memory on to accommodate"
1731
                      " failovers should peer node %s fail", prinode)
1732

    
1733
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1734
                       master_files):
1735
    """Verifies and computes the node required file checksums.
1736

1737
    @type ninfo: L{objects.Node}
1738
    @param ninfo: the node to check
1739
    @param nresult: the remote results for the node
1740
    @param file_list: required list of files
1741
    @param local_cksum: dictionary of local files and their checksums
1742
    @param master_files: list of files that only masters should have
1743

1744
    """
1745
    node = ninfo.name
1746
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1747

    
1748
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1749
    test = not isinstance(remote_cksum, dict)
1750
    _ErrorIf(test, self.ENODEFILECHECK, node,
1751
             "node hasn't returned file checksum data")
1752
    if test:
1753
      return
1754

    
1755
    for file_name in file_list:
1756
      node_is_mc = ninfo.master_candidate
1757
      must_have = (file_name not in master_files) or node_is_mc
1758
      # missing
1759
      test1 = file_name not in remote_cksum
1760
      # invalid checksum
1761
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1762
      # existing and good
1763
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1764
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1765
               "file '%s' missing", file_name)
1766
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1767
               "file '%s' has wrong checksum", file_name)
1768
      # not candidate and this is not a must-have file
1769
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1770
               "file '%s' should not exist on non master"
1771
               " candidates (and the file is outdated)", file_name)
1772
      # all good, except non-master/non-must have combination
1773
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1774
               "file '%s' should not exist"
1775
               " on non master candidates", file_name)
1776

    
1777
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_helper,
1778
                      drbd_map):
1779
    """Verifies and the node DRBD status.
1780

1781
    @type ninfo: L{objects.Node}
1782
    @param ninfo: the node to check
1783
    @param nresult: the remote results for the node
1784
    @param instanceinfo: the dict of instances
1785
    @param drbd_helper: the configured DRBD usermode helper
1786
    @param drbd_map: the DRBD map as returned by
1787
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1788

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

    
1793
    if drbd_helper:
1794
      helper_result = nresult.get(constants.NV_DRBDHELPER, None)
1795
      test = (helper_result == None)
1796
      _ErrorIf(test, self.ENODEDRBDHELPER, node,
1797
               "no drbd usermode helper returned")
1798
      if helper_result:
1799
        status, payload = helper_result
1800
        test = not status
1801
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1802
                 "drbd usermode helper check unsuccessful: %s", payload)
1803
        test = status and (payload != drbd_helper)
1804
        _ErrorIf(test, self.ENODEDRBDHELPER, node,
1805
                 "wrong drbd usermode helper: %s", payload)
1806

    
1807
    # compute the DRBD minors
1808
    node_drbd = {}
1809
    for minor, instance in drbd_map[node].items():
1810
      test = instance not in instanceinfo
1811
      _ErrorIf(test, self.ECLUSTERCFG, None,
1812
               "ghost instance '%s' in temporary DRBD map", instance)
1813
        # ghost instance should not be running, but otherwise we
1814
        # don't give double warnings (both ghost instance and
1815
        # unallocated minor in use)
1816
      if test:
1817
        node_drbd[minor] = (instance, False)
1818
      else:
1819
        instance = instanceinfo[instance]
1820
        node_drbd[minor] = (instance.name, instance.admin_up)
1821

    
1822
    # and now check them
1823
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1824
    test = not isinstance(used_minors, (tuple, list))
1825
    _ErrorIf(test, self.ENODEDRBD, node,
1826
             "cannot parse drbd status file: %s", str(used_minors))
1827
    if test:
1828
      # we cannot check drbd status
1829
      return
1830

    
1831
    for minor, (iname, must_exist) in node_drbd.items():
1832
      test = minor not in used_minors and must_exist
1833
      _ErrorIf(test, self.ENODEDRBD, node,
1834
               "drbd minor %d of instance %s is not active", minor, iname)
1835
    for minor in used_minors:
1836
      test = minor not in node_drbd
1837
      _ErrorIf(test, self.ENODEDRBD, node,
1838
               "unallocated drbd minor %d is in use", minor)
1839

    
1840
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1841
    """Builds the node OS structures.
1842

1843
    @type ninfo: L{objects.Node}
1844
    @param ninfo: the node to check
1845
    @param nresult: the remote results for the node
1846
    @param nimg: the node image object
1847

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

    
1852
    remote_os = nresult.get(constants.NV_OSLIST, None)
1853
    test = (not isinstance(remote_os, list) or
1854
            not compat.all(isinstance(v, list) and len(v) == 7
1855
                           for v in remote_os))
1856

    
1857
    _ErrorIf(test, self.ENODEOS, node,
1858
             "node hasn't returned valid OS data")
1859

    
1860
    nimg.os_fail = test
1861

    
1862
    if test:
1863
      return
1864

    
1865
    os_dict = {}
1866

    
1867
    for (name, os_path, status, diagnose,
1868
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1869

    
1870
      if name not in os_dict:
1871
        os_dict[name] = []
1872

    
1873
      # parameters is a list of lists instead of list of tuples due to
1874
      # JSON lacking a real tuple type, fix it:
1875
      parameters = [tuple(v) for v in parameters]
1876
      os_dict[name].append((os_path, status, diagnose,
1877
                            set(variants), set(parameters), set(api_ver)))
1878

    
1879
    nimg.oslist = os_dict
1880

    
1881
  def _VerifyNodeOS(self, ninfo, nimg, base):
1882
    """Verifies the node OS list.
1883

1884
    @type ninfo: L{objects.Node}
1885
    @param ninfo: the node to check
1886
    @param nimg: the node image object
1887
    @param base: the 'template' node we match against (e.g. from the master)
1888

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

    
1893
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1894

    
1895
    for os_name, os_data in nimg.oslist.items():
1896
      assert os_data, "Empty OS status for OS %s?!" % os_name
1897
      f_path, f_status, f_diag, f_var, f_param, f_api = os_data[0]
1898
      _ErrorIf(not f_status, self.ENODEOS, node,
1899
               "Invalid OS %s (located at %s): %s", os_name, f_path, f_diag)
1900
      _ErrorIf(len(os_data) > 1, self.ENODEOS, node,
1901
               "OS '%s' has multiple entries (first one shadows the rest): %s",
1902
               os_name, utils.CommaJoin([v[0] for v in os_data]))
1903
      # this will catched in backend too
1904
      _ErrorIf(compat.any(v >= constants.OS_API_V15 for v in f_api)
1905
               and not f_var, self.ENODEOS, node,
1906
               "OS %s with API at least %d does not declare any variant",
1907
               os_name, constants.OS_API_V15)
1908
      # comparisons with the 'base' image
1909
      test = os_name not in base.oslist
1910
      _ErrorIf(test, self.ENODEOS, node,
1911
               "Extra OS %s not present on reference node (%s)",
1912
               os_name, base.name)
1913
      if test:
1914
        continue
1915
      assert base.oslist[os_name], "Base node has empty OS status?"
1916
      _, b_status, _, b_var, b_param, b_api = base.oslist[os_name][0]
1917
      if not b_status:
1918
        # base OS is invalid, skipping
1919
        continue
1920
      for kind, a, b in [("API version", f_api, b_api),
1921
                         ("variants list", f_var, b_var),
1922
                         ("parameters", f_param, b_param)]:
1923
        _ErrorIf(a != b, self.ENODEOS, node,
1924
                 "OS %s %s differs from reference node %s: %s vs. %s",
1925
                 kind, os_name, base.name,
1926
                 utils.CommaJoin(a), utils.CommaJoin(b))
1927

    
1928
    # check any missing OSes
1929
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1930
    _ErrorIf(missing, self.ENODEOS, node,
1931
             "OSes present on reference node %s but missing on this node: %s",
1932
             base.name, utils.CommaJoin(missing))
1933

    
1934
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1935
    """Verifies and updates the node volume data.
1936

1937
    This function will update a L{NodeImage}'s internal structures
1938
    with data from the remote call.
1939

1940
    @type ninfo: L{objects.Node}
1941
    @param ninfo: the node to check
1942
    @param nresult: the remote results for the node
1943
    @param nimg: the node image object
1944
    @param vg_name: the configured VG name
1945

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

    
1950
    nimg.lvm_fail = True
1951
    lvdata = nresult.get(constants.NV_LVLIST, "Missing LV data")
1952
    if vg_name is None:
1953
      pass
1954
    elif isinstance(lvdata, basestring):
1955
      _ErrorIf(True, self.ENODELVM, node, "LVM problem on node: %s",
1956
               utils.SafeEncode(lvdata))
1957
    elif not isinstance(lvdata, dict):
1958
      _ErrorIf(True, self.ENODELVM, node, "rpc call to node failed (lvlist)")
1959
    else:
1960
      nimg.volumes = lvdata
1961
      nimg.lvm_fail = False
1962

    
1963
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1964
    """Verifies and updates the node instance list.
1965

1966
    If the listing was successful, then updates this node's instance
1967
    list. Otherwise, it marks the RPC call as failed for the instance
1968
    list key.
1969

1970
    @type ninfo: L{objects.Node}
1971
    @param ninfo: the node to check
1972
    @param nresult: the remote results for the node
1973
    @param nimg: the node image object
1974

1975
    """
1976
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1977
    test = not isinstance(idata, list)
1978
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1979
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1980
    if test:
1981
      nimg.hyp_fail = True
1982
    else:
1983
      nimg.instances = idata
1984

    
1985
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1986
    """Verifies and computes a node information map
1987

1988
    @type ninfo: L{objects.Node}
1989
    @param ninfo: the node to check
1990
    @param nresult: the remote results for the node
1991
    @param nimg: the node image object
1992
    @param vg_name: the configured VG name
1993

1994
    """
1995
    node = ninfo.name
1996
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1997

    
1998
    # try to read free memory (from the hypervisor)
1999
    hv_info = nresult.get(constants.NV_HVINFO, None)
2000
    test = not isinstance(hv_info, dict) or "memory_free" not in hv_info
2001
    _ErrorIf(test, self.ENODEHV, node, "rpc call to node failed (hvinfo)")
2002
    if not test:
2003
      try:
2004
        nimg.mfree = int(hv_info["memory_free"])
2005
      except (ValueError, TypeError):
2006
        _ErrorIf(True, self.ENODERPC, node,
2007
                 "node returned invalid nodeinfo, check hypervisor")
2008

    
2009
    # FIXME: devise a free space model for file based instances as well
2010
    if vg_name is not None:
2011
      test = (constants.NV_VGLIST not in nresult or
2012
              vg_name not in nresult[constants.NV_VGLIST])
2013
      _ErrorIf(test, self.ENODELVM, node,
2014
               "node didn't return data for the volume group '%s'"
2015
               " - it is either missing or broken", vg_name)
2016
      if not test:
2017
        try:
2018
          nimg.dfree = int(nresult[constants.NV_VGLIST][vg_name])
2019
        except (ValueError, TypeError):
2020
          _ErrorIf(True, self.ENODERPC, node,
2021
                   "node returned invalid LVM info, check LVM status")
2022

    
2023
  def BuildHooksEnv(self):
2024
    """Build hooks env.
2025

2026
    Cluster-Verify hooks just ran in the post phase and their failure makes
2027
    the output be logged in the verify output and the verification to fail.
2028

2029
    """
2030
    all_nodes = self.cfg.GetNodeList()
2031
    env = {
2032
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
2033
      }
2034
    for node in self.cfg.GetAllNodesInfo().values():
2035
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
2036

    
2037
    return env, [], all_nodes
2038

    
2039
  def Exec(self, feedback_fn):
2040
    """Verify integrity of cluster, performing various test on nodes.
2041

2042
    """
2043
    self.bad = False
2044
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
2045
    verbose = self.op.verbose
2046
    self._feedback_fn = feedback_fn
2047
    feedback_fn("* Verifying global settings")
2048
    for msg in self.cfg.VerifyConfig():
2049
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
2050

    
2051
    # Check the cluster certificates
2052
    for cert_filename in constants.ALL_CERT_FILES:
2053
      (errcode, msg) = _VerifyCertificate(cert_filename)
2054
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
2055

    
2056
    vg_name = self.cfg.GetVGName()
2057
    drbd_helper = self.cfg.GetDRBDHelper()
2058
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
2059
    cluster = self.cfg.GetClusterInfo()
2060
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
2061
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
2062
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
2063
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
2064
                        for iname in instancelist)
2065
    i_non_redundant = [] # Non redundant instances
2066
    i_non_a_balanced = [] # Non auto-balanced instances
2067
    n_offline = 0 # Count of offline nodes
2068
    n_drained = 0 # Count of nodes being drained
2069
    node_vol_should = {}
2070

    
2071
    # FIXME: verify OS list
2072
    # do local checksums
2073
    master_files = [constants.CLUSTER_CONF_FILE]
2074
    master_node = self.master_node = self.cfg.GetMasterNode()
2075
    master_ip = self.cfg.GetMasterIP()
2076

    
2077
    file_names = ssconf.SimpleStore().GetFileList()
2078
    file_names.extend(constants.ALL_CERT_FILES)
2079
    file_names.extend(master_files)
2080
    if cluster.modify_etc_hosts:
2081
      file_names.append(constants.ETC_HOSTS)
2082

    
2083
    local_checksums = utils.FingerprintFiles(file_names)
2084

    
2085
    feedback_fn("* Gathering data (%d nodes)" % len(nodelist))
2086
    node_verify_param = {
2087
      constants.NV_FILELIST: file_names,
2088
      constants.NV_NODELIST: [node.name for node in nodeinfo
2089
                              if not node.offline],
2090
      constants.NV_HYPERVISOR: hypervisors,
2091
      constants.NV_NODENETTEST: [(node.name, node.primary_ip,
2092
                                  node.secondary_ip) for node in nodeinfo
2093
                                 if not node.offline],
2094
      constants.NV_INSTANCELIST: hypervisors,
2095
      constants.NV_VERSION: None,
2096
      constants.NV_HVINFO: self.cfg.GetHypervisorType(),
2097
      constants.NV_NODESETUP: None,
2098
      constants.NV_TIME: None,
2099
      constants.NV_MASTERIP: (master_node, master_ip),
2100
      constants.NV_OSLIST: None,
2101
      }
2102

    
2103
    if vg_name is not None:
2104
      node_verify_param[constants.NV_VGLIST] = None
2105
      node_verify_param[constants.NV_LVLIST] = vg_name
2106
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2107
      node_verify_param[constants.NV_DRBDLIST] = None
2108

    
2109
    if drbd_helper:
2110
      node_verify_param[constants.NV_DRBDHELPER] = drbd_helper
2111

    
2112
    # Build our expected cluster state
2113
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2114
                                                 name=node.name))
2115
                      for node in nodeinfo)
2116

    
2117
    for instance in instancelist:
2118
      inst_config = instanceinfo[instance]
2119

    
2120
      for nname in inst_config.all_nodes:
2121
        if nname not in node_image:
2122
          # ghost node
2123
          gnode = self.NodeImage(name=nname)
2124
          gnode.ghost = True
2125
          node_image[nname] = gnode
2126

    
2127
      inst_config.MapLVsByNode(node_vol_should)
2128

    
2129
      pnode = inst_config.primary_node
2130
      node_image[pnode].pinst.append(instance)
2131

    
2132
      for snode in inst_config.secondary_nodes:
2133
        nimg = node_image[snode]
2134
        nimg.sinst.append(instance)
2135
        if pnode not in nimg.sbp:
2136
          nimg.sbp[pnode] = []
2137
        nimg.sbp[pnode].append(instance)
2138

    
2139
    # At this point, we have the in-memory data structures complete,
2140
    # except for the runtime information, which we'll gather next
2141

    
2142
    # Due to the way our RPC system works, exact response times cannot be
2143
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2144
    # time before and after executing the request, we can at least have a time
2145
    # window.
2146
    nvinfo_starttime = time.time()
2147
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2148
                                           self.cfg.GetClusterName())
2149
    nvinfo_endtime = time.time()
2150

    
2151
    all_drbd_map = self.cfg.ComputeDRBDMap()
2152

    
2153
    feedback_fn("* Verifying node status")
2154

    
2155
    refos_img = None
2156

    
2157
    for node_i in nodeinfo:
2158
      node = node_i.name
2159
      nimg = node_image[node]
2160

    
2161
      if node_i.offline:
2162
        if verbose:
2163
          feedback_fn("* Skipping offline node %s" % (node,))
2164
        n_offline += 1
2165
        continue
2166

    
2167
      if node == master_node:
2168
        ntype = "master"
2169
      elif node_i.master_candidate:
2170
        ntype = "master candidate"
2171
      elif node_i.drained:
2172
        ntype = "drained"
2173
        n_drained += 1
2174
      else:
2175
        ntype = "regular"
2176
      if verbose:
2177
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2178

    
2179
      msg = all_nvinfo[node].fail_msg
2180
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2181
      if msg:
2182
        nimg.rpc_fail = True
2183
        continue
2184

    
2185
      nresult = all_nvinfo[node].payload
2186

    
2187
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2188
      self._VerifyNodeNetwork(node_i, nresult)
2189
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2190
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2191
                            master_files)
2192
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, drbd_helper,
2193
                           all_drbd_map)
2194
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2195

    
2196
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2197
      self._UpdateNodeInstances(node_i, nresult, nimg)
2198
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2199
      self._UpdateNodeOS(node_i, nresult, nimg)
2200
      if not nimg.os_fail:
2201
        if refos_img is None:
2202
          refos_img = nimg
2203
        self._VerifyNodeOS(node_i, nimg, refos_img)
2204

    
2205
    feedback_fn("* Verifying instance status")
2206
    for instance in instancelist:
2207
      if verbose:
2208
        feedback_fn("* Verifying instance %s" % instance)
2209
      inst_config = instanceinfo[instance]
2210
      self._VerifyInstance(instance, inst_config, node_image)
2211
      inst_nodes_offline = []
2212

    
2213
      pnode = inst_config.primary_node
2214
      pnode_img = node_image[pnode]
2215
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2216
               self.ENODERPC, pnode, "instance %s, connection to"
2217
               " primary node failed", instance)
2218

    
2219
      if pnode_img.offline:
2220
        inst_nodes_offline.append(pnode)
2221

    
2222
      # If the instance is non-redundant we cannot survive losing its primary
2223
      # node, so we are not N+1 compliant. On the other hand we have no disk
2224
      # templates with more than one secondary so that situation is not well
2225
      # supported either.
2226
      # FIXME: does not support file-backed instances
2227
      if not inst_config.secondary_nodes:
2228
        i_non_redundant.append(instance)
2229
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2230
               instance, "instance has multiple secondary nodes: %s",
2231
               utils.CommaJoin(inst_config.secondary_nodes),
2232
               code=self.ETYPE_WARNING)
2233

    
2234
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2235
        i_non_a_balanced.append(instance)
2236

    
2237
      for snode in inst_config.secondary_nodes:
2238
        s_img = node_image[snode]
2239
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2240
                 "instance %s, connection to secondary node failed", instance)
2241

    
2242
        if s_img.offline:
2243
          inst_nodes_offline.append(snode)
2244

    
2245
      # warn that the instance lives on offline nodes
2246
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2247
               "instance lives on offline node(s) %s",
2248
               utils.CommaJoin(inst_nodes_offline))
2249
      # ... or ghost nodes
2250
      for node in inst_config.all_nodes:
2251
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2252
                 "instance lives on ghost node %s", node)
2253

    
2254
    feedback_fn("* Verifying orphan volumes")
2255
    reserved = utils.FieldSet(*cluster.reserved_lvs)
2256
    self._VerifyOrphanVolumes(node_vol_should, node_image, reserved)
2257

    
2258
    feedback_fn("* Verifying orphan instances")
2259
    self._VerifyOrphanInstances(instancelist, node_image)
2260

    
2261
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2262
      feedback_fn("* Verifying N+1 Memory redundancy")
2263
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2264

    
2265
    feedback_fn("* Other Notes")
2266
    if i_non_redundant:
2267
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2268
                  % len(i_non_redundant))
2269

    
2270
    if i_non_a_balanced:
2271
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2272
                  % len(i_non_a_balanced))
2273

    
2274
    if n_offline:
2275
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2276

    
2277
    if n_drained:
2278
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2279

    
2280
    return not self.bad
2281

    
2282
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2283
    """Analyze the post-hooks' result
2284

2285
    This method analyses the hook result, handles it, and sends some
2286
    nicely-formatted feedback back to the user.
2287

2288
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2289
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2290
    @param hooks_results: the results of the multi-node hooks rpc call
2291
    @param feedback_fn: function used send feedback back to the caller
2292
    @param lu_result: previous Exec result
2293
    @return: the new Exec result, based on the previous result
2294
        and hook results
2295

2296
    """
2297
    # We only really run POST phase hooks, and are only interested in
2298
    # their results
2299
    if phase == constants.HOOKS_PHASE_POST:
2300
      # Used to change hooks' output to proper indentation
2301
      indent_re = re.compile('^', re.M)
2302
      feedback_fn("* Hooks Results")
2303
      assert hooks_results, "invalid result from hooks"
2304

    
2305
      for node_name in hooks_results:
2306
        res = hooks_results[node_name]
2307
        msg = res.fail_msg
2308
        test = msg and not res.offline
2309
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2310
                      "Communication failure in hooks execution: %s", msg)
2311
        if res.offline or msg:
2312
          # No need to investigate payload if node is offline or gave an error.
2313
          # override manually lu_result here as _ErrorIf only
2314
          # overrides self.bad
2315
          lu_result = 1
2316
          continue
2317
        for script, hkr, output in res.payload:
2318
          test = hkr == constants.HKR_FAIL
2319
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2320
                        "Script %s failed, output:", script)
2321
          if test:
2322
            output = indent_re.sub('      ', output)
2323
            feedback_fn("%s" % output)
2324
            lu_result = 0
2325

    
2326
      return lu_result
2327

    
2328

    
2329
class LUVerifyDisks(NoHooksLU):
2330
  """Verifies the cluster disks status.
2331

2332
  """
2333
  REQ_BGL = False
2334

    
2335
  def ExpandNames(self):
2336
    self.needed_locks = {
2337
      locking.LEVEL_NODE: locking.ALL_SET,
2338
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2339
    }
2340
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2341

    
2342
  def Exec(self, feedback_fn):
2343
    """Verify integrity of cluster disks.
2344

2345
    @rtype: tuple of three items
2346
    @return: a tuple of (dict of node-to-node_error, list of instances
2347
        which need activate-disks, dict of instance: (node, volume) for
2348
        missing volumes
2349

2350
    """
2351
    result = res_nodes, res_instances, res_missing = {}, [], {}
2352

    
2353
    vg_name = self.cfg.GetVGName()
2354
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2355
    instances = [self.cfg.GetInstanceInfo(name)
2356
                 for name in self.cfg.GetInstanceList()]
2357

    
2358
    nv_dict = {}
2359
    for inst in instances:
2360
      inst_lvs = {}
2361
      if (not inst.admin_up or
2362
          inst.disk_template not in constants.DTS_NET_MIRROR):
2363
        continue
2364
      inst.MapLVsByNode(inst_lvs)
2365
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2366
      for node, vol_list in inst_lvs.iteritems():
2367
        for vol in vol_list:
2368
          nv_dict[(node, vol)] = inst
2369

    
2370
    if not nv_dict:
2371
      return result
2372

    
2373
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2374

    
2375
    for node in nodes:
2376
      # node_volume
2377
      node_res = node_lvs[node]
2378
      if node_res.offline:
2379
        continue
2380
      msg = node_res.fail_msg
2381
      if msg:
2382
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2383
        res_nodes[node] = msg
2384
        continue
2385

    
2386
      lvs = node_res.payload
2387
      for lv_name, (_, _, lv_online) in lvs.items():
2388
        inst = nv_dict.pop((node, lv_name), None)
2389
        if (not lv_online and inst is not None
2390
            and inst.name not in res_instances):
2391
          res_instances.append(inst.name)
2392

    
2393
    # any leftover items in nv_dict are missing LVs, let's arrange the
2394
    # data better
2395
    for key, inst in nv_dict.iteritems():
2396
      if inst.name not in res_missing:
2397
        res_missing[inst.name] = []
2398
      res_missing[inst.name].append(key)
2399

    
2400
    return result
2401

    
2402

    
2403
class LURepairDiskSizes(NoHooksLU):
2404
  """Verifies the cluster disks sizes.
2405

2406
  """
2407
  _OP_PARAMS = [("instances", _EmptyList, _TListOf(_TNonEmptyString))]
2408
  REQ_BGL = False
2409

    
2410
  def ExpandNames(self):
2411
    if self.op.instances:
2412
      self.wanted_names = []
2413
      for name in self.op.instances:
2414
        full_name = _ExpandInstanceName(self.cfg, name)
2415
        self.wanted_names.append(full_name)
2416
      self.needed_locks = {
2417
        locking.LEVEL_NODE: [],
2418
        locking.LEVEL_INSTANCE: self.wanted_names,
2419
        }
2420
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2421
    else:
2422
      self.wanted_names = None
2423
      self.needed_locks = {
2424
        locking.LEVEL_NODE: locking.ALL_SET,
2425
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2426
        }
2427
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2428

    
2429
  def DeclareLocks(self, level):
2430
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2431
      self._LockInstancesNodes(primary_only=True)
2432

    
2433
  def CheckPrereq(self):
2434
    """Check prerequisites.
2435

2436
    This only checks the optional instance list against the existing names.
2437

2438
    """
2439
    if self.wanted_names is None:
2440
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2441

    
2442
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2443
                             in self.wanted_names]
2444

    
2445
  def _EnsureChildSizes(self, disk):
2446
    """Ensure children of the disk have the needed disk size.
2447

2448
    This is valid mainly for DRBD8 and fixes an issue where the
2449
    children have smaller disk size.
2450

2451
    @param disk: an L{ganeti.objects.Disk} object
2452

2453
    """
2454
    if disk.dev_type == constants.LD_DRBD8:
2455
      assert disk.children, "Empty children for DRBD8?"
2456
      fchild = disk.children[0]
2457
      mismatch = fchild.size < disk.size
2458
      if mismatch:
2459
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2460
                     fchild.size, disk.size)
2461
        fchild.size = disk.size
2462

    
2463
      # and we recurse on this child only, not on the metadev
2464
      return self._EnsureChildSizes(fchild) or mismatch
2465
    else:
2466
      return False
2467

    
2468
  def Exec(self, feedback_fn):
2469
    """Verify the size of cluster disks.
2470

2471
    """
2472
    # TODO: check child disks too
2473
    # TODO: check differences in size between primary/secondary nodes
2474
    per_node_disks = {}
2475
    for instance in self.wanted_instances:
2476
      pnode = instance.primary_node
2477
      if pnode not in per_node_disks:
2478
        per_node_disks[pnode] = []
2479
      for idx, disk in enumerate(instance.disks):
2480
        per_node_disks[pnode].append((instance, idx, disk))
2481

    
2482
    changed = []
2483
    for node, dskl in per_node_disks.items():
2484
      newl = [v[2].Copy() for v in dskl]
2485
      for dsk in newl:
2486
        self.cfg.SetDiskID(dsk, node)
2487
      result = self.rpc.call_blockdev_getsizes(node, newl)
2488
      if result.fail_msg:
2489
        self.LogWarning("Failure in blockdev_getsizes call to node"
2490
                        " %s, ignoring", node)
2491
        continue
2492
      if len(result.data) != len(dskl):
2493
        self.LogWarning("Invalid result from node %s, ignoring node results",
2494
                        node)
2495
        continue
2496
      for ((instance, idx, disk), size) in zip(dskl, result.data):
2497
        if size is None:
2498
          self.LogWarning("Disk %d of instance %s did not return size"
2499
                          " information, ignoring", idx, instance.name)
2500
          continue
2501
        if not isinstance(size, (int, long)):
2502
          self.LogWarning("Disk %d of instance %s did not return valid"
2503
                          " size information, ignoring", idx, instance.name)
2504
          continue
2505
        size = size >> 20
2506
        if size != disk.size:
2507
          self.LogInfo("Disk %d of instance %s has mismatched size,"
2508
                       " correcting: recorded %d, actual %d", idx,
2509
                       instance.name, disk.size, size)
2510
          disk.size = size
2511
          self.cfg.Update(instance, feedback_fn)
2512
          changed.append((instance.name, idx, size))
2513
        if self._EnsureChildSizes(disk):
2514
          self.cfg.Update(instance, feedback_fn)
2515
          changed.append((instance.name, idx, disk.size))
2516
    return changed
2517

    
2518

    
2519
class LURenameCluster(LogicalUnit):
2520
  """Rename the cluster.
2521

2522
  """
2523
  HPATH = "cluster-rename"
2524
  HTYPE = constants.HTYPE_CLUSTER
2525
  _OP_PARAMS = [("name", _NoDefault, _TNonEmptyString)]
2526

    
2527
  def BuildHooksEnv(self):
2528
    """Build hooks env.
2529

2530
    """
2531
    env = {
2532
      "OP_TARGET": self.cfg.GetClusterName(),
2533
      "NEW_NAME": self.op.name,
2534
      }
2535
    mn = self.cfg.GetMasterNode()
2536
    all_nodes = self.cfg.GetNodeList()
2537
    return env, [mn], all_nodes
2538

    
2539
  def CheckPrereq(self):
2540
    """Verify that the passed name is a valid one.
2541

2542
    """
2543
    hostname = netutils.GetHostInfo(self.op.name)
2544

    
2545
    new_name = hostname.name
2546
    self.ip = new_ip = hostname.ip
2547
    old_name = self.cfg.GetClusterName()
2548
    old_ip = self.cfg.GetMasterIP()
2549
    if new_name == old_name and new_ip == old_ip:
2550
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2551
                                 " cluster has changed",
2552
                                 errors.ECODE_INVAL)
2553
    if new_ip != old_ip:
2554
      if netutils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2555
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2556
                                   " reachable on the network. Aborting." %
2557
                                   new_ip, errors.ECODE_NOTUNIQUE)
2558

    
2559
    self.op.name = new_name
2560

    
2561
  def Exec(self, feedback_fn):
2562
    """Rename the cluster.
2563

2564
    """
2565
    clustername = self.op.name
2566
    ip = self.ip
2567

    
2568
    # shutdown the master IP
2569
    master = self.cfg.GetMasterNode()
2570
    result = self.rpc.call_node_stop_master(master, False)
2571
    result.Raise("Could not disable the master role")
2572

    
2573
    try:
2574
      cluster = self.cfg.GetClusterInfo()
2575
      cluster.cluster_name = clustername
2576
      cluster.master_ip = ip
2577
      self.cfg.Update(cluster, feedback_fn)
2578

    
2579
      # update the known hosts file
2580
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2581
      node_list = self.cfg.GetNodeList()
2582
      try:
2583
        node_list.remove(master)
2584
      except ValueError:
2585
        pass
2586
      result = self.rpc.call_upload_file(node_list,
2587
                                         constants.SSH_KNOWN_HOSTS_FILE)
2588
      for to_node, to_result in result.iteritems():
2589
        msg = to_result.fail_msg
2590
        if msg:
2591
          msg = ("Copy of file %s to node %s failed: %s" %
2592
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2593
          self.proc.LogWarning(msg)
2594

    
2595
    finally:
2596
      result = self.rpc.call_node_start_master(master, False, False)
2597
      msg = result.fail_msg
2598
      if msg:
2599
        self.LogWarning("Could not re-enable the master role on"
2600
                        " the master, please restart manually: %s", msg)
2601

    
2602
    return clustername
2603

    
2604

    
2605
class LUSetClusterParams(LogicalUnit):
2606
  """Change the parameters of the cluster.
2607

2608
  """
2609
  HPATH = "cluster-modify"
2610
  HTYPE = constants.HTYPE_CLUSTER
2611
  _OP_PARAMS = [
2612
    ("vg_name", None, _TMaybeString),
2613
    ("enabled_hypervisors", None,
2614
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2615
    ("hvparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2616
    ("beparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2617
    ("os_hvp", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2618
    ("osparams", None, _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2619
    ("candidate_pool_size", None, _TOr(_TStrictPositiveInt, _TNone)),
2620
    ("uid_pool", None, _NoType),
2621
    ("add_uids", None, _NoType),
2622
    ("remove_uids", None, _NoType),
2623
    ("maintain_node_health", None, _TMaybeBool),
2624
    ("nicparams", None, _TOr(_TDict, _TNone)),
2625
    ("drbd_helper", None, _TOr(_TString, _TNone)),
2626
    ("default_iallocator", None, _TMaybeString),
2627
    ("reserved_lvs", None, _TOr(_TListOf(_TNonEmptyString), _TNone)),
2628
    ]
2629
  REQ_BGL = False
2630

    
2631
  def CheckArguments(self):
2632
    """Check parameters
2633

2634
    """
2635
    if self.op.uid_pool:
2636
      uidpool.CheckUidPool(self.op.uid_pool)
2637

    
2638
    if self.op.add_uids:
2639
      uidpool.CheckUidPool(self.op.add_uids)
2640

    
2641
    if self.op.remove_uids:
2642
      uidpool.CheckUidPool(self.op.remove_uids)
2643

    
2644
  def ExpandNames(self):
2645
    # FIXME: in the future maybe other cluster params won't require checking on
2646
    # all nodes to be modified.
2647
    self.needed_locks = {
2648
      locking.LEVEL_NODE: locking.ALL_SET,
2649
    }
2650
    self.share_locks[locking.LEVEL_NODE] = 1
2651

    
2652
  def BuildHooksEnv(self):
2653
    """Build hooks env.
2654

2655
    """
2656
    env = {
2657
      "OP_TARGET": self.cfg.GetClusterName(),
2658
      "NEW_VG_NAME": self.op.vg_name,
2659
      }
2660
    mn = self.cfg.GetMasterNode()
2661
    return env, [mn], [mn]
2662

    
2663
  def CheckPrereq(self):
2664
    """Check prerequisites.
2665

2666
    This checks whether the given params don't conflict and
2667
    if the given volume group is valid.
2668

2669
    """
2670
    if self.op.vg_name is not None and not self.op.vg_name:
2671
      if self.cfg.HasAnyDiskOfType(constants.LD_LV):
2672
        raise errors.OpPrereqError("Cannot disable lvm storage while lvm-based"
2673
                                   " instances exist", errors.ECODE_INVAL)
2674

    
2675
    if self.op.drbd_helper is not None and not self.op.drbd_helper:
2676
      if self.cfg.HasAnyDiskOfType(constants.LD_DRBD8):
2677
        raise errors.OpPrereqError("Cannot disable drbd helper while"
2678
                                   " drbd-based instances exist",
2679
                                   errors.ECODE_INVAL)
2680

    
2681
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2682

    
2683
    # if vg_name not None, checks given volume group on all nodes
2684
    if self.op.vg_name:
2685
      vglist = self.rpc.call_vg_list(node_list)
2686
      for node in node_list:
2687
        msg = vglist[node].fail_msg
2688
        if msg:
2689
          # ignoring down node
2690
          self.LogWarning("Error while gathering data on node %s"
2691
                          " (ignoring node): %s", node, msg)
2692
          continue
2693
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2694
                                              self.op.vg_name,
2695
                                              constants.MIN_VG_SIZE)
2696
        if vgstatus:
2697
          raise errors.OpPrereqError("Error on node '%s': %s" %
2698
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2699

    
2700
    if self.op.drbd_helper:
2701
      # checks given drbd helper on all nodes
2702
      helpers = self.rpc.call_drbd_helper(node_list)
2703
      for node in node_list:
2704
        ninfo = self.cfg.GetNodeInfo(node)
2705
        if ninfo.offline:
2706
          self.LogInfo("Not checking drbd helper on offline node %s", node)
2707
          continue
2708
        msg = helpers[node].fail_msg
2709
        if msg:
2710
          raise errors.OpPrereqError("Error checking drbd helper on node"
2711
                                     " '%s': %s" % (node, msg),
2712
                                     errors.ECODE_ENVIRON)
2713
        node_helper = helpers[node].payload
2714
        if node_helper != self.op.drbd_helper:
2715
          raise errors.OpPrereqError("Error on node '%s': drbd helper is %s" %
2716
                                     (node, node_helper), errors.ECODE_ENVIRON)
2717

    
2718
    self.cluster = cluster = self.cfg.GetClusterInfo()
2719
    # validate params changes
2720
    if self.op.beparams:
2721
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
2722
      self.new_beparams = cluster.SimpleFillBE(self.op.beparams)
2723

    
2724
    if self.op.nicparams:
2725
      utils.ForceDictType(self.op.nicparams, constants.NICS_PARAMETER_TYPES)
2726
      self.new_nicparams = cluster.SimpleFillNIC(self.op.nicparams)
2727
      objects.NIC.CheckParameterSyntax(self.new_nicparams)
2728
      nic_errors = []
2729

    
2730
      # check all instances for consistency
2731
      for instance in self.cfg.GetAllInstancesInfo().values():
2732
        for nic_idx, nic in enumerate(instance.nics):
2733
          params_copy = copy.deepcopy(nic.nicparams)
2734
          params_filled = objects.FillDict(self.new_nicparams, params_copy)
2735

    
2736
          # check parameter syntax
2737
          try:
2738
            objects.NIC.CheckParameterSyntax(params_filled)
2739
          except errors.ConfigurationError, err:
2740
            nic_errors.append("Instance %s, nic/%d: %s" %
2741
                              (instance.name, nic_idx, err))
2742

    
2743
          # if we're moving instances to routed, check that they have an ip
2744
          target_mode = params_filled[constants.NIC_MODE]
2745
          if target_mode == constants.NIC_MODE_ROUTED and not nic.ip:
2746
            nic_errors.append("Instance %s, nic/%d: routed nick with no ip" %
2747
                              (instance.name, nic_idx))
2748
      if nic_errors:
2749
        raise errors.OpPrereqError("Cannot apply the change, errors:\n%s" %
2750
                                   "\n".join(nic_errors))
2751

    
2752
    # hypervisor list/parameters
2753
    self.new_hvparams = new_hvp = objects.FillDict(cluster.hvparams, {})
2754
    if self.op.hvparams:
2755
      for hv_name, hv_dict in self.op.hvparams.items():
2756
        if hv_name not in self.new_hvparams:
2757
          self.new_hvparams[hv_name] = hv_dict
2758
        else:
2759
          self.new_hvparams[hv_name].update(hv_dict)
2760

    
2761
    # os hypervisor parameters
2762
    self.new_os_hvp = objects.FillDict(cluster.os_hvp, {})
2763
    if self.op.os_hvp:
2764
      for os_name, hvs in self.op.os_hvp.items():
2765
        if os_name not in self.new_os_hvp:
2766
          self.new_os_hvp[os_name] = hvs
2767
        else:
2768
          for hv_name, hv_dict in hvs.items():
2769
            if hv_name not in self.new_os_hvp[os_name]:
2770
              self.new_os_hvp[os_name][hv_name] = hv_dict
2771
            else:
2772
              self.new_os_hvp[os_name][hv_name].update(hv_dict)
2773

    
2774
    # os parameters
2775
    self.new_osp = objects.FillDict(cluster.osparams, {})
2776
    if self.op.osparams:
2777
      for os_name, osp in self.op.osparams.items():
2778
        if os_name not in self.new_osp:
2779
          self.new_osp[os_name] = {}
2780

    
2781
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2782
                                                  use_none=True)
2783

    
2784
        if not self.new_osp[os_name]:
2785
          # we removed all parameters
2786
          del self.new_osp[os_name]
2787
        else:
2788
          # check the parameter validity (remote check)
2789
          _CheckOSParams(self, False, [self.cfg.GetMasterNode()],
2790
                         os_name, self.new_osp[os_name])
2791

    
2792
    # changes to the hypervisor list
2793
    if self.op.enabled_hypervisors is not None:
2794
      self.hv_list = self.op.enabled_hypervisors
2795
      for hv in self.hv_list:
2796
        # if the hypervisor doesn't already exist in the cluster
2797
        # hvparams, we initialize it to empty, and then (in both
2798
        # cases) we make sure to fill the defaults, as we might not
2799
        # have a complete defaults list if the hypervisor wasn't
2800
        # enabled before
2801
        if hv not in new_hvp:
2802
          new_hvp[hv] = {}
2803
        new_hvp[hv] = objects.FillDict(constants.HVC_DEFAULTS[hv], new_hvp[hv])
2804
        utils.ForceDictType(new_hvp[hv], constants.HVS_PARAMETER_TYPES)
2805
    else:
2806
      self.hv_list = cluster.enabled_hypervisors
2807

    
2808
    if self.op.hvparams or self.op.enabled_hypervisors is not None:
2809
      # either the enabled list has changed, or the parameters have, validate
2810
      for hv_name, hv_params in self.new_hvparams.items():
2811
        if ((self.op.hvparams and hv_name in self.op.hvparams) or
2812
            (self.op.enabled_hypervisors and
2813
             hv_name in self.op.enabled_hypervisors)):
2814
          # either this is a new hypervisor, or its parameters have changed
2815
          hv_class = hypervisor.GetHypervisor(hv_name)
2816
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2817
          hv_class.CheckParameterSyntax(hv_params)
2818
          _CheckHVParams(self, node_list, hv_name, hv_params)
2819

    
2820
    if self.op.os_hvp:
2821
      # no need to check any newly-enabled hypervisors, since the
2822
      # defaults have already been checked in the above code-block
2823
      for os_name, os_hvp in self.new_os_hvp.items():
2824
        for hv_name, hv_params in os_hvp.items():
2825
          utils.ForceDictType(hv_params, constants.HVS_PARAMETER_TYPES)
2826
          # we need to fill in the new os_hvp on top of the actual hv_p
2827
          cluster_defaults = self.new_hvparams.get(hv_name, {})
2828
          new_osp = objects.FillDict(cluster_defaults, hv_params)
2829
          hv_class = hypervisor.GetHypervisor(hv_name)
2830
          hv_class.CheckParameterSyntax(new_osp)
2831
          _CheckHVParams(self, node_list, hv_name, new_osp)
2832

    
2833
    if self.op.default_iallocator:
2834
      alloc_script = utils.FindFile(self.op.default_iallocator,
2835
                                    constants.IALLOCATOR_SEARCH_PATH,
2836
                                    os.path.isfile)
2837
      if alloc_script is None:
2838
        raise errors.OpPrereqError("Invalid default iallocator script '%s'"
2839
                                   " specified" % self.op.default_iallocator,
2840
                                   errors.ECODE_INVAL)
2841

    
2842
  def Exec(self, feedback_fn):
2843
    """Change the parameters of the cluster.
2844

2845
    """
2846
    if self.op.vg_name is not None:
2847
      new_volume = self.op.vg_name
2848
      if not new_volume:
2849
        new_volume = None
2850
      if new_volume != self.cfg.GetVGName():
2851
        self.cfg.SetVGName(new_volume)
2852
      else:
2853
        feedback_fn("Cluster LVM configuration already in desired"
2854
                    " state, not changing")
2855
    if self.op.drbd_helper is not None:
2856
      new_helper = self.op.drbd_helper
2857
      if not new_helper:
2858
        new_helper = None
2859
      if new_helper != self.cfg.GetDRBDHelper():
2860
        self.cfg.SetDRBDHelper(new_helper)
2861
      else:
2862
        feedback_fn("Cluster DRBD helper already in desired state,"
2863
                    " not changing")
2864
    if self.op.hvparams:
2865
      self.cluster.hvparams = self.new_hvparams
2866
    if self.op.os_hvp:
2867
      self.cluster.os_hvp = self.new_os_hvp
2868
    if self.op.enabled_hypervisors is not None:
2869
      self.cluster.hvparams = self.new_hvparams
2870
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2871
    if self.op.beparams:
2872
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2873
    if self.op.nicparams:
2874
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2875
    if self.op.osparams:
2876
      self.cluster.osparams = self.new_osp
2877

    
2878
    if self.op.candidate_pool_size is not None:
2879
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2880
      # we need to update the pool size here, otherwise the save will fail
2881
      _AdjustCandidatePool(self, [])
2882

    
2883
    if self.op.maintain_node_health is not None:
2884
      self.cluster.maintain_node_health = self.op.maintain_node_health
2885

    
2886
    if self.op.add_uids is not None:
2887
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2888

    
2889
    if self.op.remove_uids is not None:
2890
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2891

    
2892
    if self.op.uid_pool is not None:
2893
      self.cluster.uid_pool = self.op.uid_pool
2894

    
2895
    if self.op.default_iallocator is not None:
2896
      self.cluster.default_iallocator = self.op.default_iallocator
2897

    
2898
    if self.op.reserved_lvs is not None:
2899
      self.cluster.reserved_lvs = self.op.reserved_lvs
2900

    
2901
    self.cfg.Update(self.cluster, feedback_fn)
2902

    
2903

    
2904
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2905
  """Distribute additional files which are part of the cluster configuration.
2906

2907
  ConfigWriter takes care of distributing the config and ssconf files, but
2908
  there are more files which should be distributed to all nodes. This function
2909
  makes sure those are copied.
2910

2911
  @param lu: calling logical unit
2912
  @param additional_nodes: list of nodes not in the config to distribute to
2913

2914
  """
2915
  # 1. Gather target nodes
2916
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2917
  dist_nodes = lu.cfg.GetOnlineNodeList()
2918
  if additional_nodes is not None:
2919
    dist_nodes.extend(additional_nodes)
2920
  if myself.name in dist_nodes:
2921
    dist_nodes.remove(myself.name)
2922

    
2923
  # 2. Gather files to distribute
2924
  dist_files = set([constants.ETC_HOSTS,
2925
                    constants.SSH_KNOWN_HOSTS_FILE,
2926
                    constants.RAPI_CERT_FILE,
2927
                    constants.RAPI_USERS_FILE,
2928
                    constants.CONFD_HMAC_KEY,
2929
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2930
                   ])
2931

    
2932
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2933
  for hv_name in enabled_hypervisors:
2934
    hv_class = hypervisor.GetHypervisor(hv_name)
2935
    dist_files.update(hv_class.GetAncillaryFiles())
2936

    
2937
  # 3. Perform the files upload
2938
  for fname in dist_files:
2939
    if os.path.exists(fname):
2940
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2941
      for to_node, to_result in result.items():
2942
        msg = to_result.fail_msg
2943
        if msg:
2944
          msg = ("Copy of file %s to node %s failed: %s" %
2945
                 (fname, to_node, msg))
2946
          lu.proc.LogWarning(msg)
2947

    
2948

    
2949
class LURedistributeConfig(NoHooksLU):
2950
  """Force the redistribution of cluster configuration.
2951

2952
  This is a very simple LU.
2953

2954
  """
2955
  REQ_BGL = False
2956

    
2957
  def ExpandNames(self):
2958
    self.needed_locks = {
2959
      locking.LEVEL_NODE: locking.ALL_SET,
2960
    }
2961
    self.share_locks[locking.LEVEL_NODE] = 1
2962

    
2963
  def Exec(self, feedback_fn):
2964
    """Redistribute the configuration.
2965

2966
    """
2967
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2968
    _RedistributeAncillaryFiles(self)
2969

    
2970

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

2974
  """
2975
  if not instance.disks or disks is not None and not disks:
2976
    return True
2977

    
2978
  disks = _ExpandCheckDisks(instance, disks)
2979

    
2980
  if not oneshot:
2981
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2982

    
2983
  node = instance.primary_node
2984

    
2985
  for dev in disks:
2986
    lu.cfg.SetDiskID(dev, node)
2987

    
2988
  # TODO: Convert to utils.Retry
2989

    
2990
  retries = 0
2991
  degr_retries = 10 # in seconds, as we sleep 1 second each time
2992
  while True:
2993
    max_time = 0
2994
    done = True
2995
    cumul_degraded = False
2996
    rstats = lu.rpc.call_blockdev_getmirrorstatus(node, disks)
2997
    msg = rstats.fail_msg
2998
    if msg:
2999
      lu.LogWarning("Can't get any data from node %s: %s", node, msg)
3000
      retries += 1
3001
      if retries >= 10:
3002
        raise errors.RemoteError("Can't contact node %s for mirror data,"
3003
                                 " aborting." % node)
3004
      time.sleep(6)
3005
      continue
3006
    rstats = rstats.payload
3007
    retries = 0
3008
    for i, mstat in enumerate(rstats):
3009
      if mstat is None:
3010
        lu.LogWarning("Can't compute data for node %s/%s",
3011
                           node, disks[i].iv_name)
3012
        continue
3013

    
3014
      cumul_degraded = (cumul_degraded or
3015
                        (mstat.is_degraded and mstat.sync_percent is None))
3016
      if mstat.sync_percent is not None:
3017
        done = False
3018
        if mstat.estimated_time is not None:
3019
          rem_time = ("%s remaining (estimated)" %
3020
                      utils.FormatSeconds(mstat.estimated_time))
3021
          max_time = mstat.estimated_time
3022
        else:
3023
          rem_time = "no time estimate"
3024
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
3025
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
3026

    
3027
    # if we're done but degraded, let's do a few small retries, to
3028
    # make sure we see a stable and not transient situation; therefore
3029
    # we force restart of the loop
3030
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
3031
      logging.info("Degraded disks found, %d retries left", degr_retries)
3032
      degr_retries -= 1
3033
      time.sleep(1)
3034
      continue
3035

    
3036
    if done or oneshot:
3037
      break
3038

    
3039
    time.sleep(min(60, max_time))
3040

    
3041
  if done:
3042
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
3043
  return not cumul_degraded
3044

    
3045

    
3046
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
3047
  """Check that mirrors are not degraded.
3048

3049
  The ldisk parameter, if True, will change the test from the
3050
  is_degraded attribute (which represents overall non-ok status for
3051
  the device(s)) to the ldisk (representing the local storage status).
3052

3053
  """
3054
  lu.cfg.SetDiskID(dev, node)
3055

    
3056
  result = True
3057

    
3058
  if on_primary or dev.AssembleOnSecondary():
3059
    rstats = lu.rpc.call_blockdev_find(node, dev)
3060
    msg = rstats.fail_msg
3061
    if msg:
3062
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
3063
      result = False
3064
    elif not rstats.payload:
3065
      lu.LogWarning("Can't find disk on node %s", node)
3066
      result = False
3067
    else:
3068
      if ldisk:
3069
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
3070
      else:
3071
        result = result and not rstats.payload.is_degraded
3072

    
3073
  if dev.children:
3074
    for child in dev.children:
3075
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
3076

    
3077
  return result
3078

    
3079

    
3080
class LUDiagnoseOS(NoHooksLU):
3081
  """Logical unit for OS diagnose/query.
3082

3083
  """
3084
  _OP_PARAMS = [
3085
    _POutputFields,
3086
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3087
    ]
3088
  REQ_BGL = False
3089
  _HID = "hidden"
3090
  _BLK = "blacklisted"
3091
  _FIELDS_STATIC = utils.FieldSet()
3092
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3093
                                   "parameters", "api_versions", _HID, _BLK)
3094

    
3095
  def CheckArguments(self):
3096
    if self.op.names:
3097
      raise errors.OpPrereqError("Selective OS query not supported",
3098
                                 errors.ECODE_INVAL)
3099

    
3100
    _CheckOutputFields(static=self._FIELDS_STATIC,
3101
                       dynamic=self._FIELDS_DYNAMIC,
3102
                       selected=self.op.output_fields)
3103

    
3104
  def ExpandNames(self):
3105
    # Lock all nodes, in shared mode
3106
    # Temporary removal of locks, should be reverted later
3107
    # TODO: reintroduce locks when they are lighter-weight
3108
    self.needed_locks = {}
3109
    #self.share_locks[locking.LEVEL_NODE] = 1
3110
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3111

    
3112
  @staticmethod
3113
  def _DiagnoseByOS(rlist):
3114
    """Remaps a per-node return list into an a per-os per-node dictionary
3115

3116
    @param rlist: a map with node names as keys and OS objects as values
3117

3118
    @rtype: dict
3119
    @return: a dictionary with osnames as keys and as value another
3120
        map, with nodes as keys and tuples of (path, status, diagnose,
3121
        variants, parameters, api_versions) as values, eg::
3122

3123
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3124
                                     (/srv/..., False, "invalid api")],
3125
                           "node2": [(/srv/..., True, "", [], [])]}
3126
          }
3127

3128
    """
3129
    all_os = {}
3130
    # we build here the list of nodes that didn't fail the RPC (at RPC
3131
    # level), so that nodes with a non-responding node daemon don't
3132
    # make all OSes invalid
3133
    good_nodes = [node_name for node_name in rlist
3134
                  if not rlist[node_name].fail_msg]
3135
    for node_name, nr in rlist.items():
3136
      if nr.fail_msg or not nr.payload:
3137
        continue
3138
      for (name, path, status, diagnose, variants,
3139
           params, api_versions) in nr.payload:
3140
        if name not in all_os:
3141
          # build a list of nodes for this os containing empty lists
3142
          # for each node in node_list
3143
          all_os[name] = {}
3144
          for nname in good_nodes:
3145
            all_os[name][nname] = []
3146
        # convert params from [name, help] to (name, help)
3147
        params = [tuple(v) for v in params]
3148
        all_os[name][node_name].append((path, status, diagnose,
3149
                                        variants, params, api_versions))
3150
    return all_os
3151

    
3152
  def Exec(self, feedback_fn):
3153
    """Compute the list of OSes.
3154

3155
    """
3156
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3157
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3158
    pol = self._DiagnoseByOS(node_data)
3159
    output = []
3160
    cluster = self.cfg.GetClusterInfo()
3161

    
3162
    for os_name, os_data in pol.items():
3163
      row = []
3164
      valid = True
3165
      (variants, params, api_versions) = null_state = (set(), set(), set())
3166
      for idx, osl in enumerate(os_data.values()):
3167
        valid = bool(valid and osl and osl[0][1])
3168
        if not valid:
3169
          (variants, params, api_versions) = null_state
3170
          break
3171
        node_variants, node_params, node_api = osl[0][3:6]
3172
        if idx == 0: # first entry
3173
          variants = set(node_variants)
3174
          params = set(node_params)
3175
          api_versions = set(node_api)
3176
        else: # keep consistency
3177
          variants.intersection_update(node_variants)
3178
          params.intersection_update(node_params)
3179
          api_versions.intersection_update(node_api)
3180

    
3181
      is_hid = os_name in cluster.hidden_oss
3182
      is_blk = os_name in cluster.blacklisted_oss
3183
      if ((self._HID not in self.op.output_fields and is_hid) or
3184
          (self._BLK not in self.op.output_fields and is_blk)):
3185
        continue
3186

    
3187
      for field in self.op.output_fields:
3188
        if field == "name":
3189
          val = os_name
3190
        elif field == "valid":
3191
          val = valid
3192
        elif field == "node_status":
3193
          # this is just a copy of the dict
3194
          val = {}
3195
          for node_name, nos_list in os_data.items():
3196
            val[node_name] = nos_list
3197
        elif field == "variants":
3198
          val = list(variants)
3199
        elif field == "parameters":
3200
          val = list(params)
3201
        elif field == "api_versions":
3202
          val = list(api_versions)
3203
        elif field == self._HID:
3204
          val = is_hid
3205
        elif field == self._BLK:
3206
          val = is_blk
3207
        else:
3208
          raise errors.ParameterError(field)
3209
        row.append(val)
3210
      output.append(row)
3211

    
3212
    return output
3213

    
3214

    
3215
class LURemoveNode(LogicalUnit):
3216
  """Logical unit for removing a node.
3217

3218
  """
3219
  HPATH = "node-remove"
3220
  HTYPE = constants.HTYPE_NODE
3221
  _OP_PARAMS = [
3222
    _PNodeName,
3223
    ]
3224

    
3225
  def BuildHooksEnv(self):
3226
    """Build hooks env.
3227

3228
    This doesn't run on the target node in the pre phase as a failed
3229
    node would then be impossible to remove.
3230

3231
    """
3232
    env = {
3233
      "OP_TARGET": self.op.node_name,
3234
      "NODE_NAME": self.op.node_name,
3235
      }
3236
    all_nodes = self.cfg.GetNodeList()
3237
    try:
3238
      all_nodes.remove(self.op.node_name)
3239
    except ValueError:
3240
      logging.warning("Node %s which is about to be removed not found"
3241
                      " in the all nodes list", self.op.node_name)
3242
    return env, all_nodes, all_nodes
3243

    
3244
  def CheckPrereq(self):
3245
    """Check prerequisites.
3246

3247
    This checks:
3248
     - the node exists in the configuration
3249
     - it does not have primary or secondary instances
3250
     - it's not the master
3251

3252
    Any errors are signaled by raising errors.OpPrereqError.
3253

3254
    """
3255
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3256
    node = self.cfg.GetNodeInfo(self.op.node_name)
3257
    assert node is not None
3258

    
3259
    instance_list = self.cfg.GetInstanceList()
3260

    
3261
    masternode = self.cfg.GetMasterNode()
3262
    if node.name == masternode:
3263
      raise errors.OpPrereqError("Node is the master node,"
3264
                                 " you need to failover first.",
3265
                                 errors.ECODE_INVAL)
3266

    
3267
    for instance_name in instance_list:
3268
      instance = self.cfg.GetInstanceInfo(instance_name)
3269
      if node.name in instance.all_nodes:
3270
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3271
                                   " please remove first." % instance_name,
3272
                                   errors.ECODE_INVAL)
3273
    self.op.node_name = node.name
3274
    self.node = node
3275

    
3276
  def Exec(self, feedback_fn):
3277
    """Removes the node from the cluster.
3278

3279
    """
3280
    node = self.node
3281
    logging.info("Stopping the node daemon and removing configs from node %s",
3282
                 node.name)
3283

    
3284
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3285

    
3286
    # Promote nodes to master candidate as needed
3287
    _AdjustCandidatePool(self, exceptions=[node.name])
3288
    self.context.RemoveNode(node.name)
3289

    
3290
    # Run post hooks on the node before it's removed
3291
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3292
    try:
3293
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3294
    except:
3295
      # pylint: disable-msg=W0702
3296
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3297

    
3298
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3299
    msg = result.fail_msg
3300
    if msg:
3301
      self.LogWarning("Errors encountered on the remote node while leaving"
3302
                      " the cluster: %s", msg)
3303

    
3304
    # Remove node from our /etc/hosts
3305
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3306
      # FIXME: this should be done via an rpc call to node daemon
3307
      utils.RemoveHostFromEtcHosts(node.name)
3308
      _RedistributeAncillaryFiles(self)
3309

    
3310

    
3311
class LUQueryNodes(NoHooksLU):
3312
  """Logical unit for querying nodes.
3313

3314
  """
3315
  # pylint: disable-msg=W0142
3316
  _OP_PARAMS = [
3317
    _POutputFields,
3318
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
3319
    ("use_locking", False, _TBool),
3320
    ]
3321
  REQ_BGL = False
3322

    
3323
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3324
                    "master_candidate", "offline", "drained"]
3325

    
3326
  _FIELDS_DYNAMIC = utils.FieldSet(
3327
    "dtotal", "dfree",
3328
    "mtotal", "mnode", "mfree",
3329
    "bootid",
3330
    "ctotal", "cnodes", "csockets",
3331
    )
3332

    
3333
  _FIELDS_STATIC = utils.FieldSet(*[
3334
    "pinst_cnt", "sinst_cnt",
3335
    "pinst_list", "sinst_list",
3336
    "pip", "sip", "tags",
3337
    "master",
3338
    "role"] + _SIMPLE_FIELDS
3339
    )
3340

    
3341
  def CheckArguments(self):
3342
    _CheckOutputFields(static=self._FIELDS_STATIC,
3343
                       dynamic=self._FIELDS_DYNAMIC,
3344
                       selected=self.op.output_fields)
3345

    
3346
  def ExpandNames(self):
3347
    self.needed_locks = {}
3348
    self.share_locks[locking.LEVEL_NODE] = 1
3349

    
3350
    if self.op.names:
3351
      self.wanted = _GetWantedNodes(self, self.op.names)
3352
    else:
3353
      self.wanted = locking.ALL_SET
3354

    
3355
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3356
    self.do_locking = self.do_node_query and self.op.use_locking
3357
    if self.do_locking:
3358
      # if we don't request only static fields, we need to lock the nodes
3359
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3360

    
3361
  def Exec(self, feedback_fn):
3362
    """Computes the list of nodes and their attributes.
3363

3364
    """
3365
    all_info = self.cfg.GetAllNodesInfo()
3366
    if self.do_locking:
3367
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3368
    elif self.wanted != locking.ALL_SET:
3369
      nodenames = self.wanted
3370
      missing = set(nodenames).difference(all_info.keys())
3371
      if missing:
3372
        raise errors.OpExecError(
3373
          "Some nodes were removed before retrieving their data: %s" % missing)
3374
    else:
3375
      nodenames = all_info.keys()
3376

    
3377
    nodenames = utils.NiceSort(nodenames)
3378
    nodelist = [all_info[name] for name in nodenames]
3379

    
3380
    # begin data gathering
3381

    
3382
    if self.do_node_query:
3383
      live_data = {}
3384
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3385
                                          self.cfg.GetHypervisorType())
3386
      for name in nodenames:
3387
        nodeinfo = node_data[name]
3388
        if not nodeinfo.fail_msg and nodeinfo.payload:
3389
          nodeinfo = nodeinfo.payload
3390
          fn = utils.TryConvert
3391
          live_data[name] = {
3392
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3393
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3394
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3395
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3396
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3397
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3398
            "bootid": nodeinfo.get('bootid', None),
3399
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3400
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3401
            }
3402
        else:
3403
          live_data[name] = {}
3404
    else:
3405
      live_data = dict.fromkeys(nodenames, {})
3406

    
3407
    node_to_primary = dict([(name, set()) for name in nodenames])
3408
    node_to_secondary = dict([(name, set()) for name in nodenames])
3409

    
3410
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3411
                             "sinst_cnt", "sinst_list"))
3412
    if inst_fields & frozenset(self.op.output_fields):
3413
      inst_data = self.cfg.GetAllInstancesInfo()
3414

    
3415
      for inst in inst_data.values():
3416
        if inst.primary_node in node_to_primary:
3417
          node_to_primary[inst.primary_node].add(inst.name)
3418
        for secnode in inst.secondary_nodes:
3419
          if secnode in node_to_secondary:
3420
            node_to_secondary[secnode].add(inst.name)
3421

    
3422
    master_node = self.cfg.GetMasterNode()
3423

    
3424
    # end data gathering
3425

    
3426
    output = []
3427
    for node in nodelist:
3428
      node_output = []
3429
      for field in self.op.output_fields:
3430
        if field in self._SIMPLE_FIELDS:
3431
          val = getattr(node, field)
3432
        elif field == "pinst_list":
3433
          val = list(node_to_primary[node.name])
3434
        elif field == "sinst_list":
3435
          val = list(node_to_secondary[node.name])
3436
        elif field == "pinst_cnt":
3437
          val = len(node_to_primary[node.name])
3438
        elif field == "sinst_cnt":
3439
          val = len(node_to_secondary[node.name])
3440
        elif field == "pip":
3441
          val = node.primary_ip
3442
        elif field == "sip":
3443
          val = node.secondary_ip
3444
        elif field == "tags":
3445
          val = list(node.GetTags())
3446
        elif field == "master":
3447
          val = node.name == master_node
3448
        elif self._FIELDS_DYNAMIC.Matches(field):
3449
          val = live_data[node.name].get(field, None)
3450
        elif field == "role":
3451
          if node.name == master_node:
3452
            val = "M"
3453
          elif node.master_candidate:
3454
            val = "C"
3455
          elif node.drained:
3456
            val = "D"
3457
          elif node.offline:
3458
            val = "O"
3459
          else:
3460
            val = "R"
3461
        else:
3462
          raise errors.ParameterError(field)
3463
        node_output.append(val)
3464
      output.append(node_output)
3465

    
3466
    return output
3467

    
3468

    
3469
class LUQueryNodeVolumes(NoHooksLU):
3470
  """Logical unit for getting volumes on node(s).
3471

3472
  """
3473
  _OP_PARAMS = [
3474
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3475
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3476
    ]
3477
  REQ_BGL = False
3478
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3479
  _FIELDS_STATIC = utils.FieldSet("node")
3480

    
3481
  def CheckArguments(self):
3482
    _CheckOutputFields(static=self._FIELDS_STATIC,
3483
                       dynamic=self._FIELDS_DYNAMIC,
3484
                       selected=self.op.output_fields)
3485

    
3486
  def ExpandNames(self):
3487
    self.needed_locks = {}
3488
    self.share_locks[locking.LEVEL_NODE] = 1
3489
    if not self.op.nodes:
3490
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3491
    else:
3492
      self.needed_locks[locking.LEVEL_NODE] = \
3493
        _GetWantedNodes(self, self.op.nodes)
3494

    
3495
  def Exec(self, feedback_fn):
3496
    """Computes the list of nodes and their attributes.
3497

3498
    """
3499
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3500
    volumes = self.rpc.call_node_volumes(nodenames)
3501

    
3502
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3503
             in self.cfg.GetInstanceList()]
3504

    
3505
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3506

    
3507
    output = []
3508
    for node in nodenames:
3509
      nresult = volumes[node]
3510
      if nresult.offline:
3511
        continue
3512
      msg = nresult.fail_msg
3513
      if msg:
3514
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3515
        continue
3516

    
3517
      node_vols = nresult.payload[:]
3518
      node_vols.sort(key=lambda vol: vol['dev'])
3519

    
3520
      for vol in node_vols:
3521
        node_output = []
3522
        for field in self.op.output_fields:
3523
          if field == "node":
3524
            val = node
3525
          elif field == "phys":
3526
            val = vol['dev']
3527
          elif field == "vg":
3528
            val = vol['vg']
3529
          elif field == "name":
3530
            val = vol['name']
3531
          elif field == "size":
3532
            val = int(float(vol['size']))
3533
          elif field == "instance":
3534
            for inst in ilist:
3535
              if node not in lv_by_node[inst]:
3536
                continue
3537
              if vol['name'] in lv_by_node[inst][node]:
3538
                val = inst.name
3539
                break
3540
            else:
3541
              val = '-'
3542
          else:
3543
            raise errors.ParameterError(field)
3544
          node_output.append(str(val))
3545

    
3546
        output.append(node_output)
3547

    
3548
    return output
3549

    
3550

    
3551
class LUQueryNodeStorage(NoHooksLU):
3552
  """Logical unit for getting information on storage units on node(s).
3553

3554
  """
3555
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3556
  _OP_PARAMS = [
3557
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
3558
    ("storage_type", _NoDefault, _CheckStorageType),
3559
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
3560
    ("name", None, _TMaybeString),
3561
    ]
3562
  REQ_BGL = False
3563

    
3564
  def CheckArguments(self):
3565
    _CheckOutputFields(static=self._FIELDS_STATIC,
3566
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3567
                       selected=self.op.output_fields)
3568

    
3569
  def ExpandNames(self):
3570
    self.needed_locks = {}
3571
    self.share_locks[locking.LEVEL_NODE] = 1
3572

    
3573
    if self.op.nodes:
3574
      self.needed_locks[locking.LEVEL_NODE] = \
3575
        _GetWantedNodes(self, self.op.nodes)
3576
    else:
3577
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3578

    
3579
  def Exec(self, feedback_fn):
3580
    """Computes the list of nodes and their attributes.
3581

3582
    """
3583
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3584

    
3585
    # Always get name to sort by
3586
    if constants.SF_NAME in self.op.output_fields:
3587
      fields = self.op.output_fields[:]
3588
    else:
3589
      fields = [constants.SF_NAME] + self.op.output_fields
3590

    
3591
    # Never ask for node or type as it's only known to the LU
3592
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3593
      while extra in fields:
3594
        fields.remove(extra)
3595

    
3596
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3597
    name_idx = field_idx[constants.SF_NAME]
3598

    
3599
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3600
    data = self.rpc.call_storage_list(self.nodes,
3601
                                      self.op.storage_type, st_args,
3602
                                      self.op.name, fields)
3603

    
3604
    result = []
3605

    
3606
    for node in utils.NiceSort(self.nodes):
3607
      nresult = data[node]
3608
      if nresult.offline:
3609
        continue
3610

    
3611
      msg = nresult.fail_msg
3612
      if msg:
3613
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3614
        continue
3615

    
3616
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3617

    
3618
      for name in utils.NiceSort(rows.keys()):
3619
        row = rows[name]
3620

    
3621
        out = []
3622

    
3623
        for field in self.op.output_fields:
3624
          if field == constants.SF_NODE:
3625
            val = node
3626
          elif field == constants.SF_TYPE:
3627
            val = self.op.storage_type
3628
          elif field in field_idx:
3629
            val = row[field_idx[field]]
3630
          else:
3631
            raise errors.ParameterError(field)
3632

    
3633
          out.append(val)
3634

    
3635
        result.append(out)
3636

    
3637
    return result
3638

    
3639

    
3640
class LUModifyNodeStorage(NoHooksLU):
3641
  """Logical unit for modifying a storage volume on a node.
3642

3643
  """
3644
  _OP_PARAMS = [
3645
    _PNodeName,
3646
    ("storage_type", _NoDefault, _CheckStorageType),
3647
    ("name", _NoDefault, _TNonEmptyString),
3648
    ("changes", _NoDefault, _TDict),
3649
    ]
3650
  REQ_BGL = False
3651

    
3652
  def CheckArguments(self):
3653
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3654

    
3655
    storage_type = self.op.storage_type
3656

    
3657
    try:
3658
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3659
    except KeyError:
3660
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3661
                                 " modified" % storage_type,
3662
                                 errors.ECODE_INVAL)
3663

    
3664
    diff = set(self.op.changes.keys()) - modifiable
3665
    if diff:
3666
      raise errors.OpPrereqError("The following fields can not be modified for"
3667
                                 " storage units of type '%s': %r" %
3668
                                 (storage_type, list(diff)),
3669
                                 errors.ECODE_INVAL)
3670

    
3671
  def ExpandNames(self):
3672
    self.needed_locks = {
3673
      locking.LEVEL_NODE: self.op.node_name,
3674
      }
3675

    
3676
  def Exec(self, feedback_fn):
3677
    """Computes the list of nodes and their attributes.
3678

3679
    """
3680
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3681
    result = self.rpc.call_storage_modify(self.op.node_name,
3682
                                          self.op.storage_type, st_args,
3683
                                          self.op.name, self.op.changes)
3684
    result.Raise("Failed to modify storage unit '%s' on %s" %
3685
                 (self.op.name, self.op.node_name))
3686

    
3687

    
3688
class LUAddNode(LogicalUnit):
3689
  """Logical unit for adding node to the cluster.
3690

3691
  """
3692
  HPATH = "node-add"
3693
  HTYPE = constants.HTYPE_NODE
3694
  _OP_PARAMS = [
3695
    _PNodeName,
3696
    ("primary_ip", None, _NoType),
3697
    ("secondary_ip", None, _TMaybeString),
3698
    ("readd", False, _TBool),
3699
    ]
3700

    
3701
  def CheckArguments(self):
3702
    # validate/normalize the node name
3703
    self.op.node_name = netutils.HostInfo.NormalizeName(self.op.node_name)
3704

    
3705
  def BuildHooksEnv(self):
3706
    """Build hooks env.
3707

3708
    This will run on all nodes before, and on all nodes + the new node after.
3709

3710
    """
3711
    env = {
3712
      "OP_TARGET": self.op.node_name,
3713
      "NODE_NAME": self.op.node_name,
3714
      "NODE_PIP": self.op.primary_ip,
3715
      "NODE_SIP": self.op.secondary_ip,
3716
      }
3717
    nodes_0 = self.cfg.GetNodeList()
3718
    nodes_1 = nodes_0 + [self.op.node_name, ]
3719
    return env, nodes_0, nodes_1
3720

    
3721
  def CheckPrereq(self):
3722
    """Check prerequisites.
3723

3724
    This checks:
3725
     - the new node is not already in the config
3726
     - it is resolvable
3727
     - its parameters (single/dual homed) matches the cluster
3728

3729
    Any errors are signaled by raising errors.OpPrereqError.
3730

3731
    """
3732
    node_name = self.op.node_name
3733
    cfg = self.cfg
3734

    
3735
    dns_data = netutils.GetHostInfo(node_name)
3736

    
3737
    node = dns_data.name
3738
    primary_ip = self.op.primary_ip = dns_data.ip
3739
    if self.op.secondary_ip is None:
3740
      self.op.secondary_ip = primary_ip
3741
    if not netutils.IsValidIP4(self.op.secondary_ip):
3742
      raise errors.OpPrereqError("Invalid secondary IP given",
3743
                                 errors.ECODE_INVAL)
3744
    secondary_ip = self.op.secondary_ip
3745

    
3746
    node_list = cfg.GetNodeList()
3747
    if not self.op.readd and node in node_list:
3748
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3749
                                 node, errors.ECODE_EXISTS)
3750
    elif self.op.readd and node not in node_list:
3751
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3752
                                 errors.ECODE_NOENT)
3753

    
3754
    self.changed_primary_ip = False
3755

    
3756
    for existing_node_name in node_list:
3757
      existing_node = cfg.GetNodeInfo(existing_node_name)
3758

    
3759
      if self.op.readd and node == existing_node_name:
3760
        if existing_node.secondary_ip != secondary_ip:
3761
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3762
                                     " address configuration as before",
3763
                                     errors.ECODE_INVAL)
3764
        if existing_node.primary_ip != primary_ip:
3765
          self.changed_primary_ip = True
3766

    
3767
        continue
3768

    
3769
      if (existing_node.primary_ip == primary_ip or
3770
          existing_node.secondary_ip == primary_ip or
3771
          existing_node.primary_ip == secondary_ip or
3772
          existing_node.secondary_ip == secondary_ip):
3773
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3774
                                   " existing node %s" % existing_node.name,
3775
                                   errors.ECODE_NOTUNIQUE)
3776

    
3777
    # check that the type of the node (single versus dual homed) is the
3778
    # same as for the master
3779
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3780
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3781
    newbie_singlehomed = secondary_ip == primary_ip
3782
    if master_singlehomed != newbie_singlehomed:
3783
      if master_singlehomed:
3784
        raise errors.OpPrereqError("The master has no private ip but the"
3785
                                   " new node has one",
3786
                                   errors.ECODE_INVAL)
3787
      else:
3788
        raise errors.OpPrereqError("The master has a private ip but the"
3789
                                   " new node doesn't have one",
3790
                                   errors.ECODE_INVAL)
3791

    
3792
    # checks reachability
3793
    if not netutils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3794
      raise errors.OpPrereqError("Node not reachable by ping",
3795
                                 errors.ECODE_ENVIRON)
3796

    
3797
    if not newbie_singlehomed:
3798
      # check reachability from my secondary ip to newbie's secondary ip
3799
      if not netutils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3800
                           source=myself.secondary_ip):
3801
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3802
                                   " based ping to noded port",
3803
                                   errors.ECODE_ENVIRON)
3804

    
3805
    if self.op.readd:
3806
      exceptions = [node]
3807
    else:
3808
      exceptions = []
3809

    
3810
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3811

    
3812
    if self.op.readd:
3813
      self.new_node = self.cfg.GetNodeInfo(node)
3814
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3815
    else:
3816
      self.new_node = objects.Node(name=node,
3817
                                   primary_ip=primary_ip,
3818
                                   secondary_ip=secondary_ip,
3819
                                   master_candidate=self.master_candidate,
3820
                                   offline=False, drained=False)
3821

    
3822
  def Exec(self, feedback_fn):
3823
    """Adds the new node to the cluster.
3824

3825
    """
3826
    new_node = self.new_node
3827
    node = new_node.name
3828

    
3829
    # for re-adds, reset the offline/drained/master-candidate flags;
3830
    # we need to reset here, otherwise offline would prevent RPC calls
3831
    # later in the procedure; this also means that if the re-add
3832
    # fails, we are left with a non-offlined, broken node
3833
    if self.op.readd:
3834
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3835
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3836
      # if we demote the node, we do cleanup later in the procedure
3837
      new_node.master_candidate = self.master_candidate
3838
      if self.changed_primary_ip:
3839
        new_node.primary_ip = self.op.primary_ip
3840

    
3841
    # notify the user about any possible mc promotion
3842
    if new_node.master_candidate:
3843
      self.LogInfo("Node will be a master candidate")
3844

    
3845
    # check connectivity
3846
    result = self.rpc.call_version([node])[node]
3847
    result.Raise("Can't get version information from node %s" % node)
3848
    if constants.PROTOCOL_VERSION == result.payload:
3849
      logging.info("Communication to node %s fine, sw version %s match",
3850
                   node, result.payload)
3851
    else:
3852
      raise errors.OpExecError("Version mismatch master version %s,"
3853
                               " node version %s" %
3854
                               (constants.PROTOCOL_VERSION, result.payload))
3855

    
3856
    # setup ssh on node
3857
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3858
      logging.info("Copy ssh key to node %s", node)
3859
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3860
      keyarray = []
3861
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3862
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3863
                  priv_key, pub_key]
3864

    
3865
      for i in keyfiles:
3866
        keyarray.append(utils.ReadFile(i))
3867

    
3868
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3869
                                      keyarray[2], keyarray[3], keyarray[4],
3870
                                      keyarray[5])
3871
      result.Raise("Cannot transfer ssh keys to the new node")
3872

    
3873
    # Add node to our /etc/hosts, and add key to known_hosts
3874
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3875
      # FIXME: this should be done via an rpc call to node daemon
3876
      utils.AddHostToEtcHosts(new_node.name)
3877

    
3878
    if new_node.secondary_ip != new_node.primary_ip:
3879
      result = self.rpc.call_node_has_ip_address(new_node.name,
3880
                                                 new_node.secondary_ip)
3881
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3882
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3883
      if not result.payload:
3884
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3885
                                 " you gave (%s). Please fix and re-run this"
3886
                                 " command." % new_node.secondary_ip)
3887

    
3888
    node_verify_list = [self.cfg.GetMasterNode()]
3889
    node_verify_param = {
3890
      constants.NV_NODELIST: [node],
3891
      # TODO: do a node-net-test as well?
3892
    }
3893

    
3894
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3895
                                       self.cfg.GetClusterName())
3896
    for verifier in node_verify_list:
3897
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3898
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3899
      if nl_payload:
3900
        for failed in nl_payload:
3901
          feedback_fn("ssh/hostname verification failed"
3902
                      " (checking from %s): %s" %
3903
                      (verifier, nl_payload[failed]))
3904
        raise errors.OpExecError("ssh/hostname verification failed.")
3905

    
3906
    if self.op.readd:
3907
      _RedistributeAncillaryFiles(self)
3908
      self.context.ReaddNode(new_node)
3909
      # make sure we redistribute the config
3910
      self.cfg.Update(new_node, feedback_fn)
3911
      # and make sure the new node will not have old files around
3912
      if not new_node.master_candidate:
3913
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3914
        msg = result.fail_msg
3915
        if msg:
3916
          self.LogWarning("Node failed to demote itself from master"
3917
                          " candidate status: %s" % msg)
3918
    else:
3919
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3920
      self.context.AddNode(new_node, self.proc.GetECId())
3921

    
3922

    
3923
class LUSetNodeParams(LogicalUnit):
3924
  """Modifies the parameters of a node.
3925

3926
  """
3927
  HPATH = "node-modify"
3928
  HTYPE = constants.HTYPE_NODE
3929
  _OP_PARAMS = [
3930
    _PNodeName,
3931
    ("master_candidate", None, _TMaybeBool),
3932
    ("offline", None, _TMaybeBool),
3933
    ("drained", None, _TMaybeBool),
3934
    ("auto_promote", False, _TBool),
3935
    _PForce,
3936
    ]
3937
  REQ_BGL = False
3938

    
3939
  def CheckArguments(self):
3940
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3941
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3942
    if all_mods.count(None) == 3:
3943
      raise errors.OpPrereqError("Please pass at least one modification",
3944
                                 errors.ECODE_INVAL)
3945
    if all_mods.count(True) > 1:
3946
      raise errors.OpPrereqError("Can't set the node into more than one"
3947
                                 " state at the same time",
3948
                                 errors.ECODE_INVAL)
3949

    
3950
    # Boolean value that tells us whether we're offlining or draining the node
3951
    self.offline_or_drain = (self.op.offline == True or
3952
                             self.op.drained == True)
3953
    self.deoffline_or_drain = (self.op.offline == False or
3954
                               self.op.drained == False)
3955
    self.might_demote = (self.op.master_candidate == False or
3956
                         self.offline_or_drain)
3957

    
3958
    self.lock_all = self.op.auto_promote and self.might_demote
3959

    
3960

    
3961
  def ExpandNames(self):
3962
    if self.lock_all:
3963
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3964
    else:
3965
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3966

    
3967
  def BuildHooksEnv(self):
3968
    """Build hooks env.
3969

3970
    This runs on the master node.
3971

3972
    """
3973
    env = {
3974
      "OP_TARGET": self.op.node_name,
3975
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3976
      "OFFLINE": str(self.op.offline),
3977
      "DRAINED": str(self.op.drained),
3978
      }
3979
    nl = [self.cfg.GetMasterNode(),
3980
          self.op.node_name]
3981
    return env, nl, nl
3982

    
3983
  def CheckPrereq(self):
3984
    """Check prerequisites.
3985

3986
    This only checks the instance list against the existing names.
3987

3988
    """
3989
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3990

    
3991
    if (self.op.master_candidate is not None or
3992
        self.op.drained is not None or
3993
        self.op.offline is not None):
3994
      # we can't change the master's node flags
3995
      if self.op.node_name == self.cfg.GetMasterNode():
3996
        raise errors.OpPrereqError("The master role can be changed"
3997
                                   " only via master-failover",
3998
                                   errors.ECODE_INVAL)
3999

    
4000

    
4001
    if node.master_candidate and self.might_demote and not self.lock_all:
4002
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
4003
      # check if after removing the current node, we're missing master
4004
      # candidates
4005
      (mc_remaining, mc_should, _) = \
4006
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
4007
      if mc_remaining < mc_should:
4008
        raise errors.OpPrereqError("Not enough master candidates, please"
4009
                                   " pass auto_promote to allow promotion",
4010
                                   errors.ECODE_INVAL)
4011

    
4012
    if (self.op.master_candidate == True and
4013
        ((node.offline and not self.op.offline == False) or
4014
         (node.drained and not self.op.drained == False))):
4015
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
4016
                                 " to master_candidate" % node.name,
4017
                                 errors.ECODE_INVAL)
4018

    
4019
    # If we're being deofflined/drained, we'll MC ourself if needed
4020
    if (self.deoffline_or_drain and not self.offline_or_drain and not
4021
        self.op.master_candidate == True and not node.master_candidate):
4022
      self.op.master_candidate = _DecideSelfPromotion(self)
4023
      if self.op.master_candidate:
4024
        self.LogInfo("Autopromoting node to master candidate")
4025

    
4026
    return
4027

    
4028
  def Exec(self, feedback_fn):
4029
    """Modifies a node.
4030

4031
    """
4032
    node = self.node
4033

    
4034
    result = []
4035
    changed_mc = False
4036

    
4037
    if self.op.offline is not None:
4038
      node.offline = self.op.offline
4039
      result.append(("offline", str(self.op.offline)))
4040
      if self.op.offline == True:
4041
        if node.master_candidate:
4042
          node.master_candidate = False
4043
          changed_mc = True
4044
          result.append(("master_candidate", "auto-demotion due to offline"))
4045
        if node.drained:
4046
          node.drained = False
4047
          result.append(("drained", "clear drained status due to offline"))
4048

    
4049
    if self.op.master_candidate is not None:
4050
      node.master_candidate = self.op.master_candidate
4051
      changed_mc = True
4052
      result.append(("master_candidate", str(self.op.master_candidate)))
4053
      if self.op.master_candidate == False:
4054
        rrc = self.rpc.call_node_demote_from_mc(node.name)
4055
        msg = rrc.fail_msg
4056
        if msg:
4057
          self.LogWarning("Node failed to demote itself: %s" % msg)
4058

    
4059
    if self.op.drained is not None:
4060
      node.drained = self.op.drained
4061
      result.append(("drained", str(self.op.drained)))
4062
      if self.op.drained == True:
4063
        if node.master_candidate:
4064
          node.master_candidate = False
4065
          changed_mc = True
4066
          result.append(("master_candidate", "auto-demotion due to drain"))
4067
          rrc = self.rpc.call_node_demote_from_mc(node.name)
4068
          msg = rrc.fail_msg
4069
          if msg:
4070
            self.LogWarning("Node failed to demote itself: %s" % msg)
4071
        if node.offline:
4072
          node.offline = False
4073
          result.append(("offline", "clear offline status due to drain"))
4074

    
4075
    # we locked all nodes, we adjust the CP before updating this node
4076
    if self.lock_all:
4077
      _AdjustCandidatePool(self, [node.name])
4078

    
4079
    # this will trigger configuration file update, if needed
4080
    self.cfg.Update(node, feedback_fn)
4081

    
4082
    # this will trigger job queue propagation or cleanup
4083
    if changed_mc:
4084
      self.context.ReaddNode(node)
4085

    
4086
    return result
4087

    
4088

    
4089
class LUPowercycleNode(NoHooksLU):
4090
  """Powercycles a node.
4091

4092
  """
4093
  _OP_PARAMS = [
4094
    _PNodeName,
4095
    _PForce,
4096
    ]
4097
  REQ_BGL = False
4098

    
4099
  def CheckArguments(self):
4100
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
4101
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
4102
      raise errors.OpPrereqError("The node is the master and the force"
4103
                                 " parameter was not set",
4104
                                 errors.ECODE_INVAL)
4105

    
4106
  def ExpandNames(self):
4107
    """Locking for PowercycleNode.
4108

4109
    This is a last-resort option and shouldn't block on other
4110
    jobs. Therefore, we grab no locks.
4111

4112
    """
4113
    self.needed_locks = {}
4114

    
4115
  def Exec(self, feedback_fn):
4116
    """Reboots a node.
4117

4118
    """
4119
    result = self.rpc.call_node_powercycle(self.op.node_name,
4120
                                           self.cfg.GetHypervisorType())
4121
    result.Raise("Failed to schedule the reboot")
4122
    return result.payload
4123

    
4124

    
4125
class LUQueryClusterInfo(NoHooksLU):
4126
  """Query cluster configuration.
4127

4128
  """
4129
  REQ_BGL = False
4130

    
4131
  def ExpandNames(self):
4132
    self.needed_locks = {}
4133

    
4134
  def Exec(self, feedback_fn):
4135
    """Return cluster config.
4136

4137
    """
4138
    cluster = self.cfg.GetClusterInfo()
4139
    os_hvp = {}
4140

    
4141
    # Filter just for enabled hypervisors
4142
    for os_name, hv_dict in cluster.os_hvp.items():
4143
      os_hvp[os_name] = {}
4144
      for hv_name, hv_params in hv_dict.items():
4145
        if hv_name in cluster.enabled_hypervisors:
4146
          os_hvp[os_name][hv_name] = hv_params
4147

    
4148
    result = {
4149
      "software_version": constants.RELEASE_VERSION,
4150
      "protocol_version": constants.PROTOCOL_VERSION,
4151
      "config_version": constants.CONFIG_VERSION,
4152
      "os_api_version": max(constants.OS_API_VERSIONS),
4153
      "export_version": constants.EXPORT_VERSION,
4154
      "architecture": (platform.architecture()[0], platform.machine()),
4155
      "name": cluster.cluster_name,
4156
      "master": cluster.master_node,
4157
      "default_hypervisor": cluster.enabled_hypervisors[0],
4158
      "enabled_hypervisors": cluster.enabled_hypervisors,
4159
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4160
                        for hypervisor_name in cluster.enabled_hypervisors]),
4161
      "os_hvp": os_hvp,
4162
      "beparams": cluster.beparams,
4163
      "osparams": cluster.osparams,
4164
      "nicparams": cluster.nicparams,
4165
      "candidate_pool_size": cluster.candidate_pool_size,
4166
      "master_netdev": cluster.master_netdev,
4167
      "volume_group_name": cluster.volume_group_name,
4168
      "drbd_usermode_helper": cluster.drbd_usermode_helper,
4169
      "file_storage_dir": cluster.file_storage_dir,
4170
      "maintain_node_health": cluster.maintain_node_health,
4171
      "ctime": cluster.ctime,
4172
      "mtime": cluster.mtime,
4173
      "uuid": cluster.uuid,
4174
      "tags": list(cluster.GetTags()),
4175
      "uid_pool": cluster.uid_pool,
4176
      "default_iallocator": cluster.default_iallocator,
4177
      "reserved_lvs": cluster.reserved_lvs,
4178
      }
4179

    
4180
    return result
4181

    
4182

    
4183
class LUQueryConfigValues(NoHooksLU):
4184
  """Return configuration values.
4185

4186
  """
4187
  _OP_PARAMS = [_POutputFields]
4188
  REQ_BGL = False
4189
  _FIELDS_DYNAMIC = utils.FieldSet()
4190
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4191
                                  "watcher_pause")
4192

    
4193
  def CheckArguments(self):
4194
    _CheckOutputFields(static=self._FIELDS_STATIC,
4195
                       dynamic=self._FIELDS_DYNAMIC,
4196
                       selected=self.op.output_fields)
4197

    
4198
  def ExpandNames(self):
4199
    self.needed_locks = {}
4200

    
4201
  def Exec(self, feedback_fn):
4202
    """Dump a representation of the cluster config to the standard output.
4203

4204
    """
4205
    values = []
4206
    for field in self.op.output_fields:
4207
      if field == "cluster_name":
4208
        entry = self.cfg.GetClusterName()
4209
      elif field == "master_node":
4210
        entry = self.cfg.GetMasterNode()
4211
      elif field == "drain_flag":
4212
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4213
      elif field == "watcher_pause":
4214
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4215
      else:
4216
        raise errors.ParameterError(field)
4217
      values.append(entry)
4218
    return values
4219

    
4220

    
4221
class LUActivateInstanceDisks(NoHooksLU):
4222
  """Bring up an instance's disks.
4223

4224
  """
4225
  _OP_PARAMS = [
4226
    _PInstanceName,
4227
    ("ignore_size", False, _TBool),
4228
    ]
4229
  REQ_BGL = False
4230

    
4231
  def ExpandNames(self):
4232
    self._ExpandAndLockInstance()
4233
    self.needed_locks[locking.LEVEL_NODE] = []
4234
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4235

    
4236
  def DeclareLocks(self, level):
4237
    if level == locking.LEVEL_NODE:
4238
      self._LockInstancesNodes()
4239

    
4240
  def CheckPrereq(self):
4241
    """Check prerequisites.
4242

4243
    This checks that the instance is in the cluster.
4244

4245
    """
4246
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4247
    assert self.instance is not None, \
4248
      "Cannot retrieve locked instance %s" % self.op.instance_name
4249
    _CheckNodeOnline(self, self.instance.primary_node)
4250

    
4251
  def Exec(self, feedback_fn):
4252
    """Activate the disks.
4253

4254
    """
4255
    disks_ok, disks_info = \
4256
              _AssembleInstanceDisks(self, self.instance,
4257
                                     ignore_size=self.op.ignore_size)
4258
    if not disks_ok:
4259
      raise errors.OpExecError("Cannot activate block devices")
4260

    
4261
    return disks_info
4262

    
4263

    
4264
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4265
                           ignore_size=False):
4266
  """Prepare the block devices for an instance.
4267

4268
  This sets up the block devices on all nodes.
4269

4270
  @type lu: L{LogicalUnit}
4271
  @param lu: the logical unit on whose behalf we execute
4272
  @type instance: L{objects.Instance}
4273
  @param instance: the instance for whose disks we assemble
4274
  @type disks: list of L{objects.Disk} or None
4275
  @param disks: which disks to assemble (or all, if None)
4276
  @type ignore_secondaries: boolean
4277
  @param ignore_secondaries: if true, errors on secondary nodes
4278
      won't result in an error return from the function
4279
  @type ignore_size: boolean
4280
  @param ignore_size: if true, the current known size of the disk
4281
      will not be used during the disk activation, useful for cases
4282
      when the size is wrong
4283
  @return: False if the operation failed, otherwise a list of
4284
      (host, instance_visible_name, node_visible_name)
4285
      with the mapping from node devices to instance devices
4286

4287
  """
4288
  device_info = []
4289
  disks_ok = True
4290
  iname = instance.name
4291
  disks = _ExpandCheckDisks(instance, disks)
4292

    
4293
  # With the two passes mechanism we try to reduce the window of
4294
  # opportunity for the race condition of switching DRBD to primary
4295
  # before handshaking occured, but we do not eliminate it
4296

    
4297
  # The proper fix would be to wait (with some limits) until the
4298
  # connection has been made and drbd transitions from WFConnection
4299
  # into any other network-connected state (Connected, SyncTarget,
4300
  # SyncSource, etc.)
4301

    
4302
  # 1st pass, assemble on all nodes in secondary mode
4303
  for inst_disk in disks:
4304
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4305
      if ignore_size:
4306
        node_disk = node_disk.Copy()
4307
        node_disk.UnsetSize()
4308
      lu.cfg.SetDiskID(node_disk, node)
4309
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4310
      msg = result.fail_msg
4311
      if msg:
4312
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4313
                           " (is_primary=False, pass=1): %s",
4314
                           inst_disk.iv_name, node, msg)
4315
        if not ignore_secondaries:
4316
          disks_ok = False
4317

    
4318
  # FIXME: race condition on drbd migration to primary
4319

    
4320
  # 2nd pass, do only the primary node
4321
  for inst_disk in disks:
4322
    dev_path = None
4323

    
4324
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4325
      if node != instance.primary_node:
4326
        continue
4327
      if ignore_size:
4328
        node_disk = node_disk.Copy()
4329
        node_disk.UnsetSize()
4330
      lu.cfg.SetDiskID(node_disk, node)
4331
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4332
      msg = result.fail_msg
4333
      if msg:
4334
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4335
                           " (is_primary=True, pass=2): %s",
4336
                           inst_disk.iv_name, node, msg)
4337
        disks_ok = False
4338
      else:
4339
        dev_path = result.payload
4340

    
4341
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4342

    
4343
  # leave the disks configured for the primary node
4344
  # this is a workaround that would be fixed better by
4345
  # improving the logical/physical id handling
4346
  for disk in disks:
4347
    lu.cfg.SetDiskID(disk, instance.primary_node)
4348

    
4349
  return disks_ok, device_info
4350

    
4351

    
4352
def _StartInstanceDisks(lu, instance, force):
4353
  """Start the disks of an instance.
4354

4355
  """
4356
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4357
                                           ignore_secondaries=force)
4358
  if not disks_ok:
4359
    _ShutdownInstanceDisks(lu, instance)
4360
    if force is not None and not force:
4361
      lu.proc.LogWarning("", hint="If the message above refers to a"
4362
                         " secondary node,"
4363
                         " you can retry the operation using '--force'.")
4364
    raise errors.OpExecError("Disk consistency error")
4365

    
4366

    
4367
class LUDeactivateInstanceDisks(NoHooksLU):
4368
  """Shutdown an instance's disks.
4369

4370
  """
4371
  _OP_PARAMS = [
4372
    _PInstanceName,
4373
    ]
4374
  REQ_BGL = False
4375

    
4376
  def ExpandNames(self):
4377
    self._ExpandAndLockInstance()
4378
    self.needed_locks[locking.LEVEL_NODE] = []
4379
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4380

    
4381
  def DeclareLocks(self, level):
4382
    if level == locking.LEVEL_NODE:
4383
      self._LockInstancesNodes()
4384

    
4385
  def CheckPrereq(self):
4386
    """Check prerequisites.
4387

4388
    This checks that the instance is in the cluster.
4389

4390
    """
4391
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4392
    assert self.instance is not None, \
4393
      "Cannot retrieve locked instance %s" % self.op.instance_name
4394

    
4395
  def Exec(self, feedback_fn):
4396
    """Deactivate the disks
4397

4398
    """
4399
    instance = self.instance
4400
    _SafeShutdownInstanceDisks(self, instance)
4401

    
4402

    
4403
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4404
  """Shutdown block devices of an instance.
4405

4406
  This function checks if an instance is running, before calling
4407
  _ShutdownInstanceDisks.
4408

4409
  """
4410
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4411
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4412

    
4413

    
4414
def _ExpandCheckDisks(instance, disks):
4415
  """Return the instance disks selected by the disks list
4416

4417
  @type disks: list of L{objects.Disk} or None
4418
  @param disks: selected disks
4419
  @rtype: list of L{objects.Disk}
4420
  @return: selected instance disks to act on
4421

4422
  """
4423
  if disks is None:
4424
    return instance.disks
4425
  else:
4426
    if not set(disks).issubset(instance.disks):
4427
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4428
                                   " target instance")
4429
    return disks
4430

    
4431

    
4432
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4433
  """Shutdown block devices of an instance.
4434

4435
  This does the shutdown on all nodes of the instance.
4436

4437
  If the ignore_primary is false, errors on the primary node are
4438
  ignored.
4439

4440
  """
4441
  all_result = True
4442
  disks = _ExpandCheckDisks(instance, disks)
4443

    
4444
  for disk in disks:
4445
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4446
      lu.cfg.SetDiskID(top_disk, node)
4447
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4448
      msg = result.fail_msg
4449
      if msg:
4450
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4451
                      disk.iv_name, node, msg)
4452
        if not ignore_primary or node != instance.primary_node:
4453
          all_result = False
4454
  return all_result
4455

    
4456

    
4457
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4458
  """Checks if a node has enough free memory.
4459

4460
  This function check if a given node has the needed amount of free
4461
  memory. In case the node has less memory or we cannot get the
4462
  information from the node, this function raise an OpPrereqError
4463
  exception.
4464

4465
  @type lu: C{LogicalUnit}
4466
  @param lu: a logical unit from which we get configuration data
4467
  @type node: C{str}
4468
  @param node: the node to check
4469
  @type reason: C{str}
4470
  @param reason: string to use in the error message
4471
  @type requested: C{int}
4472
  @param requested: the amount of memory in MiB to check for
4473
  @type hypervisor_name: C{str}
4474
  @param hypervisor_name: the hypervisor to ask for memory stats
4475
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4476
      we cannot check the node
4477

4478
  """
4479
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4480
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4481
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4482
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4483
  if not isinstance(free_mem, int):
4484
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4485
                               " was '%s'" % (node, free_mem),
4486
                               errors.ECODE_ENVIRON)
4487
  if requested > free_mem:
4488
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4489
                               " needed %s MiB, available %s MiB" %
4490
                               (node, reason, requested, free_mem),
4491
                               errors.ECODE_NORES)
4492

    
4493

    
4494
def _CheckNodesFreeDisk(lu, nodenames, requested):
4495
  """Checks if nodes have enough free disk space in the default VG.
4496

4497
  This function check if all given nodes have the needed amount of
4498
  free disk. In case any node has less disk or we cannot get the
4499
  information from the node, this function raise an OpPrereqError
4500
  exception.
4501

4502
  @type lu: C{LogicalUnit}
4503
  @param lu: a logical unit from which we get configuration data
4504
  @type nodenames: C{list}
4505
  @param nodenames: the list of node names to check
4506
  @type requested: C{int}
4507
  @param requested: the amount of disk in MiB to check for
4508
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4509
      we cannot check the node
4510

4511
  """
4512
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4513
                                   lu.cfg.GetHypervisorType())
4514
  for node in nodenames:
4515
    info = nodeinfo[node]
4516
    info.Raise("Cannot get current information from node %s" % node,
4517
               prereq=True, ecode=errors.ECODE_ENVIRON)
4518
    vg_free = info.payload.get("vg_free", None)
4519
    if not isinstance(vg_free, int):
4520
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4521
                                 " result was '%s'" % (node, vg_free),
4522
                                 errors.ECODE_ENVIRON)
4523
    if requested > vg_free:
4524
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4525
                                 " required %d MiB, available %d MiB" %
4526
                                 (node, requested, vg_free),
4527
                                 errors.ECODE_NORES)
4528

    
4529

    
4530
class LUStartupInstance(LogicalUnit):
4531
  """Starts an instance.
4532

4533
  """
4534
  HPATH = "instance-start"
4535
  HTYPE = constants.HTYPE_INSTANCE
4536
  _OP_PARAMS = [
4537
    _PInstanceName,
4538
    _PForce,
4539
    ("hvparams", _EmptyDict, _TDict),
4540
    ("beparams", _EmptyDict, _TDict),
4541
    ]
4542
  REQ_BGL = False
4543

    
4544
  def CheckArguments(self):
4545
    # extra beparams
4546
    if self.op.beparams:
4547
      # fill the beparams dict
4548
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4549

    
4550
  def ExpandNames(self):
4551
    self._ExpandAndLockInstance()
4552

    
4553
  def BuildHooksEnv(self):
4554
    """Build hooks env.
4555

4556
    This runs on master, primary and secondary nodes of the instance.
4557

4558
    """
4559
    env = {
4560
      "FORCE": self.op.force,
4561
      }
4562
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4563
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4564
    return env, nl, nl
4565

    
4566
  def CheckPrereq(self):
4567
    """Check prerequisites.
4568

4569
    This checks that the instance is in the cluster.
4570

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

    
4576
    # extra hvparams
4577
    if self.op.hvparams:
4578
      # check hypervisor parameter syntax (locally)
4579
      cluster = self.cfg.GetClusterInfo()
4580
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4581
      filled_hvp = cluster.FillHV(instance)
4582
      filled_hvp.update(self.op.hvparams)
4583
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4584
      hv_type.CheckParameterSyntax(filled_hvp)
4585
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4586

    
4587
    _CheckNodeOnline(self, instance.primary_node)
4588

    
4589
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4590
    # check bridges existence
4591
    _CheckInstanceBridgesExist(self, instance)
4592

    
4593
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4594
                                              instance.name,
4595
                                              instance.hypervisor)
4596
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4597
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4598
    if not remote_info.payload: # not running already
4599
      _CheckNodeFreeMemory(self, instance.primary_node,
4600
                           "starting instance %s" % instance.name,
4601
                           bep[constants.BE_MEMORY], instance.hypervisor)
4602

    
4603
  def Exec(self, feedback_fn):
4604
    """Start the instance.
4605

4606
    """
4607
    instance = self.instance
4608
    force = self.op.force
4609

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

    
4612
    node_current = instance.primary_node
4613

    
4614
    _StartInstanceDisks(self, instance, force)
4615

    
4616
    result = self.rpc.call_instance_start(node_current, instance,
4617
                                          self.op.hvparams, self.op.beparams)
4618
    msg = result.fail_msg
4619
    if msg:
4620
      _ShutdownInstanceDisks(self, instance)
4621
      raise errors.OpExecError("Could not start instance: %s" % msg)
4622

    
4623

    
4624
class LURebootInstance(LogicalUnit):
4625
  """Reboot an instance.
4626

4627
  """
4628
  HPATH = "instance-reboot"
4629
  HTYPE = constants.HTYPE_INSTANCE
4630
  _OP_PARAMS = [
4631
    _PInstanceName,
4632
    ("ignore_secondaries", False, _TBool),
4633
    ("reboot_type", _NoDefault, _TElemOf(constants.REBOOT_TYPES)),
4634
    _PShutdownTimeout,
4635
    ]
4636
  REQ_BGL = False
4637

    
4638
  def ExpandNames(self):
4639
    self._ExpandAndLockInstance()
4640

    
4641
  def BuildHooksEnv(self):
4642
    """Build hooks env.
4643

4644
    This runs on master, primary and secondary nodes of the instance.
4645

4646
    """
4647
    env = {
4648
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4649
      "REBOOT_TYPE": self.op.reboot_type,
4650
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4651
      }
4652
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4653
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4654
    return env, nl, nl
4655

    
4656
  def CheckPrereq(self):
4657
    """Check prerequisites.
4658

4659
    This checks that the instance is in the cluster.
4660

4661
    """
4662
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4663
    assert self.instance is not None, \
4664
      "Cannot retrieve locked instance %s" % self.op.instance_name
4665

    
4666
    _CheckNodeOnline(self, instance.primary_node)
4667

    
4668
    # check bridges existence
4669
    _CheckInstanceBridgesExist(self, instance)
4670

    
4671
  def Exec(self, feedback_fn):
4672
    """Reboot the instance.
4673

4674
    """
4675
    instance = self.instance
4676
    ignore_secondaries = self.op.ignore_secondaries
4677
    reboot_type = self.op.reboot_type
4678

    
4679
    node_current = instance.primary_node
4680

    
4681
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4682
                       constants.INSTANCE_REBOOT_HARD]:
4683
      for disk in instance.disks:
4684
        self.cfg.SetDiskID(disk, node_current)
4685
      result = self.rpc.call_instance_reboot(node_current, instance,
4686
                                             reboot_type,
4687
                                             self.op.shutdown_timeout)
4688
      result.Raise("Could not reboot instance")
4689
    else:
4690
      result = self.rpc.call_instance_shutdown(node_current, instance,
4691
                                               self.op.shutdown_timeout)
4692
      result.Raise("Could not shutdown instance for full reboot")
4693
      _ShutdownInstanceDisks(self, instance)
4694
      _StartInstanceDisks(self, instance, ignore_secondaries)
4695
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4696
      msg = result.fail_msg
4697
      if msg:
4698
        _ShutdownInstanceDisks(self, instance)
4699
        raise errors.OpExecError("Could not start instance for"
4700
                                 " full reboot: %s" % msg)
4701

    
4702
    self.cfg.MarkInstanceUp(instance.name)
4703

    
4704

    
4705
class LUShutdownInstance(LogicalUnit):
4706
  """Shutdown an instance.
4707

4708
  """
4709
  HPATH = "instance-stop"
4710
  HTYPE = constants.HTYPE_INSTANCE
4711
  _OP_PARAMS = [
4712
    _PInstanceName,
4713
    ("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT, _TPositiveInt),
4714
    ]
4715
  REQ_BGL = False
4716

    
4717
  def ExpandNames(self):
4718
    self._ExpandAndLockInstance()
4719

    
4720
  def BuildHooksEnv(self):
4721
    """Build hooks env.
4722

4723
    This runs on master, primary and secondary nodes of the instance.
4724

4725
    """
4726
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4727
    env["TIMEOUT"] = self.op.timeout
4728
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4729
    return env, nl, nl
4730

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

4734
    This checks that the instance is in the cluster.
4735

4736
    """
4737
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4738
    assert self.instance is not None, \
4739
      "Cannot retrieve locked instance %s" % self.op.instance_name
4740
    _CheckNodeOnline(self, self.instance.primary_node)
4741

    
4742
  def Exec(self, feedback_fn):
4743
    """Shutdown the instance.
4744

4745
    """
4746
    instance = self.instance
4747
    node_current = instance.primary_node
4748
    timeout = self.op.timeout
4749
    self.cfg.MarkInstanceDown(instance.name)
4750
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4751
    msg = result.fail_msg
4752
    if msg:
4753
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4754

    
4755
    _ShutdownInstanceDisks(self, instance)
4756

    
4757

    
4758
class LUReinstallInstance(LogicalUnit):
4759
  """Reinstall an instance.
4760

4761
  """
4762
  HPATH = "instance-reinstall"
4763
  HTYPE = constants.HTYPE_INSTANCE
4764
  _OP_PARAMS = [
4765
    _PInstanceName,
4766
    ("os_type", None, _TMaybeString),
4767
    ("force_variant", False, _TBool),
4768
    ]
4769
  REQ_BGL = False
4770

    
4771
  def ExpandNames(self):
4772
    self._ExpandAndLockInstance()
4773

    
4774
  def BuildHooksEnv(self):
4775
    """Build hooks env.
4776

4777
    This runs on master, primary and secondary nodes of the instance.
4778

4779
    """
4780
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4781
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4782
    return env, nl, nl
4783

    
4784
  def CheckPrereq(self):
4785
    """Check prerequisites.
4786

4787
    This checks that the instance is in the cluster and is not running.
4788

4789
    """
4790
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4791
    assert instance is not None, \
4792
      "Cannot retrieve locked instance %s" % self.op.instance_name
4793
    _CheckNodeOnline(self, instance.primary_node)
4794

    
4795
    if instance.disk_template == constants.DT_DISKLESS:
4796
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4797
                                 self.op.instance_name,
4798
                                 errors.ECODE_INVAL)
4799
    _CheckInstanceDown(self, instance, "cannot reinstall")
4800

    
4801
    if self.op.os_type is not None:
4802
      # OS verification
4803
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4804
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4805

    
4806
    self.instance = instance
4807

    
4808
  def Exec(self, feedback_fn):
4809
    """Reinstall the instance.
4810

4811
    """
4812
    inst = self.instance
4813

    
4814
    if self.op.os_type is not None:
4815
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4816
      inst.os = self.op.os_type
4817
      self.cfg.Update(inst, feedback_fn)
4818

    
4819
    _StartInstanceDisks(self, inst, None)
4820
    try:
4821
      feedback_fn("Running the instance OS create scripts...")
4822
      # FIXME: pass debug option from opcode to backend
4823
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4824
                                             self.op.debug_level)
4825
      result.Raise("Could not install OS for instance %s on node %s" %
4826
                   (inst.name, inst.primary_node))
4827
    finally:
4828
      _ShutdownInstanceDisks(self, inst)
4829

    
4830

    
4831
class LURecreateInstanceDisks(LogicalUnit):
4832
  """Recreate an instance's missing disks.
4833

4834
  """
4835
  HPATH = "instance-recreate-disks"
4836
  HTYPE = constants.HTYPE_INSTANCE
4837
  _OP_PARAMS = [
4838
    _PInstanceName,
4839
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
4840
    ]
4841
  REQ_BGL = False
4842

    
4843
  def ExpandNames(self):
4844
    self._ExpandAndLockInstance()
4845

    
4846
  def BuildHooksEnv(self):
4847
    """Build hooks env.
4848

4849
    This runs on master, primary and secondary nodes of the instance.
4850

4851
    """
4852
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4853
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4854
    return env, nl, nl
4855

    
4856
  def CheckPrereq(self):
4857
    """Check prerequisites.
4858

4859
    This checks that the instance is in the cluster and is not running.
4860

4861
    """
4862
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4863
    assert instance is not None, \
4864
      "Cannot retrieve locked instance %s" % self.op.instance_name
4865
    _CheckNodeOnline(self, instance.primary_node)
4866

    
4867
    if instance.disk_template == constants.DT_DISKLESS:
4868
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4869
                                 self.op.instance_name, errors.ECODE_INVAL)
4870
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4871

    
4872
    if not self.op.disks:
4873
      self.op.disks = range(len(instance.disks))
4874
    else:
4875
      for idx in self.op.disks:
4876
        if idx >= len(instance.disks):
4877
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4878
                                     errors.ECODE_INVAL)
4879

    
4880
    self.instance = instance
4881

    
4882
  def Exec(self, feedback_fn):
4883
    """Recreate the disks.
4884

4885
    """
4886
    to_skip = []
4887
    for idx, _ in enumerate(self.instance.disks):
4888
      if idx not in self.op.disks: # disk idx has not been passed in
4889
        to_skip.append(idx)
4890
        continue
4891

    
4892
    _CreateDisks(self, self.instance, to_skip=to_skip)
4893

    
4894

    
4895
class LURenameInstance(LogicalUnit):
4896
  """Rename an instance.
4897

4898
  """
4899
  HPATH = "instance-rename"
4900
  HTYPE = constants.HTYPE_INSTANCE
4901
  _OP_PARAMS = [
4902
    _PInstanceName,
4903
    ("new_name", _NoDefault, _TNonEmptyString),
4904
    ("ip_check", False, _TBool),
4905
    ("name_check", True, _TBool),
4906
    ]
4907

    
4908
  def CheckArguments(self):
4909
    """Check arguments.
4910

4911
    """
4912
    if self.op.ip_check and not self.op.name_check:
4913
      # TODO: make the ip check more flexible and not depend on the name check
4914
      raise errors.OpPrereqError("Cannot do ip check without a name check",
4915
                                 errors.ECODE_INVAL)
4916

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

4920
    This runs on master, primary and secondary nodes of the instance.
4921

4922
    """
4923
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4924
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4925
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4926
    return env, nl, nl
4927

    
4928
  def CheckPrereq(self):
4929
    """Check prerequisites.
4930

4931
    This checks that the instance is in the cluster and is not running.
4932

4933
    """
4934
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4935
                                                self.op.instance_name)
4936
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4937
    assert instance is not None
4938
    _CheckNodeOnline(self, instance.primary_node)
4939
    _CheckInstanceDown(self, instance, "cannot rename")
4940
    self.instance = instance
4941

    
4942
    new_name = self.op.new_name
4943
    if self.op.name_check:
4944
      hostinfo = netutils.HostInfo(netutils.HostInfo.NormalizeName(new_name))
4945
      new_name = hostinfo.name
4946
      if (self.op.ip_check and
4947
          netutils.TcpPing(hostinfo.ip, constants.DEFAULT_NODED_PORT)):
4948
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4949
                                   (hostinfo.ip, new_name),
4950
                                   errors.ECODE_NOTUNIQUE)
4951

    
4952
    instance_list = self.cfg.GetInstanceList()
4953
    if new_name in instance_list:
4954
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4955
                                 new_name, errors.ECODE_EXISTS)
4956

    
4957

    
4958
  def Exec(self, feedback_fn):
4959
    """Reinstall the instance.
4960

4961
    """
4962
    inst = self.instance
4963
    old_name = inst.name
4964

    
4965
    if inst.disk_template == constants.DT_FILE:
4966
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4967

    
4968
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4969
    # Change the instance lock. This is definitely safe while we hold the BGL
4970
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4971
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4972

    
4973
    # re-read the instance from the configuration after rename
4974
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4975

    
4976
    if inst.disk_template == constants.DT_FILE:
4977
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4978
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4979
                                                     old_file_storage_dir,
4980
                                                     new_file_storage_dir)
4981
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4982
                   " (but the instance has been renamed in Ganeti)" %
4983
                   (inst.primary_node, old_file_storage_dir,
4984
                    new_file_storage_dir))
4985

    
4986
    _StartInstanceDisks(self, inst, None)
4987
    try:
4988
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4989
                                                 old_name, self.op.debug_level)
4990
      msg = result.fail_msg
4991
      if msg:
4992
        msg = ("Could not run OS rename script for instance %s on node %s"
4993
               " (but the instance has been renamed in Ganeti): %s" %
4994
               (inst.name, inst.primary_node, msg))
4995
        self.proc.LogWarning(msg)
4996
    finally:
4997
      _ShutdownInstanceDisks(self, inst)
4998

    
4999
    return inst.name
5000

    
5001

    
5002
class LURemoveInstance(LogicalUnit):
5003
  """Remove an instance.
5004

5005
  """
5006
  HPATH = "instance-remove"
5007
  HTYPE = constants.HTYPE_INSTANCE
5008
  _OP_PARAMS = [
5009
    _PInstanceName,
5010
    ("ignore_failures", False, _TBool),
5011
    _PShutdownTimeout,
5012
    ]
5013
  REQ_BGL = False
5014

    
5015
  def ExpandNames(self):
5016
    self._ExpandAndLockInstance()
5017
    self.needed_locks[locking.LEVEL_NODE] = []
5018
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5019

    
5020
  def DeclareLocks(self, level):
5021
    if level == locking.LEVEL_NODE:
5022
      self._LockInstancesNodes()
5023

    
5024
  def BuildHooksEnv(self):
5025
    """Build hooks env.
5026

5027
    This runs on master, primary and secondary nodes of the instance.
5028

5029
    """
5030
    env = _BuildInstanceHookEnvByObject(self, self.instance)
5031
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
5032
    nl = [self.cfg.GetMasterNode()]
5033
    nl_post = list(self.instance.all_nodes) + nl
5034
    return env, nl, nl_post
5035

    
5036
  def CheckPrereq(self):
5037
    """Check prerequisites.
5038

5039
    This checks that the instance is in the cluster.
5040

5041
    """
5042
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5043
    assert self.instance is not None, \
5044
      "Cannot retrieve locked instance %s" % self.op.instance_name
5045

    
5046
  def Exec(self, feedback_fn):
5047
    """Remove the instance.
5048

5049
    """
5050
    instance = self.instance
5051
    logging.info("Shutting down instance %s on node %s",
5052
                 instance.name, instance.primary_node)
5053

    
5054
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
5055
                                             self.op.shutdown_timeout)
5056
    msg = result.fail_msg
5057
    if msg:
5058
      if self.op.ignore_failures:
5059
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
5060
      else:
5061
        raise errors.OpExecError("Could not shutdown instance %s on"
5062
                                 " node %s: %s" %
5063
                                 (instance.name, instance.primary_node, msg))
5064

    
5065
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
5066

    
5067

    
5068
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
5069
  """Utility function to remove an instance.
5070

5071
  """
5072
  logging.info("Removing block devices for instance %s", instance.name)
5073

    
5074
  if not _RemoveDisks(lu, instance):
5075
    if not ignore_failures:
5076
      raise errors.OpExecError("Can't remove instance's disks")
5077
    feedback_fn("Warning: can't remove instance's disks")
5078

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

    
5081
  lu.cfg.RemoveInstance(instance.name)
5082

    
5083
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
5084
    "Instance lock removal conflict"
5085

    
5086
  # Remove lock for the instance
5087
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
5088

    
5089

    
5090
class LUQueryInstances(NoHooksLU):
5091
  """Logical unit for querying instances.
5092

5093
  """
5094
  # pylint: disable-msg=W0142
5095
  _OP_PARAMS = [
5096
    ("output_fields", _NoDefault, _TListOf(_TNonEmptyString)),
5097
    ("names", _EmptyList, _TListOf(_TNonEmptyString)),
5098
    ("use_locking", False, _TBool),
5099
    ]
5100
  REQ_BGL = False
5101
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
5102
                    "serial_no", "ctime", "mtime", "uuid"]
5103
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
5104
                                    "admin_state",
5105
                                    "disk_template", "ip", "mac", "bridge",
5106
                                    "nic_mode", "nic_link",
5107
                                    "sda_size", "sdb_size", "vcpus", "tags",
5108
                                    "network_port", "beparams",
5109
                                    r"(disk)\.(size)/([0-9]+)",
5110
                                    r"(disk)\.(sizes)", "disk_usage",
5111
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
5112
                                    r"(nic)\.(bridge)/([0-9]+)",
5113
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
5114
                                    r"(disk|nic)\.(count)",
5115
                                    "hvparams",
5116
                                    ] + _SIMPLE_FIELDS +
5117
                                  ["hv/%s" % name
5118
                                   for name in constants.HVS_PARAMETERS
5119
                                   if name not in constants.HVC_GLOBALS] +
5120
                                  ["be/%s" % name
5121
                                   for name in constants.BES_PARAMETERS])
5122
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state",
5123
                                   "oper_ram",
5124
                                   "oper_vcpus",
5125
                                   "status")
5126

    
5127

    
5128
  def CheckArguments(self):
5129
    _CheckOutputFields(static=self._FIELDS_STATIC,
5130
                       dynamic=self._FIELDS_DYNAMIC,
5131
                       selected=self.op.output_fields)
5132

    
5133
  def ExpandNames(self):
5134
    self.needed_locks = {}
5135
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5136
    self.share_locks[locking.LEVEL_NODE] = 1
5137

    
5138
    if self.op.names:
5139
      self.wanted = _GetWantedInstances(self, self.op.names)
5140
    else:
5141
      self.wanted = locking.ALL_SET
5142

    
5143
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5144
    self.do_locking = self.do_node_query and self.op.use_locking
5145
    if self.do_locking:
5146
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5147
      self.needed_locks[locking.LEVEL_NODE] = []
5148
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5149

    
5150
  def DeclareLocks(self, level):
5151
    if level == locking.LEVEL_NODE and self.do_locking:
5152
      self._LockInstancesNodes()
5153

    
5154
  def Exec(self, feedback_fn):
5155
    """Computes the list of nodes and their attributes.
5156

5157
    """
5158
    # pylint: disable-msg=R0912
5159
    # way too many branches here
5160
    all_info = self.cfg.GetAllInstancesInfo()
5161
    if self.wanted == locking.ALL_SET:
5162
      # caller didn't specify instance names, so ordering is not important
5163
      if self.do_locking:
5164
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5165
      else:
5166
        instance_names = all_info.keys()
5167
      instance_names = utils.NiceSort(instance_names)
5168
    else:
5169
      # caller did specify names, so we must keep the ordering
5170
      if self.do_locking:
5171
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5172
      else:
5173
        tgt_set = all_info.keys()
5174
      missing = set(self.wanted).difference(tgt_set)
5175
      if missing:
5176
        raise errors.OpExecError("Some instances were removed before"
5177
                                 " retrieving their data: %s" % missing)
5178
      instance_names = self.wanted
5179

    
5180
    instance_list = [all_info[iname] for iname in instance_names]
5181

    
5182
    # begin data gathering
5183

    
5184
    nodes = frozenset([inst.primary_node for inst in instance_list])
5185
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5186

    
5187
    bad_nodes = []
5188
    off_nodes = []
5189
    if self.do_node_query:
5190
      live_data = {}
5191
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5192
      for name in nodes:
5193
        result = node_data[name]
5194
        if result.offline:
5195
          # offline nodes will be in both lists
5196
          off_nodes.append(name)
5197
        if result.fail_msg:
5198
          bad_nodes.append(name)
5199
        else:
5200
          if result.payload:
5201
            live_data.update(result.payload)
5202
          # else no instance is alive
5203
    else:
5204
      live_data = dict([(name, {}) for name in instance_names])
5205

    
5206
    # end data gathering
5207

    
5208
    HVPREFIX = "hv/"
5209
    BEPREFIX = "be/"
5210
    output = []
5211
    cluster = self.cfg.GetClusterInfo()
5212
    for instance in instance_list:
5213
      iout = []
5214
      i_hv = cluster.FillHV(instance, skip_globals=True)
5215
      i_be = cluster.FillBE(instance)
5216
      i_nicp = [cluster.SimpleFillNIC(nic.nicparams) for nic in instance.nics]
5217
      for field in self.op.output_fields:
5218
        st_match = self._FIELDS_STATIC.Matches(field)
5219
        if field in self._SIMPLE_FIELDS:
5220
          val = getattr(instance, field)
5221
        elif field == "pnode":
5222
          val = instance.primary_node
5223
        elif field == "snodes":
5224
          val = list(instance.secondary_nodes)
5225
        elif field == "admin_state":
5226
          val = instance.admin_up
5227
        elif field == "oper_state":
5228
          if instance.primary_node in bad_nodes:
5229
            val = None
5230
          else:
5231
            val = bool(live_data.get(instance.name))
5232
        elif field == "status":
5233
          if instance.primary_node in off_nodes:
5234
            val = "ERROR_nodeoffline"
5235
          elif instance.primary_node in bad_nodes:
5236
            val = "ERROR_nodedown"
5237
          else:
5238
            running = bool(live_data.get(instance.name))
5239
            if running:
5240
              if instance.admin_up:
5241
                val = "running"
5242
              else:
5243
                val = "ERROR_up"
5244
            else:
5245
              if instance.admin_up:
5246
                val = "ERROR_down"
5247
              else:
5248
                val = "ADMIN_down"
5249
        elif field == "oper_ram":
5250
          if instance.primary_node in bad_nodes:
5251
            val = None
5252
          elif instance.name in live_data:
5253
            val = live_data[instance.name].get("memory", "?")
5254
          else:
5255
            val = "-"
5256
        elif field == "oper_vcpus":
5257
          if instance.primary_node in bad_nodes:
5258
            val = None
5259
          elif instance.name in live_data:
5260
            val = live_data[instance.name].get("vcpus", "?")
5261
          else:
5262
            val = "-"
5263
        elif field == "vcpus":
5264
          val = i_be[constants.BE_VCPUS]
5265
        elif field == "disk_template":
5266
          val = instance.disk_template
5267
        elif field == "ip":
5268
          if instance.nics:
5269
            val = instance.nics[0].ip
5270
          else:
5271
            val = None
5272
        elif field == "nic_mode":
5273
          if instance.nics:
5274
            val = i_nicp[0][constants.NIC_MODE]
5275
          else:
5276
            val = None
5277
        elif field == "nic_link":
5278
          if instance.nics:
5279
            val = i_nicp[0][constants.NIC_LINK]
5280
          else:
5281
            val = None
5282
        elif field == "bridge":
5283
          if (instance.nics and
5284
              i_nicp[0][constants.NIC_MODE] == constants.NIC_MODE_BRIDGED):
5285
            val = i_nicp[0][constants.NIC_LINK]
5286
          else:
5287
            val = None
5288
        elif field == "mac":
5289
          if instance.nics:
5290
            val = instance.nics[0].mac
5291
          else:
5292
            val = None
5293
        elif field == "sda_size" or field == "sdb_size":
5294
          idx = ord(field[2]) - ord('a')
5295
          try:
5296
            val = instance.FindDisk(idx).size
5297
          except errors.OpPrereqError:
5298
            val = None
5299
        elif field == "disk_usage": # total disk usage per node
5300
          disk_sizes = [{'size': disk.size} for disk in instance.disks]
5301
          val = _ComputeDiskSize(instance.disk_template, disk_sizes)
5302
        elif field == "tags":
5303
          val = list(instance.GetTags())
5304
        elif field == "hvparams":
5305
          val = i_hv
5306
        elif (field.startswith(HVPREFIX) and
5307
              field[len(HVPREFIX):] in constants.HVS_PARAMETERS and
5308
              field[len(HVPREFIX):] not in constants.HVC_GLOBALS):
5309
          val = i_hv.get(field[len(HVPREFIX):], None)
5310
        elif field == "beparams":
5311
          val = i_be
5312
        elif (field.startswith(BEPREFIX) and
5313
              field[len(BEPREFIX):] in constants.BES_PARAMETERS):
5314
          val = i_be.get(field[len(BEPREFIX):], None)
5315
        elif st_match and st_match.groups():
5316
          # matches a variable list
5317
          st_groups = st_match.groups()
5318
          if st_groups and st_groups[0] == "disk":
5319
            if st_groups[1] == "count":
5320
              val = len(instance.disks)
5321
            elif st_groups[1] == "sizes":
5322
              val = [disk.size for disk in instance.disks]
5323
            elif st_groups[1] == "size":
5324
              try:
5325
                val = instance.FindDisk(st_groups[2]).size
5326
              except errors.OpPrereqError:
5327
                val = None
5328
            else:
5329
              assert False, "Unhandled disk parameter"
5330
          elif st_groups[0] == "nic":
5331
            if st_groups[1] == "count":
5332
              val = len(instance.nics)
5333
            elif st_groups[1] == "macs":
5334
              val = [nic.mac for nic in instance.nics]
5335
            elif st_groups[1] == "ips":
5336
              val = [nic.ip for nic in instance.nics]
5337
            elif st_groups[1] == "modes":
5338
              val = [nicp[constants.NIC_MODE] for nicp in i_nicp]
5339
            elif st_groups[1] == "links":
5340
              val = [nicp[constants.NIC_LINK] for nicp in i_nicp]
5341
            elif st_groups[1] == "bridges":
5342
              val = []
5343
              for nicp in i_nicp:
5344
                if nicp[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
5345
                  val.append(nicp[constants.NIC_LINK])
5346
                else:
5347
                  val.append(None)
5348
            else:
5349
              # index-based item
5350
              nic_idx = int(st_groups[2])
5351
              if nic_idx >= len(instance.nics):
5352
                val = None
5353
              else:
5354
                if st_groups[1] == "mac":
5355
                  val = instance.nics[nic_idx].mac
5356
                elif st_groups[1] == "ip":
5357
                  val = instance.nics[nic_idx].ip
5358
                elif st_groups[1] == "mode":
5359
                  val = i_nicp[nic_idx][constants.NIC_MODE]
5360
                elif st_groups[1] == "link":
5361
                  val = i_nicp[nic_idx][constants.NIC_LINK]
5362
                elif st_groups[1] == "bridge":
5363
                  nic_mode = i_nicp[nic_idx][constants.NIC_MODE]
5364
                  if nic_mode == constants.NIC_MODE_BRIDGED:
5365
                    val = i_nicp[nic_idx][constants.NIC_LINK]
5366
                  else:
5367
                    val = None
5368
                else:
5369
                  assert False, "Unhandled NIC parameter"
5370
          else:
5371
            assert False, ("Declared but unhandled variable parameter '%s'" %
5372
                           field)
5373
        else:
5374
          assert False, "Declared but unhandled parameter '%s'" % field
5375
        iout.append(val)
5376
      output.append(iout)
5377

    
5378
    return output
5379

    
5380

    
5381
class LUFailoverInstance(LogicalUnit):
5382
  """Failover an instance.
5383

5384
  """
5385
  HPATH = "instance-failover"
5386
  HTYPE = constants.HTYPE_INSTANCE
5387
  _OP_PARAMS = [
5388
    _PInstanceName,
5389
    ("ignore_consistency", False, _TBool),
5390
    _PShutdownTimeout,
5391
    ]
5392
  REQ_BGL = False
5393

    
5394
  def ExpandNames(self):
5395
    self._ExpandAndLockInstance()
5396
    self.needed_locks[locking.LEVEL_NODE] = []
5397
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5398

    
5399
  def DeclareLocks(self, level):
5400
    if level == locking.LEVEL_NODE:
5401
      self._LockInstancesNodes()
5402

    
5403
  def BuildHooksEnv(self):
5404
    """Build hooks env.
5405

5406
    This runs on master, primary and secondary nodes of the instance.
5407

5408
    """
5409
    instance = self.instance
5410
    source_node = instance.primary_node
5411
    target_node = instance.secondary_nodes[0]
5412
    env = {
5413
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5414
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5415
      "OLD_PRIMARY": source_node,
5416
      "OLD_SECONDARY": target_node,
5417
      "NEW_PRIMARY": target_node,
5418
      "NEW_SECONDARY": source_node,
5419
      }
5420
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5421
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5422
    nl_post = list(nl)
5423
    nl_post.append(source_node)
5424
    return env, nl, nl_post
5425

    
5426
  def CheckPrereq(self):
5427
    """Check prerequisites.
5428

5429
    This checks that the instance is in the cluster.
5430

5431
    """
5432
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5433
    assert self.instance is not None, \
5434
      "Cannot retrieve locked instance %s" % self.op.instance_name
5435

    
5436
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5437
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5438
      raise errors.OpPrereqError("Instance's disk layout is not"
5439
                                 " network mirrored, cannot failover.",
5440
                                 errors.ECODE_STATE)
5441

    
5442
    secondary_nodes = instance.secondary_nodes
5443
    if not secondary_nodes:
5444
      raise errors.ProgrammerError("no secondary node but using "
5445
                                   "a mirrored disk template")
5446

    
5447
    target_node = secondary_nodes[0]
5448
    _CheckNodeOnline(self, target_node)
5449
    _CheckNodeNotDrained(self, target_node)
5450
    if instance.admin_up:
5451
      # check memory requirements on the secondary node
5452
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5453
                           instance.name, bep[constants.BE_MEMORY],
5454
                           instance.hypervisor)
5455
    else:
5456
      self.LogInfo("Not checking memory on the secondary node as"
5457
                   " instance will not be started")
5458

    
5459
    # check bridge existance
5460
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5461

    
5462
  def Exec(self, feedback_fn):
5463
    """Failover an instance.
5464

5465
    The failover is done by shutting it down on its present node and
5466
    starting it on the secondary.
5467

5468
    """
5469
    instance = self.instance
5470

    
5471
    source_node = instance.primary_node
5472
    target_node = instance.secondary_nodes[0]
5473

    
5474
    if instance.admin_up:
5475
      feedback_fn("* checking disk consistency between source and target")
5476
      for dev in instance.disks:
5477
        # for drbd, these are drbd over lvm
5478
        if not _CheckDiskConsistency(self, dev, target_node, False):
5479
          if not self.op.ignore_consistency:
5480
            raise errors.OpExecError("Disk %s is degraded on target node,"
5481
                                     " aborting failover." % dev.iv_name)
5482
    else:
5483
      feedback_fn("* not checking disk consistency as instance is not running")
5484

    
5485
    feedback_fn("* shutting down instance on source node")
5486
    logging.info("Shutting down instance %s on node %s",
5487
                 instance.name, source_node)
5488

    
5489
    result = self.rpc.call_instance_shutdown(source_node, instance,
5490
                                             self.op.shutdown_timeout)
5491
    msg = result.fail_msg
5492
    if msg:
5493
      if self.op.ignore_consistency:
5494
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5495
                             " Proceeding anyway. Please make sure node"
5496
                             " %s is down. Error details: %s",
5497
                             instance.name, source_node, source_node, msg)
5498
      else:
5499
        raise errors.OpExecError("Could not shutdown instance %s on"
5500
                                 " node %s: %s" %
5501
                                 (instance.name, source_node, msg))
5502

    
5503
    feedback_fn("* deactivating the instance's disks on source node")
5504
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5505
      raise errors.OpExecError("Can't shut down the instance's disks.")
5506

    
5507
    instance.primary_node = target_node
5508
    # distribute new instance config to the other nodes
5509
    self.cfg.Update(instance, feedback_fn)
5510

    
5511
    # Only start the instance if it's marked as up
5512
    if instance.admin_up:
5513
      feedback_fn("* activating the instance's disks on target node")
5514
      logging.info("Starting instance %s on node %s",
5515
                   instance.name, target_node)
5516

    
5517
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5518
                                           ignore_secondaries=True)
5519
      if not disks_ok:
5520
        _ShutdownInstanceDisks(self, instance)
5521
        raise errors.OpExecError("Can't activate the instance's disks")
5522

    
5523
      feedback_fn("* starting the instance on the target node")
5524
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5525
      msg = result.fail_msg
5526
      if msg:
5527
        _ShutdownInstanceDisks(self, instance)
5528
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5529
                                 (instance.name, target_node, msg))
5530

    
5531

    
5532
class LUMigrateInstance(LogicalUnit):
5533
  """Migrate an instance.
5534

5535
  This is migration without shutting down, compared to the failover,
5536
  which is done with shutdown.
5537

5538
  """
5539
  HPATH = "instance-migrate"
5540
  HTYPE = constants.HTYPE_INSTANCE
5541
  _OP_PARAMS = [
5542
    _PInstanceName,
5543
    _PMigrationMode,
5544
    _PMigrationLive,
5545
    ("cleanup", False, _TBool),
5546
    ]
5547

    
5548
  REQ_BGL = False
5549

    
5550
  def ExpandNames(self):
5551
    self._ExpandAndLockInstance()
5552

    
5553
    self.needed_locks[locking.LEVEL_NODE] = []
5554
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5555

    
5556
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5557
                                       self.op.cleanup)
5558
    self.tasklets = [self._migrater]
5559

    
5560
  def DeclareLocks(self, level):
5561
    if level == locking.LEVEL_NODE:
5562
      self._LockInstancesNodes()
5563

    
5564
  def BuildHooksEnv(self):
5565
    """Build hooks env.
5566

5567
    This runs on master, primary and secondary nodes of the instance.
5568

5569
    """
5570
    instance = self._migrater.instance
5571
    source_node = instance.primary_node
5572
    target_node = instance.secondary_nodes[0]
5573
    env = _BuildInstanceHookEnvByObject(self, instance)
5574
    env["MIGRATE_LIVE"] = self._migrater.live
5575
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5576
    env.update({
5577
        "OLD_PRIMARY": source_node,
5578
        "OLD_SECONDARY": target_node,
5579
        "NEW_PRIMARY": target_node,
5580
        "NEW_SECONDARY": source_node,
5581
        })
5582
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5583
    nl_post = list(nl)
5584
    nl_post.append(source_node)
5585
    return env, nl, nl_post
5586

    
5587

    
5588
class LUMoveInstance(LogicalUnit):
5589
  """Move an instance by data-copying.
5590

5591
  """
5592
  HPATH = "instance-move"
5593
  HTYPE = constants.HTYPE_INSTANCE
5594
  _OP_PARAMS = [
5595
    _PInstanceName,
5596
    ("target_node", _NoDefault, _TNonEmptyString),
5597
    _PShutdownTimeout,
5598
    ]
5599
  REQ_BGL = False
5600

    
5601
  def ExpandNames(self):
5602
    self._ExpandAndLockInstance()
5603
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5604
    self.op.target_node = target_node
5605
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5606
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5607

    
5608
  def DeclareLocks(self, level):
5609
    if level == locking.LEVEL_NODE:
5610
      self._LockInstancesNodes(primary_only=True)
5611

    
5612
  def BuildHooksEnv(self):
5613
    """Build hooks env.
5614

5615
    This runs on master, primary and secondary nodes of the instance.
5616

5617
    """
5618
    env = {
5619
      "TARGET_NODE": self.op.target_node,
5620
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5621
      }
5622
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5623
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5624
                                       self.op.target_node]
5625
    return env, nl, nl
5626

    
5627
  def CheckPrereq(self):
5628
    """Check prerequisites.
5629

5630
    This checks that the instance is in the cluster.
5631

5632
    """
5633
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5634
    assert self.instance is not None, \
5635
      "Cannot retrieve locked instance %s" % self.op.instance_name
5636

    
5637
    node = self.cfg.GetNodeInfo(self.op.target_node)
5638
    assert node is not None, \
5639
      "Cannot retrieve locked node %s" % self.op.target_node
5640

    
5641
    self.target_node = target_node = node.name
5642

    
5643
    if target_node == instance.primary_node:
5644
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5645
                                 (instance.name, target_node),
5646
                                 errors.ECODE_STATE)
5647

    
5648
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5649

    
5650
    for idx, dsk in enumerate(instance.disks):
5651
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5652
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5653
                                   " cannot copy" % idx, errors.ECODE_STATE)
5654

    
5655
    _CheckNodeOnline(self, target_node)
5656
    _CheckNodeNotDrained(self, target_node)
5657

    
5658
    if instance.admin_up:
5659
      # check memory requirements on the secondary node
5660
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5661
                           instance.name, bep[constants.BE_MEMORY],
5662
                           instance.hypervisor)
5663
    else:
5664
      self.LogInfo("Not checking memory on the secondary node as"
5665
                   " instance will not be started")
5666

    
5667
    # check bridge existance
5668
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5669

    
5670
  def Exec(self, feedback_fn):
5671
    """Move an instance.
5672

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

5676
    """
5677
    instance = self.instance
5678

    
5679
    source_node = instance.primary_node
5680
    target_node = self.target_node
5681

    
5682
    self.LogInfo("Shutting down instance %s on source node %s",
5683
                 instance.name, source_node)
5684

    
5685
    result = self.rpc.call_instance_shutdown(source_node, instance,
5686
                                             self.op.shutdown_timeout)
5687
    msg = result.fail_msg
5688
    if msg:
5689
      if self.op.ignore_consistency:
5690
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5691
                             " Proceeding anyway. Please make sure node"
5692
                             " %s is down. Error details: %s",
5693
                             instance.name, source_node, source_node, msg)
5694
      else:
5695
        raise errors.OpExecError("Could not shutdown instance %s on"
5696
                                 " node %s: %s" %
5697
                                 (instance.name, source_node, msg))
5698

    
5699
    # create the target disks
5700
    try:
5701
      _CreateDisks(self, instance, target_node=target_node)
5702
    except errors.OpExecError:
5703
      self.LogWarning("Device creation failed, reverting...")
5704
      try:
5705
        _RemoveDisks(self, instance, target_node=target_node)
5706
      finally:
5707
        self.cfg.ReleaseDRBDMinors(instance.name)
5708
        raise
5709

    
5710
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5711

    
5712
    errs = []
5713
    # activate, get path, copy the data over
5714
    for idx, disk in enumerate(instance.disks):
5715
      self.LogInfo("Copying data for disk %d", idx)
5716
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5717
                                               instance.name, True)
5718
      if result.fail_msg:
5719
        self.LogWarning("Can't assemble newly created disk %d: %s",
5720
                        idx, result.fail_msg)
5721
        errs.append(result.fail_msg)
5722
        break
5723
      dev_path = result.payload
5724
      result = self.rpc.call_blockdev_export(source_node, disk,
5725
                                             target_node, dev_path,
5726
                                             cluster_name)
5727
      if result.fail_msg:
5728
        self.LogWarning("Can't copy data over for disk %d: %s",
5729
                        idx, result.fail_msg)
5730
        errs.append(result.fail_msg)
5731
        break
5732

    
5733
    if errs:
5734
      self.LogWarning("Some disks failed to copy, aborting")
5735
      try:
5736
        _RemoveDisks(self, instance, target_node=target_node)
5737
      finally:
5738
        self.cfg.ReleaseDRBDMinors(instance.name)
5739
        raise errors.OpExecError("Errors during disk copy: %s" %
5740
                                 (",".join(errs),))
5741

    
5742
    instance.primary_node = target_node
5743
    self.cfg.Update(instance, feedback_fn)
5744

    
5745
    self.LogInfo("Removing the disks on the original node")
5746
    _RemoveDisks(self, instance, target_node=source_node)
5747

    
5748
    # Only start the instance if it's marked as up
5749
    if instance.admin_up:
5750
      self.LogInfo("Starting instance %s on node %s",
5751
                   instance.name, target_node)
5752

    
5753
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5754
                                           ignore_secondaries=True)
5755
      if not disks_ok:
5756
        _ShutdownInstanceDisks(self, instance)
5757
        raise errors.OpExecError("Can't activate the instance's disks")
5758

    
5759
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5760
      msg = result.fail_msg
5761
      if msg:
5762
        _ShutdownInstanceDisks(self, instance)
5763
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5764
                                 (instance.name, target_node, msg))
5765

    
5766

    
5767
class LUMigrateNode(LogicalUnit):
5768
  """Migrate all instances from a node.
5769

5770
  """
5771
  HPATH = "node-migrate"
5772
  HTYPE = constants.HTYPE_NODE
5773
  _OP_PARAMS = [
5774
    _PNodeName,
5775
    _PMigrationMode,
5776
    _PMigrationLive,
5777
    ]
5778
  REQ_BGL = False
5779

    
5780
  def ExpandNames(self):
5781
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5782

    
5783
    self.needed_locks = {
5784
      locking.LEVEL_NODE: [self.op.node_name],
5785
      }
5786

    
5787
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5788

    
5789
    # Create tasklets for migrating instances for all instances on this node
5790
    names = []
5791
    tasklets = []
5792

    
5793
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5794
      logging.debug("Migrating instance %s", inst.name)
5795
      names.append(inst.name)
5796

    
5797
      tasklets.append(TLMigrateInstance(self, inst.name, False))
5798

    
5799
    self.tasklets = tasklets
5800

    
5801
    # Declare instance locks
5802
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5803

    
5804
  def DeclareLocks(self, level):
5805
    if level == locking.LEVEL_NODE:
5806
      self._LockInstancesNodes()
5807

    
5808
  def BuildHooksEnv(self):
5809
    """Build hooks env.
5810

5811
    This runs on the master, the primary and all the secondaries.
5812

5813
    """
5814
    env = {
5815
      "NODE_NAME": self.op.node_name,
5816
      }
5817

    
5818
    nl = [self.cfg.GetMasterNode()]
5819

    
5820
    return (env, nl, nl)
5821

    
5822

    
5823
class TLMigrateInstance(Tasklet):
5824
  """Tasklet class for instance migration.
5825

5826
  @type live: boolean
5827
  @ivar live: whether the migration will be done live or non-live;
5828
      this variable is initalized only after CheckPrereq has run
5829

5830
  """
5831
  def __init__(self, lu, instance_name, cleanup):
5832
    """Initializes this class.
5833

5834
    """
5835
    Tasklet.__init__(self, lu)
5836

    
5837
    # Parameters
5838
    self.instance_name = instance_name
5839
    self.cleanup = cleanup
5840
    self.live = False # will be overridden later
5841

    
5842
  def CheckPrereq(self):
5843
    """Check prerequisites.
5844

5845
    This checks that the instance is in the cluster.
5846

5847
    """
5848
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5849
    instance = self.cfg.GetInstanceInfo(instance_name)
5850
    assert instance is not None
5851

    
5852
    if instance.disk_template != constants.DT_DRBD8:
5853
      raise errors.OpPrereqError("Instance's disk layout is not"
5854
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5855

    
5856
    secondary_nodes = instance.secondary_nodes
5857
    if not secondary_nodes:
5858
      raise errors.ConfigurationError("No secondary node but using"
5859
                                      " drbd8 disk template")
5860

    
5861
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5862

    
5863
    target_node = secondary_nodes[0]
5864
    # check memory requirements on the secondary node
5865
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5866
                         instance.name, i_be[constants.BE_MEMORY],
5867
                         instance.hypervisor)
5868

    
5869
    # check bridge existance
5870
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5871

    
5872
    if not self.cleanup:
5873
      _CheckNodeNotDrained(self.lu, target_node)
5874
      result = self.rpc.call_instance_migratable(instance.primary_node,
5875
                                                 instance)
5876
      result.Raise("Can't migrate, please use failover",
5877
                   prereq=True, ecode=errors.ECODE_STATE)
5878

    
5879
    self.instance = instance
5880

    
5881
    if self.lu.op.live is not None and self.lu.op.mode is not None:
5882
      raise errors.OpPrereqError("Only one of the 'live' and 'mode'"
5883
                                 " parameters are accepted",
5884
                                 errors.ECODE_INVAL)
5885
    if self.lu.op.live is not None:
5886
      if self.lu.op.live:
5887
        self.lu.op.mode = constants.HT_MIGRATION_LIVE
5888
      else:
5889
        self.lu.op.mode = constants.HT_MIGRATION_NONLIVE
5890
      # reset the 'live' parameter to None so that repeated
5891
      # invocations of CheckPrereq do not raise an exception
5892
      self.lu.op.live = None
5893
    elif self.lu.op.mode is None:
5894
      # read the default value from the hypervisor
5895
      i_hv = self.cfg.GetClusterInfo().FillHV(instance, skip_globals=False)
5896
      self.lu.op.mode = i_hv[constants.HV_MIGRATION_MODE]
5897

    
5898
    self.live = self.lu.op.mode == constants.HT_MIGRATION_LIVE
5899

    
5900
  def _WaitUntilSync(self):
5901
    """Poll with custom rpc for disk sync.
5902

5903
    This uses our own step-based rpc call.
5904

5905
    """
5906
    self.feedback_fn("* wait until resync is done")
5907
    all_done = False
5908
    while not all_done:
5909
      all_done = True
5910
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5911
                                            self.nodes_ip,
5912
                                            self.instance.disks)
5913
      min_percent = 100
5914
      for node, nres in result.items():
5915
        nres.Raise("Cannot resync disks on node %s" % node)
5916
        node_done, node_percent = nres.payload
5917
        all_done = all_done and node_done
5918
        if node_percent is not None:
5919
          min_percent = min(min_percent, node_percent)
5920
      if not all_done:
5921
        if min_percent < 100:
5922
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5923
        time.sleep(2)
5924

    
5925
  def _EnsureSecondary(self, node):
5926
    """Demote a node to secondary.
5927

5928
    """
5929
    self.feedback_fn("* switching node %s to secondary mode" % node)
5930

    
5931
    for dev in self.instance.disks:
5932
      self.cfg.SetDiskID(dev, node)
5933

    
5934
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5935
                                          self.instance.disks)
5936
    result.Raise("Cannot change disk to secondary on node %s" % node)
5937

    
5938
  def _GoStandalone(self):
5939
    """Disconnect from the network.
5940

5941
    """
5942
    self.feedback_fn("* changing into standalone mode")
5943
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5944
                                               self.instance.disks)
5945
    for node, nres in result.items():
5946
      nres.Raise("Cannot disconnect disks node %s" % node)
5947

    
5948
  def _GoReconnect(self, multimaster):
5949
    """Reconnect to the network.
5950

5951
    """
5952
    if multimaster:
5953
      msg = "dual-master"
5954
    else:
5955
      msg = "single-master"
5956
    self.feedback_fn("* changing disks into %s mode" % msg)
5957
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5958
                                           self.instance.disks,
5959
                                           self.instance.name, multimaster)
5960
    for node, nres in result.items():
5961
      nres.Raise("Cannot change disks config on node %s" % node)
5962

    
5963
  def _ExecCleanup(self):
5964
    """Try to cleanup after a failed migration.
5965

5966
    The cleanup is done by:
5967
      - check that the instance is running only on one node
5968
        (and update the config if needed)
5969
      - change disks on its secondary node to secondary
5970
      - wait until disks are fully synchronized
5971
      - disconnect from the network
5972
      - change disks into single-master mode
5973
      - wait again until disks are fully synchronized
5974

5975
    """
5976
    instance = self.instance
5977
    target_node = self.target_node
5978
    source_node = self.source_node
5979

    
5980
    # check running on only one node
5981
    self.feedback_fn("* checking where the instance actually runs"
5982
                     " (if this hangs, the hypervisor might be in"
5983
                     " a bad state)")
5984
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5985
    for node, result in ins_l.items():
5986
      result.Raise("Can't contact node %s" % node)
5987

    
5988
    runningon_source = instance.name in ins_l[source_node].payload
5989
    runningon_target = instance.name in ins_l[target_node].payload
5990

    
5991
    if runningon_source and runningon_target:
5992
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5993
                               " or the hypervisor is confused. You will have"
5994
                               " to ensure manually that it runs only on one"
5995
                               " and restart this operation.")
5996

    
5997
    if not (runningon_source or runningon_target):
5998
      raise errors.OpExecError("Instance does not seem to be running at all."
5999
                               " In this case, it's safer to repair by"
6000
                               " running 'gnt-instance stop' to ensure disk"
6001
                               " shutdown, and then restarting it.")
6002

    
6003
    if runningon_target:
6004
      # the migration has actually succeeded, we need to update the config
6005
      self.feedback_fn("* instance running on secondary node (%s),"
6006
                       " updating config" % target_node)
6007
      instance.primary_node = target_node
6008
      self.cfg.Update(instance, self.feedback_fn)
6009
      demoted_node = source_node
6010
    else:
6011
      self.feedback_fn("* instance confirmed to be running on its"
6012
                       " primary node (%s)" % source_node)
6013
      demoted_node = target_node
6014

    
6015
    self._EnsureSecondary(demoted_node)
6016
    try:
6017
      self._WaitUntilSync()
6018
    except errors.OpExecError:
6019
      # we ignore here errors, since if the device is standalone, it
6020
      # won't be able to sync
6021
      pass
6022
    self._GoStandalone()
6023
    self._GoReconnect(False)
6024
    self._WaitUntilSync()
6025

    
6026
    self.feedback_fn("* done")
6027

    
6028
  def _RevertDiskStatus(self):
6029
    """Try to revert the disk status after a failed migration.
6030

6031
    """
6032
    target_node = self.target_node
6033
    try:
6034
      self._EnsureSecondary(target_node)
6035
      self._GoStandalone()
6036
      self._GoReconnect(False)
6037
      self._WaitUntilSync()
6038
    except errors.OpExecError, err:
6039
      self.lu.LogWarning("Migration failed and I can't reconnect the"
6040
                         " drives: error '%s'\n"
6041
                         "Please look and recover the instance status" %
6042
                         str(err))
6043

    
6044
  def _AbortMigration(self):
6045
    """Call the hypervisor code to abort a started migration.
6046

6047
    """
6048
    instance = self.instance
6049
    target_node = self.target_node
6050
    migration_info = self.migration_info
6051

    
6052
    abort_result = self.rpc.call_finalize_migration(target_node,
6053
                                                    instance,
6054
                                                    migration_info,
6055
                                                    False)
6056
    abort_msg = abort_result.fail_msg
6057
    if abort_msg:
6058
      logging.error("Aborting migration failed on target node %s: %s",
6059
                    target_node, abort_msg)
6060
      # Don't raise an exception here, as we stil have to try to revert the
6061
      # disk status, even if this step failed.
6062

    
6063
  def _ExecMigration(self):
6064
    """Migrate an instance.
6065

6066
    The migrate is done by:
6067
      - change the disks into dual-master mode
6068
      - wait until disks are fully synchronized again
6069
      - migrate the instance
6070
      - change disks on the new secondary node (the old primary) to secondary
6071
      - wait until disks are fully synchronized
6072
      - change disks into single-master mode
6073

6074
    """
6075
    instance = self.instance
6076
    target_node = self.target_node
6077
    source_node = self.source_node
6078

    
6079
    self.feedback_fn("* checking disk consistency between source and target")
6080
    for dev in instance.disks:
6081
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
6082
        raise errors.OpExecError("Disk %s is degraded or not fully"
6083
                                 " synchronized on target node,"
6084
                                 " aborting migrate." % dev.iv_name)
6085

    
6086
    # First get the migration information from the remote node
6087
    result = self.rpc.call_migration_info(source_node, instance)
6088
    msg = result.fail_msg
6089
    if msg:
6090
      log_err = ("Failed fetching source migration information from %s: %s" %
6091
                 (source_node, msg))
6092
      logging.error(log_err)
6093
      raise errors.OpExecError(log_err)
6094

    
6095
    self.migration_info = migration_info = result.payload
6096

    
6097
    # Then switch the disks to master/master mode
6098
    self._EnsureSecondary(target_node)
6099
    self._GoStandalone()
6100
    self._GoReconnect(True)
6101
    self._WaitUntilSync()
6102

    
6103
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
6104
    result = self.rpc.call_accept_instance(target_node,
6105
                                           instance,
6106
                                           migration_info,
6107
                                           self.nodes_ip[target_node])
6108

    
6109
    msg = result.fail_msg
6110
    if msg:
6111
      logging.error("Instance pre-migration failed, trying to revert"
6112
                    " disk status: %s", msg)
6113
      self.feedback_fn("Pre-migration failed, aborting")
6114
      self._AbortMigration()
6115
      self._RevertDiskStatus()
6116
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
6117
                               (instance.name, msg))
6118

    
6119
    self.feedback_fn("* migrating instance to %s" % target_node)
6120
    time.sleep(10)
6121
    result = self.rpc.call_instance_migrate(source_node, instance,
6122
                                            self.nodes_ip[target_node],
6123
                                            self.live)
6124
    msg = result.fail_msg
6125
    if msg:
6126
      logging.error("Instance migration failed, trying to revert"
6127
                    " disk status: %s", msg)
6128
      self.feedback_fn("Migration failed, aborting")
6129
      self._AbortMigration()
6130
      self._RevertDiskStatus()
6131
      raise errors.OpExecError("Could not migrate instance %s: %s" %
6132
                               (instance.name, msg))
6133
    time.sleep(10)
6134

    
6135
    instance.primary_node = target_node
6136
    # distribute new instance config to the other nodes
6137
    self.cfg.Update(instance, self.feedback_fn)
6138

    
6139
    result = self.rpc.call_finalize_migration(target_node,
6140
                                              instance,
6141
                                              migration_info,
6142
                                              True)
6143
    msg = result.fail_msg
6144
    if msg:
6145
      logging.error("Instance migration succeeded, but finalization failed:"
6146
                    " %s", msg)
6147
      raise errors.OpExecError("Could not finalize instance migration: %s" %
6148
                               msg)
6149

    
6150
    self._EnsureSecondary(source_node)
6151
    self._WaitUntilSync()
6152
    self._GoStandalone()
6153
    self._GoReconnect(False)
6154
    self._WaitUntilSync()
6155

    
6156
    self.feedback_fn("* done")
6157

    
6158
  def Exec(self, feedback_fn):
6159
    """Perform the migration.
6160

6161
    """
6162
    feedback_fn("Migrating instance %s" % self.instance.name)
6163

    
6164
    self.feedback_fn = feedback_fn
6165

    
6166
    self.source_node = self.instance.primary_node
6167
    self.target_node = self.instance.secondary_nodes[0]
6168
    self.all_nodes = [self.source_node, self.target_node]
6169
    self.nodes_ip = {
6170
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6171
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6172
      }
6173

    
6174
    if self.cleanup:
6175
      return self._ExecCleanup()
6176
    else:
6177
      return self._ExecMigration()
6178

    
6179

    
6180
def _CreateBlockDev(lu, node, instance, device, force_create,
6181
                    info, force_open):
6182
  """Create a tree of block devices on a given node.
6183

6184
  If this device type has to be created on secondaries, create it and
6185
  all its children.
6186

6187
  If not, just recurse to children keeping the same 'force' value.
6188

6189
  @param lu: the lu on whose behalf we execute
6190
  @param node: the node on which to create the device
6191
  @type instance: L{objects.Instance}
6192
  @param instance: the instance which owns the device
6193
  @type device: L{objects.Disk}
6194
  @param device: the device to create
6195
  @type force_create: boolean
6196
  @param force_create: whether to force creation of this device; this
6197
      will be change to True whenever we find a device which has
6198
      CreateOnSecondary() attribute
6199
  @param info: the extra 'metadata' we should attach to the device
6200
      (this will be represented as a LVM tag)
6201
  @type force_open: boolean
6202
  @param force_open: this parameter will be passes to the
6203
      L{backend.BlockdevCreate} function where it specifies
6204
      whether we run on primary or not, and it affects both
6205
      the child assembly and the device own Open() execution
6206

6207
  """
6208
  if device.CreateOnSecondary():
6209
    force_create = True
6210

    
6211
  if device.children:
6212
    for child in device.children:
6213
      _CreateBlockDev(lu, node, instance, child, force_create,
6214
                      info, force_open)
6215

    
6216
  if not force_create:
6217
    return
6218

    
6219
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6220

    
6221

    
6222
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6223
  """Create a single block device on a given node.
6224

6225
  This will not recurse over children of the device, so they must be
6226
  created in advance.
6227

6228
  @param lu: the lu on whose behalf we execute
6229
  @param node: the node on which to create the device
6230
  @type instance: L{objects.Instance}
6231
  @param instance: the instance which owns the device
6232
  @type device: L{objects.Disk}
6233
  @param device: the device to create
6234
  @param info: the extra 'metadata' we should attach to the device
6235
      (this will be represented as a LVM tag)
6236
  @type force_open: boolean
6237
  @param force_open: this parameter will be passes to the
6238
      L{backend.BlockdevCreate} function where it specifies
6239
      whether we run on primary or not, and it affects both
6240
      the child assembly and the device own Open() execution
6241

6242
  """
6243
  lu.cfg.SetDiskID(device, node)
6244
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6245
                                       instance.name, force_open, info)
6246
  result.Raise("Can't create block device %s on"
6247
               " node %s for instance %s" % (device, node, instance.name))
6248
  if device.physical_id is None:
6249
    device.physical_id = result.payload
6250

    
6251

    
6252
def _GenerateUniqueNames(lu, exts):
6253
  """Generate a suitable LV name.
6254

6255
  This will generate a logical volume name for the given instance.
6256

6257
  """
6258
  results = []
6259
  for val in exts:
6260
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6261
    results.append("%s%s" % (new_id, val))
6262
  return results
6263

    
6264

    
6265
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6266
                         p_minor, s_minor):
6267
  """Generate a drbd8 device complete with its children.
6268

6269
  """
6270
  port = lu.cfg.AllocatePort()
6271
  vgname = lu.cfg.GetVGName()
6272
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6273
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6274
                          logical_id=(vgname, names[0]))
6275
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6276
                          logical_id=(vgname, names[1]))
6277
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6278
                          logical_id=(primary, secondary, port,
6279
                                      p_minor, s_minor,
6280
                                      shared_secret),
6281
                          children=[dev_data, dev_meta],
6282
                          iv_name=iv_name)
6283
  return drbd_dev
6284

    
6285

    
6286
def _GenerateDiskTemplate(lu, template_name,
6287
                          instance_name, primary_node,
6288
                          secondary_nodes, disk_info,
6289
                          file_storage_dir, file_driver,
6290
                          base_index):
6291
  """Generate the entire disk layout for a given template type.
6292

6293
  """
6294
  #TODO: compute space requirements
6295

    
6296
  vgname = lu.cfg.GetVGName()
6297
  disk_count = len(disk_info)
6298
  disks = []
6299
  if template_name == constants.DT_DISKLESS:
6300
    pass
6301
  elif template_name == constants.DT_PLAIN:
6302
    if len(secondary_nodes) != 0:
6303
      raise errors.ProgrammerError("Wrong template configuration")
6304

    
6305
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6306
                                      for i in range(disk_count)])
6307
    for idx, disk in enumerate(disk_info):
6308
      disk_index = idx + base_index
6309
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6310
                              logical_id=(vgname, names[idx]),
6311
                              iv_name="disk/%d" % disk_index,
6312
                              mode=disk["mode"])
6313
      disks.append(disk_dev)
6314
  elif template_name == constants.DT_DRBD8:
6315
    if len(secondary_nodes) != 1:
6316
      raise errors.ProgrammerError("Wrong template configuration")
6317
    remote_node = secondary_nodes[0]
6318
    minors = lu.cfg.AllocateDRBDMinor(
6319
      [primary_node, remote_node] * len(disk_info), instance_name)
6320

    
6321
    names = []
6322
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6323
                                               for i in range(disk_count)]):
6324
      names.append(lv_prefix + "_data")
6325
      names.append(lv_prefix + "_meta")
6326
    for idx, disk in enumerate(disk_info):
6327
      disk_index = idx + base_index
6328
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6329
                                      disk["size"], names[idx*2:idx*2+2],
6330
                                      "disk/%d" % disk_index,
6331
                                      minors[idx*2], minors[idx*2+1])
6332
      disk_dev.mode = disk["mode"]
6333
      disks.append(disk_dev)
6334
  elif template_name == constants.DT_FILE:
6335
    if len(secondary_nodes) != 0:
6336
      raise errors.ProgrammerError("Wrong template configuration")
6337

    
6338
    _RequireFileStorage()
6339

    
6340
    for idx, disk in enumerate(disk_info):
6341
      disk_index = idx + base_index
6342
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6343
                              iv_name="disk/%d" % disk_index,
6344
                              logical_id=(file_driver,
6345
                                          "%s/disk%d" % (file_storage_dir,
6346
                                                         disk_index)),
6347
                              mode=disk["mode"])
6348
      disks.append(disk_dev)
6349
  else:
6350
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6351
  return disks
6352

    
6353

    
6354
def _GetInstanceInfoText(instance):
6355
  """Compute that text that should be added to the disk's metadata.
6356

6357
  """
6358
  return "originstname+%s" % instance.name
6359

    
6360

    
6361
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6362
  """Create all disks for an instance.
6363

6364
  This abstracts away some work from AddInstance.
6365

6366
  @type lu: L{LogicalUnit}
6367
  @param lu: the logical unit on whose behalf we execute
6368
  @type instance: L{objects.Instance}
6369
  @param instance: the instance whose disks we should create
6370
  @type to_skip: list
6371
  @param to_skip: list of indices to skip
6372
  @type target_node: string
6373
  @param target_node: if passed, overrides the target node for creation
6374
  @rtype: boolean
6375
  @return: the success of the creation
6376

6377
  """
6378
  info = _GetInstanceInfoText(instance)
6379
  if target_node is None:
6380
    pnode = instance.primary_node
6381
    all_nodes = instance.all_nodes
6382
  else:
6383
    pnode = target_node
6384
    all_nodes = [pnode]
6385

    
6386
  if instance.disk_template == constants.DT_FILE:
6387
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6388
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6389

    
6390
    result.Raise("Failed to create directory '%s' on"
6391
                 " node %s" % (file_storage_dir, pnode))
6392

    
6393
  # Note: this needs to be kept in sync with adding of disks in
6394
  # LUSetInstanceParams
6395
  for idx, device in enumerate(instance.disks):
6396
    if to_skip and idx in to_skip:
6397
      continue
6398
    logging.info("Creating volume %s for instance %s",
6399
                 device.iv_name, instance.name)
6400
    #HARDCODE
6401
    for node in all_nodes:
6402
      f_create = node == pnode
6403
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6404

    
6405

    
6406
def _RemoveDisks(lu, instance, target_node=None):
6407
  """Remove all disks for an instance.
6408

6409
  This abstracts away some work from `AddInstance()` and
6410
  `RemoveInstance()`. Note that in case some of the devices couldn't
6411
  be removed, the removal will continue with the other ones (compare
6412
  with `_CreateDisks()`).
6413

6414
  @type lu: L{LogicalUnit}
6415
  @param lu: the logical unit on whose behalf we execute
6416
  @type instance: L{objects.Instance}
6417
  @param instance: the instance whose disks we should remove
6418
  @type target_node: string
6419
  @param target_node: used to override the node on which to remove the disks
6420
  @rtype: boolean
6421
  @return: the success of the removal
6422

6423
  """
6424
  logging.info("Removing block devices for instance %s", instance.name)
6425

    
6426
  all_result = True
6427
  for device in instance.disks:
6428
    if target_node:
6429
      edata = [(target_node, device)]
6430
    else:
6431
      edata = device.ComputeNodeTree(instance.primary_node)
6432
    for node, disk in edata:
6433
      lu.cfg.SetDiskID(disk, node)
6434
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6435
      if msg:
6436
        lu.LogWarning("Could not remove block device %s on node %s,"
6437
                      " continuing anyway: %s", device.iv_name, node, msg)
6438
        all_result = False
6439

    
6440
  if instance.disk_template == constants.DT_FILE:
6441
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6442
    if target_node:
6443
      tgt = target_node
6444
    else:
6445
      tgt = instance.primary_node
6446
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6447
    if result.fail_msg:
6448
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6449
                    file_storage_dir, instance.primary_node, result.fail_msg)
6450
      all_result = False
6451

    
6452
  return all_result
6453

    
6454

    
6455
def _ComputeDiskSize(disk_template, disks):
6456
  """Compute disk size requirements in the volume group
6457

6458
  """
6459
  # Required free disk space as a function of disk and swap space
6460
  req_size_dict = {
6461
    constants.DT_DISKLESS: None,
6462
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6463
    # 128 MB are added for drbd metadata for each disk
6464
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6465
    constants.DT_FILE: None,
6466
  }
6467

    
6468
  if disk_template not in req_size_dict:
6469
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6470
                                 " is unknown" %  disk_template)
6471

    
6472
  return req_size_dict[disk_template]
6473

    
6474

    
6475
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6476
  """Hypervisor parameter validation.
6477

6478
  This function abstract the hypervisor parameter validation to be
6479
  used in both instance create and instance modify.
6480

6481
  @type lu: L{LogicalUnit}
6482
  @param lu: the logical unit for which we check
6483
  @type nodenames: list
6484
  @param nodenames: the list of nodes on which we should check
6485
  @type hvname: string
6486
  @param hvname: the name of the hypervisor we should use
6487
  @type hvparams: dict
6488
  @param hvparams: the parameters which we need to check
6489
  @raise errors.OpPrereqError: if the parameters are not valid
6490

6491
  """
6492
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6493
                                                  hvname,
6494
                                                  hvparams)
6495
  for node in nodenames:
6496
    info = hvinfo[node]
6497
    if info.offline:
6498
      continue
6499
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6500

    
6501

    
6502
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6503
  """OS parameters validation.
6504

6505
  @type lu: L{LogicalUnit}
6506
  @param lu: the logical unit for which we check
6507
  @type required: boolean
6508
  @param required: whether the validation should fail if the OS is not
6509
      found
6510
  @type nodenames: list
6511
  @param nodenames: the list of nodes on which we should check
6512
  @type osname: string
6513
  @param osname: the name of the hypervisor we should use
6514
  @type osparams: dict
6515
  @param osparams: the parameters which we need to check
6516
  @raise errors.OpPrereqError: if the parameters are not valid
6517

6518
  """
6519
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6520
                                   [constants.OS_VALIDATE_PARAMETERS],
6521
                                   osparams)
6522
  for node, nres in result.items():
6523
    # we don't check for offline cases since this should be run only
6524
    # against the master node and/or an instance's nodes
6525
    nres.Raise("OS Parameters validation failed on node %s" % node)
6526
    if not nres.payload:
6527
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6528
                 osname, node)
6529

    
6530

    
6531
class LUCreateInstance(LogicalUnit):
6532
  """Create an instance.
6533

6534
  """
6535
  HPATH = "instance-add"
6536
  HTYPE = constants.HTYPE_INSTANCE
6537
  _OP_PARAMS = [
6538
    _PInstanceName,
6539
    ("mode", _NoDefault, _TElemOf(constants.INSTANCE_CREATE_MODES)),
6540
    ("start", True, _TBool),
6541
    ("wait_for_sync", True, _TBool),
6542
    ("ip_check", True, _TBool),
6543
    ("name_check", True, _TBool),
6544
    ("disks", _NoDefault, _TListOf(_TDict)),
6545
    ("nics", _NoDefault, _TListOf(_TDict)),
6546
    ("hvparams", _EmptyDict, _TDict),
6547
    ("beparams", _EmptyDict, _TDict),
6548
    ("osparams", _EmptyDict, _TDict),
6549
    ("no_install", None, _TMaybeBool),
6550
    ("os_type", None, _TMaybeString),
6551
    ("force_variant", False, _TBool),
6552
    ("source_handshake", None, _TOr(_TList, _TNone)),
6553
    ("source_x509_ca", None, _TMaybeString),
6554
    ("source_instance_name", None, _TMaybeString),
6555
    ("src_node", None, _TMaybeString),
6556
    ("src_path", None, _TMaybeString),
6557
    ("pnode", None, _TMaybeString),
6558
    ("snode", None, _TMaybeString),
6559
    ("iallocator", None, _TMaybeString),
6560
    ("hypervisor", None, _TMaybeString),
6561
    ("disk_template", _NoDefault, _CheckDiskTemplate),
6562
    ("identify_defaults", False, _TBool),
6563
    ("file_driver", None, _TOr(_TNone, _TElemOf(constants.FILE_DRIVER))),
6564
    ("file_storage_dir", None, _TMaybeString),
6565
    ]
6566
  REQ_BGL = False
6567

    
6568
  def CheckArguments(self):
6569
    """Check arguments.
6570

6571
    """
6572
    # do not require name_check to ease forward/backward compatibility
6573
    # for tools
6574
    if self.op.no_install and self.op.start:
6575
      self.LogInfo("No-installation mode selected, disabling startup")
6576
      self.op.start = False
6577
    # validate/normalize the instance name
6578
    self.op.instance_name = \
6579
      netutils.HostInfo.NormalizeName(self.op.instance_name)
6580

    
6581
    if self.op.ip_check and not self.op.name_check:
6582
      # TODO: make the ip check more flexible and not depend on the name check
6583
      raise errors.OpPrereqError("Cannot do ip check without a name check",
6584
                                 errors.ECODE_INVAL)
6585

    
6586
    # check nics' parameter names
6587
    for nic in self.op.nics:
6588
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6589

    
6590
    # check disks. parameter names and consistent adopt/no-adopt strategy
6591
    has_adopt = has_no_adopt = False
6592
    for disk in self.op.disks:
6593
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6594
      if "adopt" in disk:
6595
        has_adopt = True
6596
      else:
6597
        has_no_adopt = True
6598
    if has_adopt and has_no_adopt:
6599
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6600
                                 errors.ECODE_INVAL)
6601
    if has_adopt:
6602
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6603
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6604
                                   " '%s' disk template" %
6605
                                   self.op.disk_template,
6606
                                   errors.ECODE_INVAL)
6607
      if self.op.iallocator is not None:
6608
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6609
                                   " iallocator script", errors.ECODE_INVAL)
6610
      if self.op.mode == constants.INSTANCE_IMPORT:
6611
        raise errors.OpPrereqError("Disk adoption not allowed for"
6612
                                   " instance import", errors.ECODE_INVAL)
6613

    
6614
    self.adopt_disks = has_adopt
6615

    
6616
    # instance name verification
6617
    if self.op.name_check:
6618
      self.hostname1 = netutils.GetHostInfo(self.op.instance_name)
6619
      self.op.instance_name = self.hostname1.name
6620
      # used in CheckPrereq for ip ping check
6621
      self.check_ip = self.hostname1.ip
6622
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6623
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6624
                                 errors.ECODE_INVAL)
6625
    else:
6626
      self.check_ip = None
6627

    
6628
    # file storage checks
6629
    if (self.op.file_driver and
6630
        not self.op.file_driver in constants.FILE_DRIVER):
6631
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6632
                                 self.op.file_driver, errors.ECODE_INVAL)
6633

    
6634
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6635
      raise errors.OpPrereqError("File storage directory path not absolute",
6636
                                 errors.ECODE_INVAL)
6637

    
6638
    ### Node/iallocator related checks
6639
    _CheckIAllocatorOrNode(self, "iallocator", "pnode")
6640

    
6641
    if self.op.pnode is not None:
6642
      if self.op.disk_template in constants.DTS_NET_MIRROR:
6643
        if self.op.snode is None:
6644
          raise errors.OpPrereqError("The networked disk templates need"
6645
                                     " a mirror node", errors.ECODE_INVAL)
6646
      elif self.op.snode:
6647
        self.LogWarning("Secondary node will be ignored on non-mirrored disk"
6648
                        " template")
6649
        self.op.snode = None
6650

    
6651
    self._cds = _GetClusterDomainSecret()
6652

    
6653
    if self.op.mode == constants.INSTANCE_IMPORT:
6654
      # On import force_variant must be True, because if we forced it at
6655
      # initial install, our only chance when importing it back is that it
6656
      # works again!
6657
      self.op.force_variant = True
6658

    
6659
      if self.op.no_install:
6660
        self.LogInfo("No-installation mode has no effect during import")
6661

    
6662
    elif self.op.mode == constants.INSTANCE_CREATE:
6663
      if self.op.os_type is None:
6664
        raise errors.OpPrereqError("No guest OS specified",
6665
                                   errors.ECODE_INVAL)
6666
      if self.op.os_type in self.cfg.GetClusterInfo().blacklisted_oss:
6667
        raise errors.OpPrereqError("Guest OS '%s' is not allowed for"
6668
                                   " installation" % self.op.os_type,
6669
                                   errors.ECODE_STATE)
6670
      if self.op.disk_template is None:
6671
        raise errors.OpPrereqError("No disk template specified",
6672
                                   errors.ECODE_INVAL)
6673

    
6674
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6675
      # Check handshake to ensure both clusters have the same domain secret
6676
      src_handshake = self.op.source_handshake
6677
      if not src_handshake:
6678
        raise errors.OpPrereqError("Missing source handshake",
6679
                                   errors.ECODE_INVAL)
6680

    
6681
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6682
                                                           src_handshake)
6683
      if errmsg:
6684
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6685
                                   errors.ECODE_INVAL)
6686

    
6687
      # Load and check source CA
6688
      self.source_x509_ca_pem = self.op.source_x509_ca
6689
      if not self.source_x509_ca_pem:
6690
        raise errors.OpPrereqError("Missing source X509 CA",
6691
                                   errors.ECODE_INVAL)
6692

    
6693
      try:
6694
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6695
                                                    self._cds)
6696
      except OpenSSL.crypto.Error, err:
6697
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6698
                                   (err, ), errors.ECODE_INVAL)
6699

    
6700
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6701
      if errcode is not None:
6702
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6703
                                   errors.ECODE_INVAL)
6704

    
6705
      self.source_x509_ca = cert
6706

    
6707
      src_instance_name = self.op.source_instance_name
6708
      if not src_instance_name:
6709
        raise errors.OpPrereqError("Missing source instance name",
6710
                                   errors.ECODE_INVAL)
6711

    
6712
      norm_name = netutils.HostInfo.NormalizeName(src_instance_name)
6713
      self.source_instance_name = netutils.GetHostInfo(norm_name).name
6714

    
6715
    else:
6716
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6717
                                 self.op.mode, errors.ECODE_INVAL)
6718

    
6719
  def ExpandNames(self):
6720
    """ExpandNames for CreateInstance.
6721

6722
    Figure out the right locks for instance creation.
6723

6724
    """
6725
    self.needed_locks = {}
6726

    
6727
    instance_name = self.op.instance_name
6728
    # this is just a preventive check, but someone might still add this
6729
    # instance in the meantime, and creation will fail at lock-add time
6730
    if instance_name in self.cfg.GetInstanceList():
6731
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6732
                                 instance_name, errors.ECODE_EXISTS)
6733

    
6734
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6735

    
6736
    if self.op.iallocator:
6737
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6738
    else:
6739
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6740
      nodelist = [self.op.pnode]
6741
      if self.op.snode is not None:
6742
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6743
        nodelist.append(self.op.snode)
6744
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6745

    
6746
    # in case of import lock the source node too
6747
    if self.op.mode == constants.INSTANCE_IMPORT:
6748
      src_node = self.op.src_node
6749
      src_path = self.op.src_path
6750

    
6751
      if src_path is None:
6752
        self.op.src_path = src_path = self.op.instance_name
6753

    
6754
      if src_node is None:
6755
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6756
        self.op.src_node = None
6757
        if os.path.isabs(src_path):
6758
          raise errors.OpPrereqError("Importing an instance from an absolute"
6759
                                     " path requires a source node option.",
6760
                                     errors.ECODE_INVAL)
6761
      else:
6762
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6763
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6764
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6765
        if not os.path.isabs(src_path):
6766
          self.op.src_path = src_path = \
6767
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6768

    
6769
  def _RunAllocator(self):
6770
    """Run the allocator based on input opcode.
6771

6772
    """
6773
    nics = [n.ToDict() for n in self.nics]
6774
    ial = IAllocator(self.cfg, self.rpc,
6775
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6776
                     name=self.op.instance_name,
6777
                     disk_template=self.op.disk_template,
6778
                     tags=[],
6779
                     os=self.op.os_type,
6780
                     vcpus=self.be_full[constants.BE_VCPUS],
6781
                     mem_size=self.be_full[constants.BE_MEMORY],
6782
                     disks=self.disks,
6783
                     nics=nics,
6784
                     hypervisor=self.op.hypervisor,
6785
                     )
6786

    
6787
    ial.Run(self.op.iallocator)
6788

    
6789
    if not ial.success:
6790
      raise errors.OpPrereqError("Can't compute nodes using"
6791
                                 " iallocator '%s': %s" %
6792
                                 (self.op.iallocator, ial.info),
6793
                                 errors.ECODE_NORES)
6794
    if len(ial.result) != ial.required_nodes:
6795
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6796
                                 " of nodes (%s), required %s" %
6797
                                 (self.op.iallocator, len(ial.result),
6798
                                  ial.required_nodes), errors.ECODE_FAULT)
6799
    self.op.pnode = ial.result[0]
6800
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6801
                 self.op.instance_name, self.op.iallocator,
6802
                 utils.CommaJoin(ial.result))
6803
    if ial.required_nodes == 2:
6804
      self.op.snode = ial.result[1]
6805

    
6806
  def BuildHooksEnv(self):
6807
    """Build hooks env.
6808

6809
    This runs on master, primary and secondary nodes of the instance.
6810

6811
    """
6812
    env = {
6813
      "ADD_MODE": self.op.mode,
6814
      }
6815
    if self.op.mode == constants.INSTANCE_IMPORT:
6816
      env["SRC_NODE"] = self.op.src_node
6817
      env["SRC_PATH"] = self.op.src_path
6818
      env["SRC_IMAGES"] = self.src_images
6819

    
6820
    env.update(_BuildInstanceHookEnv(
6821
      name=self.op.instance_name,
6822
      primary_node=self.op.pnode,
6823
      secondary_nodes=self.secondaries,
6824
      status=self.op.start,
6825
      os_type=self.op.os_type,
6826
      memory=self.be_full[constants.BE_MEMORY],
6827
      vcpus=self.be_full[constants.BE_VCPUS],
6828
      nics=_NICListToTuple(self, self.nics),
6829
      disk_template=self.op.disk_template,
6830
      disks=[(d["size"], d["mode"]) for d in self.disks],
6831
      bep=self.be_full,
6832
      hvp=self.hv_full,
6833
      hypervisor_name=self.op.hypervisor,
6834
    ))
6835

    
6836
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6837
          self.secondaries)
6838
    return env, nl, nl
6839

    
6840
  def _ReadExportInfo(self):
6841
    """Reads the export information from disk.
6842

6843
    It will override the opcode source node and path with the actual
6844
    information, if these two were not specified before.
6845

6846
    @return: the export information
6847

6848
    """
6849
    assert self.op.mode == constants.INSTANCE_IMPORT
6850

    
6851
    src_node = self.op.src_node
6852
    src_path = self.op.src_path
6853

    
6854
    if src_node is None:
6855
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6856
      exp_list = self.rpc.call_export_list(locked_nodes)
6857
      found = False
6858
      for node in exp_list:
6859
        if exp_list[node].fail_msg:
6860
          continue
6861
        if src_path in exp_list[node].payload:
6862
          found = True
6863
          self.op.src_node = src_node = node
6864
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6865
                                                       src_path)
6866
          break
6867
      if not found:
6868
        raise errors.OpPrereqError("No export found for relative path %s" %
6869
                                    src_path, errors.ECODE_INVAL)
6870

    
6871
    _CheckNodeOnline(self, src_node)
6872
    result = self.rpc.call_export_info(src_node, src_path)
6873
    result.Raise("No export or invalid export found in dir %s" % src_path)
6874

    
6875
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6876
    if not export_info.has_section(constants.INISECT_EXP):
6877
      raise errors.ProgrammerError("Corrupted export config",
6878
                                   errors.ECODE_ENVIRON)
6879

    
6880
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6881
    if (int(ei_version) != constants.EXPORT_VERSION):
6882
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6883
                                 (ei_version, constants.EXPORT_VERSION),
6884
                                 errors.ECODE_ENVIRON)
6885
    return export_info
6886

    
6887
  def _ReadExportParams(self, einfo):
6888
    """Use export parameters as defaults.
6889

6890
    In case the opcode doesn't specify (as in override) some instance
6891
    parameters, then try to use them from the export information, if
6892
    that declares them.
6893

6894
    """
6895
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6896

    
6897
    if self.op.disk_template is None:
6898
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6899
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6900
                                          "disk_template")
6901
      else:
6902
        raise errors.OpPrereqError("No disk template specified and the export"
6903
                                   " is missing the disk_template information",
6904
                                   errors.ECODE_INVAL)
6905

    
6906
    if not self.op.disks:
6907
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6908
        disks = []
6909
        # TODO: import the disk iv_name too
6910
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6911
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6912
          disks.append({"size": disk_sz})
6913
        self.op.disks = disks
6914
      else:
6915
        raise errors.OpPrereqError("No disk info specified and the export"
6916
                                   " is missing the disk information",
6917
                                   errors.ECODE_INVAL)
6918

    
6919
    if (not self.op.nics and
6920
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6921
      nics = []
6922
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6923
        ndict = {}
6924
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6925
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6926
          ndict[name] = v
6927
        nics.append(ndict)
6928
      self.op.nics = nics
6929

    
6930
    if (self.op.hypervisor is None and
6931
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6932
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6933
    if einfo.has_section(constants.INISECT_HYP):
6934
      # use the export parameters but do not override the ones
6935
      # specified by the user
6936
      for name, value in einfo.items(constants.INISECT_HYP):
6937
        if name not in self.op.hvparams:
6938
          self.op.hvparams[name] = value
6939

    
6940
    if einfo.has_section(constants.INISECT_BEP):
6941
      # use the parameters, without overriding
6942
      for name, value in einfo.items(constants.INISECT_BEP):
6943
        if name not in self.op.beparams:
6944
          self.op.beparams[name] = value
6945
    else:
6946
      # try to read the parameters old style, from the main section
6947
      for name in constants.BES_PARAMETERS:
6948
        if (name not in self.op.beparams and
6949
            einfo.has_option(constants.INISECT_INS, name)):
6950
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6951

    
6952
    if einfo.has_section(constants.INISECT_OSP):
6953
      # use the parameters, without overriding
6954
      for name, value in einfo.items(constants.INISECT_OSP):
6955
        if name not in self.op.osparams:
6956
          self.op.osparams[name] = value
6957

    
6958
  def _RevertToDefaults(self, cluster):
6959
    """Revert the instance parameters to the default values.
6960

6961
    """
6962
    # hvparams
6963
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6964
    for name in self.op.hvparams.keys():
6965
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6966
        del self.op.hvparams[name]
6967
    # beparams
6968
    be_defs = cluster.SimpleFillBE({})
6969
    for name in self.op.beparams.keys():
6970
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6971
        del self.op.beparams[name]
6972
    # nic params
6973
    nic_defs = cluster.SimpleFillNIC({})
6974
    for nic in self.op.nics:
6975
      for name in constants.NICS_PARAMETERS:
6976
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6977
          del nic[name]
6978
    # osparams
6979
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6980
    for name in self.op.osparams.keys():
6981
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6982
        del self.op.osparams[name]
6983

    
6984
  def CheckPrereq(self):
6985
    """Check prerequisites.
6986

6987
    """
6988
    if self.op.mode == constants.INSTANCE_IMPORT:
6989
      export_info = self._ReadExportInfo()
6990
      self._ReadExportParams(export_info)
6991

    
6992
    _CheckDiskTemplate(self.op.disk_template)
6993

    
6994
    if (not self.cfg.GetVGName() and
6995
        self.op.disk_template not in constants.DTS_NOT_LVM):
6996
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6997
                                 " instances", errors.ECODE_STATE)
6998

    
6999
    if self.op.hypervisor is None:
7000
      self.op.hypervisor = self.cfg.GetHypervisorType()
7001

    
7002
    cluster = self.cfg.GetClusterInfo()
7003
    enabled_hvs = cluster.enabled_hypervisors
7004
    if self.op.hypervisor not in enabled_hvs:
7005
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
7006
                                 " cluster (%s)" % (self.op.hypervisor,
7007
                                  ",".join(enabled_hvs)),
7008
                                 errors.ECODE_STATE)
7009

    
7010
    # check hypervisor parameter syntax (locally)
7011
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
7012
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
7013
                                      self.op.hvparams)
7014
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
7015
    hv_type.CheckParameterSyntax(filled_hvp)
7016
    self.hv_full = filled_hvp
7017
    # check that we don't specify global parameters on an instance
7018
    _CheckGlobalHvParams(self.op.hvparams)
7019

    
7020
    # fill and remember the beparams dict
7021
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
7022
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
7023

    
7024
    # build os parameters
7025
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
7026

    
7027
    # now that hvp/bep are in final format, let's reset to defaults,
7028
    # if told to do so
7029
    if self.op.identify_defaults:
7030
      self._RevertToDefaults(cluster)
7031

    
7032
    # NIC buildup
7033
    self.nics = []
7034
    for idx, nic in enumerate(self.op.nics):
7035
      nic_mode_req = nic.get("mode", None)
7036
      nic_mode = nic_mode_req
7037
      if nic_mode is None:
7038
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
7039

    
7040
      # in routed mode, for the first nic, the default ip is 'auto'
7041
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
7042
        default_ip_mode = constants.VALUE_AUTO
7043
      else:
7044
        default_ip_mode = constants.VALUE_NONE
7045

    
7046
      # ip validity checks
7047
      ip = nic.get("ip", default_ip_mode)
7048
      if ip is None or ip.lower() == constants.VALUE_NONE:
7049
        nic_ip = None
7050
      elif ip.lower() == constants.VALUE_AUTO:
7051
        if not self.op.name_check:
7052
          raise errors.OpPrereqError("IP address set to auto but name checks"
7053
                                     " have been skipped. Aborting.",
7054
                                     errors.ECODE_INVAL)
7055
        nic_ip = self.hostname1.ip
7056
      else:
7057
        if not netutils.IsValidIP4(ip):
7058
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
7059
                                     " like a valid IP" % ip,
7060
                                     errors.ECODE_INVAL)
7061
        nic_ip = ip
7062

    
7063
      # TODO: check the ip address for uniqueness
7064
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
7065
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
7066
                                   errors.ECODE_INVAL)
7067

    
7068
      # MAC address verification
7069
      mac = nic.get("mac", constants.VALUE_AUTO)
7070
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7071
        mac = utils.NormalizeAndValidateMac(mac)
7072

    
7073
        try:
7074
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
7075
        except errors.ReservationError:
7076
          raise errors.OpPrereqError("MAC address %s already in use"
7077
                                     " in cluster" % mac,
7078
                                     errors.ECODE_NOTUNIQUE)
7079

    
7080
      # bridge verification
7081
      bridge = nic.get("bridge", None)
7082
      link = nic.get("link", None)
7083
      if bridge and link:
7084
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
7085
                                   " at the same time", errors.ECODE_INVAL)
7086
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
7087
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
7088
                                   errors.ECODE_INVAL)
7089
      elif bridge:
7090
        link = bridge
7091

    
7092
      nicparams = {}
7093
      if nic_mode_req:
7094
        nicparams[constants.NIC_MODE] = nic_mode_req
7095
      if link:
7096
        nicparams[constants.NIC_LINK] = link
7097

    
7098
      check_params = cluster.SimpleFillNIC(nicparams)
7099
      objects.NIC.CheckParameterSyntax(check_params)
7100
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
7101

    
7102
    # disk checks/pre-build
7103
    self.disks = []
7104
    for disk in self.op.disks:
7105
      mode = disk.get("mode", constants.DISK_RDWR)
7106
      if mode not in constants.DISK_ACCESS_SET:
7107
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
7108
                                   mode, errors.ECODE_INVAL)
7109
      size = disk.get("size", None)
7110
      if size is None:
7111
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
7112
      try:
7113
        size = int(size)
7114
      except (TypeError, ValueError):
7115
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
7116
                                   errors.ECODE_INVAL)
7117
      new_disk = {"size": size, "mode": mode}
7118
      if "adopt" in disk:
7119
        new_disk["adopt"] = disk["adopt"]
7120
      self.disks.append(new_disk)
7121

    
7122
    if self.op.mode == constants.INSTANCE_IMPORT:
7123

    
7124
      # Check that the new instance doesn't have less disks than the export
7125
      instance_disks = len(self.disks)
7126
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
7127
      if instance_disks < export_disks:
7128
        raise errors.OpPrereqError("Not enough disks to import."
7129
                                   " (instance: %d, export: %d)" %
7130
                                   (instance_disks, export_disks),
7131
                                   errors.ECODE_INVAL)
7132

    
7133
      disk_images = []
7134
      for idx in range(export_disks):
7135
        option = 'disk%d_dump' % idx
7136
        if export_info.has_option(constants.INISECT_INS, option):
7137
          # FIXME: are the old os-es, disk sizes, etc. useful?
7138
          export_name = export_info.get(constants.INISECT_INS, option)
7139
          image = utils.PathJoin(self.op.src_path, export_name)
7140
          disk_images.append(image)
7141
        else:
7142
          disk_images.append(False)
7143

    
7144
      self.src_images = disk_images
7145

    
7146
      old_name = export_info.get(constants.INISECT_INS, 'name')
7147
      try:
7148
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
7149
      except (TypeError, ValueError), err:
7150
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
7151
                                   " an integer: %s" % str(err),
7152
                                   errors.ECODE_STATE)
7153
      if self.op.instance_name == old_name:
7154
        for idx, nic in enumerate(self.nics):
7155
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
7156
            nic_mac_ini = 'nic%d_mac' % idx
7157
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
7158

    
7159
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
7160

    
7161
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
7162
    if self.op.ip_check:
7163
      if netutils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
7164
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
7165
                                   (self.check_ip, self.op.instance_name),
7166
                                   errors.ECODE_NOTUNIQUE)
7167

    
7168
    #### mac address generation
7169
    # By generating here the mac address both the allocator and the hooks get
7170
    # the real final mac address rather than the 'auto' or 'generate' value.
7171
    # There is a race condition between the generation and the instance object
7172
    # creation, which means that we know the mac is valid now, but we're not
7173
    # sure it will be when we actually add the instance. If things go bad
7174
    # adding the instance will abort because of a duplicate mac, and the
7175
    # creation job will fail.
7176
    for nic in self.nics:
7177
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7178
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7179

    
7180
    #### allocator run
7181

    
7182
    if self.op.iallocator is not None:
7183
      self._RunAllocator()
7184

    
7185
    #### node related checks
7186

    
7187
    # check primary node
7188
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7189
    assert self.pnode is not None, \
7190
      "Cannot retrieve locked node %s" % self.op.pnode
7191
    if pnode.offline:
7192
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7193
                                 pnode.name, errors.ECODE_STATE)
7194
    if pnode.drained:
7195
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7196
                                 pnode.name, errors.ECODE_STATE)
7197

    
7198
    self.secondaries = []
7199

    
7200
    # mirror node verification
7201
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7202
      if self.op.snode == pnode.name:
7203
        raise errors.OpPrereqError("The secondary node cannot be the"
7204
                                   " primary node.", errors.ECODE_INVAL)
7205
      _CheckNodeOnline(self, self.op.snode)
7206
      _CheckNodeNotDrained(self, self.op.snode)
7207
      self.secondaries.append(self.op.snode)
7208

    
7209
    nodenames = [pnode.name] + self.secondaries
7210

    
7211
    req_size = _ComputeDiskSize(self.op.disk_template,
7212
                                self.disks)
7213

    
7214
    # Check lv size requirements, if not adopting
7215
    if req_size is not None and not self.adopt_disks:
7216
      _CheckNodesFreeDisk(self, nodenames, req_size)
7217

    
7218
    if self.adopt_disks: # instead, we must check the adoption data
7219
      all_lvs = set([i["adopt"] for i in self.disks])
7220
      if len(all_lvs) != len(self.disks):
7221
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7222
                                   errors.ECODE_INVAL)
7223
      for lv_name in all_lvs:
7224
        try:
7225
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7226
        except errors.ReservationError:
7227
          raise errors.OpPrereqError("LV named %s used by another instance" %
7228
                                     lv_name, errors.ECODE_NOTUNIQUE)
7229

    
7230
      node_lvs = self.rpc.call_lv_list([pnode.name],
7231
                                       self.cfg.GetVGName())[pnode.name]
7232
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7233
      node_lvs = node_lvs.payload
7234
      delta = all_lvs.difference(node_lvs.keys())
7235
      if delta:
7236
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7237
                                   utils.CommaJoin(delta),
7238
                                   errors.ECODE_INVAL)
7239
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7240
      if online_lvs:
7241
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7242
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7243
                                   errors.ECODE_STATE)
7244
      # update the size of disk based on what is found
7245
      for dsk in self.disks:
7246
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7247

    
7248
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7249

    
7250
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7251
    # check OS parameters (remotely)
7252
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7253

    
7254
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7255

    
7256
    # memory check on primary node
7257
    if self.op.start:
7258
      _CheckNodeFreeMemory(self, self.pnode.name,
7259
                           "creating instance %s" % self.op.instance_name,
7260
                           self.be_full[constants.BE_MEMORY],
7261
                           self.op.hypervisor)
7262

    
7263
    self.dry_run_result = list(nodenames)
7264

    
7265
  def Exec(self, feedback_fn):
7266
    """Create and add the instance to the cluster.
7267

7268
    """
7269
    instance = self.op.instance_name
7270
    pnode_name = self.pnode.name
7271

    
7272
    ht_kind = self.op.hypervisor
7273
    if ht_kind in constants.HTS_REQ_PORT:
7274
      network_port = self.cfg.AllocatePort()
7275
    else:
7276
      network_port = None
7277

    
7278
    if constants.ENABLE_FILE_STORAGE:
7279
      # this is needed because os.path.join does not accept None arguments
7280
      if self.op.file_storage_dir is None:
7281
        string_file_storage_dir = ""
7282
      else:
7283
        string_file_storage_dir = self.op.file_storage_dir
7284

    
7285
      # build the full file storage dir path
7286
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7287
                                        string_file_storage_dir, instance)
7288
    else:
7289
      file_storage_dir = ""
7290

    
7291
    disks = _GenerateDiskTemplate(self,
7292
                                  self.op.disk_template,
7293
                                  instance, pnode_name,
7294
                                  self.secondaries,
7295
                                  self.disks,
7296
                                  file_storage_dir,
7297
                                  self.op.file_driver,
7298
                                  0)
7299

    
7300
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7301
                            primary_node=pnode_name,
7302
                            nics=self.nics, disks=disks,
7303
                            disk_template=self.op.disk_template,
7304
                            admin_up=False,
7305
                            network_port=network_port,
7306
                            beparams=self.op.beparams,
7307
                            hvparams=self.op.hvparams,
7308
                            hypervisor=self.op.hypervisor,
7309
                            osparams=self.op.osparams,
7310
                            )
7311

    
7312
    if self.adopt_disks:
7313
      # rename LVs to the newly-generated names; we need to construct
7314
      # 'fake' LV disks with the old data, plus the new unique_id
7315
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7316
      rename_to = []
7317
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7318
        rename_to.append(t_dsk.logical_id)
7319
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7320
        self.cfg.SetDiskID(t_dsk, pnode_name)
7321
      result = self.rpc.call_blockdev_rename(pnode_name,
7322
                                             zip(tmp_disks, rename_to))
7323
      result.Raise("Failed to rename adoped LVs")
7324
    else:
7325
      feedback_fn("* creating instance disks...")
7326
      try:
7327
        _CreateDisks(self, iobj)
7328
      except errors.OpExecError:
7329
        self.LogWarning("Device creation failed, reverting...")
7330
        try:
7331
          _RemoveDisks(self, iobj)
7332
        finally:
7333
          self.cfg.ReleaseDRBDMinors(instance)
7334
          raise
7335

    
7336
    feedback_fn("adding instance %s to cluster config" % instance)
7337

    
7338
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7339

    
7340
    # Declare that we don't want to remove the instance lock anymore, as we've
7341
    # added the instance to the config
7342
    del self.remove_locks[locking.LEVEL_INSTANCE]
7343
    # Unlock all the nodes
7344
    if self.op.mode == constants.INSTANCE_IMPORT:
7345
      nodes_keep = [self.op.src_node]
7346
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7347
                       if node != self.op.src_node]
7348
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7349
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7350
    else:
7351
      self.context.glm.release(locking.LEVEL_NODE)
7352
      del self.acquired_locks[locking.LEVEL_NODE]
7353

    
7354
    if self.op.wait_for_sync:
7355
      disk_abort = not _WaitForSync(self, iobj)
7356
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7357
      # make sure the disks are not degraded (still sync-ing is ok)
7358
      time.sleep(15)
7359
      feedback_fn("* checking mirrors status")
7360
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7361
    else:
7362
      disk_abort = False
7363

    
7364
    if disk_abort:
7365
      _RemoveDisks(self, iobj)
7366
      self.cfg.RemoveInstance(iobj.name)
7367
      # Make sure the instance lock gets removed
7368
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7369
      raise errors.OpExecError("There are some degraded disks for"
7370
                               " this instance")
7371

    
7372
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7373
      if self.op.mode == constants.INSTANCE_CREATE:
7374
        if not self.op.no_install:
7375
          feedback_fn("* running the instance OS create scripts...")
7376
          # FIXME: pass debug option from opcode to backend
7377
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7378
                                                 self.op.debug_level)
7379
          result.Raise("Could not add os for instance %s"
7380
                       " on node %s" % (instance, pnode_name))
7381

    
7382
      elif self.op.mode == constants.INSTANCE_IMPORT:
7383
        feedback_fn("* running the instance OS import scripts...")
7384

    
7385
        transfers = []
7386

    
7387
        for idx, image in enumerate(self.src_images):
7388
          if not image:
7389
            continue
7390

    
7391
          # FIXME: pass debug option from opcode to backend
7392
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7393
                                             constants.IEIO_FILE, (image, ),
7394
                                             constants.IEIO_SCRIPT,
7395
                                             (iobj.disks[idx], idx),
7396
                                             None)
7397
          transfers.append(dt)
7398

    
7399
        import_result = \
7400
          masterd.instance.TransferInstanceData(self, feedback_fn,
7401
                                                self.op.src_node, pnode_name,
7402
                                                self.pnode.secondary_ip,
7403
                                                iobj, transfers)
7404
        if not compat.all(import_result):
7405
          self.LogWarning("Some disks for instance %s on node %s were not"
7406
                          " imported successfully" % (instance, pnode_name))
7407

    
7408
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7409
        feedback_fn("* preparing remote import...")
7410
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7411
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7412

    
7413
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7414
                                                     self.source_x509_ca,
7415
                                                     self._cds, timeouts)
7416
        if not compat.all(disk_results):
7417
          # TODO: Should the instance still be started, even if some disks
7418
          # failed to import (valid for local imports, too)?
7419
          self.LogWarning("Some disks for instance %s on node %s were not"
7420
                          " imported successfully" % (instance, pnode_name))
7421

    
7422
        # Run rename script on newly imported instance
7423
        assert iobj.name == instance
7424
        feedback_fn("Running rename script for %s" % instance)
7425
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7426
                                                   self.source_instance_name,
7427
                                                   self.op.debug_level)
7428
        if result.fail_msg:
7429
          self.LogWarning("Failed to run rename script for %s on node"
7430
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7431

    
7432
      else:
7433
        # also checked in the prereq part
7434
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7435
                                     % self.op.mode)
7436

    
7437
    if self.op.start:
7438
      iobj.admin_up = True
7439
      self.cfg.Update(iobj, feedback_fn)
7440
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7441
      feedback_fn("* starting instance...")
7442
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7443
      result.Raise("Could not start instance")
7444

    
7445
    return list(iobj.all_nodes)
7446

    
7447

    
7448
class LUConnectConsole(NoHooksLU):
7449
  """Connect to an instance's console.
7450

7451
  This is somewhat special in that it returns the command line that
7452
  you need to run on the master node in order to connect to the
7453
  console.
7454

7455
  """
7456
  _OP_PARAMS = [
7457
    _PInstanceName
7458
    ]
7459
  REQ_BGL = False
7460

    
7461
  def ExpandNames(self):
7462
    self._ExpandAndLockInstance()
7463

    
7464
  def CheckPrereq(self):
7465
    """Check prerequisites.
7466

7467
    This checks that the instance is in the cluster.
7468

7469
    """
7470
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7471
    assert self.instance is not None, \
7472
      "Cannot retrieve locked instance %s" % self.op.instance_name
7473
    _CheckNodeOnline(self, self.instance.primary_node)
7474

    
7475
  def Exec(self, feedback_fn):
7476
    """Connect to the console of an instance
7477

7478
    """
7479
    instance = self.instance
7480
    node = instance.primary_node
7481

    
7482
    node_insts = self.rpc.call_instance_list([node],
7483
                                             [instance.hypervisor])[node]
7484
    node_insts.Raise("Can't get node information from %s" % node)
7485

    
7486
    if instance.name not in node_insts.payload:
7487
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7488

    
7489
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7490

    
7491
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7492
    cluster = self.cfg.GetClusterInfo()
7493
    # beparams and hvparams are passed separately, to avoid editing the
7494
    # instance and then saving the defaults in the instance itself.
7495
    hvparams = cluster.FillHV(instance)
7496
    beparams = cluster.FillBE(instance)
7497
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7498

    
7499
    # build ssh cmdline
7500
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7501

    
7502

    
7503
class LUReplaceDisks(LogicalUnit):
7504
  """Replace the disks of an instance.
7505

7506
  """
7507
  HPATH = "mirrors-replace"
7508
  HTYPE = constants.HTYPE_INSTANCE
7509
  _OP_PARAMS = [
7510
    _PInstanceName,
7511
    ("mode", _NoDefault, _TElemOf(constants.REPLACE_MODES)),
7512
    ("disks", _EmptyList, _TListOf(_TPositiveInt)),
7513
    ("remote_node", None, _TMaybeString),
7514
    ("iallocator", None, _TMaybeString),
7515
    ("early_release", False, _TBool),
7516
    ]
7517
  REQ_BGL = False
7518

    
7519
  def CheckArguments(self):
7520
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7521
                                  self.op.iallocator)
7522

    
7523
  def ExpandNames(self):
7524
    self._ExpandAndLockInstance()
7525

    
7526
    if self.op.iallocator is not None:
7527
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7528

    
7529
    elif self.op.remote_node is not None:
7530
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7531
      self.op.remote_node = remote_node
7532

    
7533
      # Warning: do not remove the locking of the new secondary here
7534
      # unless DRBD8.AddChildren is changed to work in parallel;
7535
      # currently it doesn't since parallel invocations of
7536
      # FindUnusedMinor will conflict
7537
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7538
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7539

    
7540
    else:
7541
      self.needed_locks[locking.LEVEL_NODE] = []
7542
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7543

    
7544
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7545
                                   self.op.iallocator, self.op.remote_node,
7546
                                   self.op.disks, False, self.op.early_release)
7547

    
7548
    self.tasklets = [self.replacer]
7549

    
7550
  def DeclareLocks(self, level):
7551
    # If we're not already locking all nodes in the set we have to declare the
7552
    # instance's primary/secondary nodes.
7553
    if (level == locking.LEVEL_NODE and
7554
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7555
      self._LockInstancesNodes()
7556

    
7557
  def BuildHooksEnv(self):
7558
    """Build hooks env.
7559

7560
    This runs on the master, the primary and all the secondaries.
7561

7562
    """
7563
    instance = self.replacer.instance
7564
    env = {
7565
      "MODE": self.op.mode,
7566
      "NEW_SECONDARY": self.op.remote_node,
7567
      "OLD_SECONDARY": instance.secondary_nodes[0],
7568
      }
7569
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7570
    nl = [
7571
      self.cfg.GetMasterNode(),
7572
      instance.primary_node,
7573
      ]
7574
    if self.op.remote_node is not None:
7575
      nl.append(self.op.remote_node)
7576
    return env, nl, nl
7577

    
7578

    
7579
class TLReplaceDisks(Tasklet):
7580
  """Replaces disks for an instance.
7581

7582
  Note: Locking is not within the scope of this class.
7583

7584
  """
7585
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7586
               disks, delay_iallocator, early_release):
7587
    """Initializes this class.
7588

7589
    """
7590
    Tasklet.__init__(self, lu)
7591

    
7592
    # Parameters
7593
    self.instance_name = instance_name
7594
    self.mode = mode
7595
    self.iallocator_name = iallocator_name
7596
    self.remote_node = remote_node
7597
    self.disks = disks
7598
    self.delay_iallocator = delay_iallocator
7599
    self.early_release = early_release
7600

    
7601
    # Runtime data
7602
    self.instance = None
7603
    self.new_node = None
7604
    self.target_node = None
7605
    self.other_node = None
7606
    self.remote_node_info = None
7607
    self.node_secondary_ip = None
7608

    
7609
  @staticmethod
7610
  def CheckArguments(mode, remote_node, iallocator):
7611
    """Helper function for users of this class.
7612

7613
    """
7614
    # check for valid parameter combination
7615
    if mode == constants.REPLACE_DISK_CHG:
7616
      if remote_node is None and iallocator is None:
7617
        raise errors.OpPrereqError("When changing the secondary either an"
7618
                                   " iallocator script must be used or the"
7619
                                   " new node given", errors.ECODE_INVAL)
7620

    
7621
      if remote_node is not None and iallocator is not None:
7622
        raise errors.OpPrereqError("Give either the iallocator or the new"
7623
                                   " secondary, not both", errors.ECODE_INVAL)
7624

    
7625
    elif remote_node is not None or iallocator is not None:
7626
      # Not replacing the secondary
7627
      raise errors.OpPrereqError("The iallocator and new node options can"
7628
                                 " only be used when changing the"
7629
                                 " secondary node", errors.ECODE_INVAL)
7630

    
7631
  @staticmethod
7632
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7633
    """Compute a new secondary node using an IAllocator.
7634

7635
    """
7636
    ial = IAllocator(lu.cfg, lu.rpc,
7637
                     mode=constants.IALLOCATOR_MODE_RELOC,
7638
                     name=instance_name,
7639
                     relocate_from=relocate_from)
7640

    
7641
    ial.Run(iallocator_name)
7642

    
7643
    if not ial.success:
7644
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7645
                                 " %s" % (iallocator_name, ial.info),
7646
                                 errors.ECODE_NORES)
7647

    
7648
    if len(ial.result) != ial.required_nodes:
7649
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7650
                                 " of nodes (%s), required %s" %
7651
                                 (iallocator_name,
7652
                                  len(ial.result), ial.required_nodes),
7653
                                 errors.ECODE_FAULT)
7654

    
7655
    remote_node_name = ial.result[0]
7656

    
7657
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7658
               instance_name, remote_node_name)
7659

    
7660
    return remote_node_name
7661

    
7662
  def _FindFaultyDisks(self, node_name):
7663
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7664
                                    node_name, True)
7665

    
7666
  def CheckPrereq(self):
7667
    """Check prerequisites.
7668

7669
    This checks that the instance is in the cluster.
7670

7671
    """
7672
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7673
    assert instance is not None, \
7674
      "Cannot retrieve locked instance %s" % self.instance_name
7675

    
7676
    if instance.disk_template != constants.DT_DRBD8:
7677
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7678
                                 " instances", errors.ECODE_INVAL)
7679

    
7680
    if len(instance.secondary_nodes) != 1:
7681
      raise errors.OpPrereqError("The instance has a strange layout,"
7682
                                 " expected one secondary but found %d" %
7683
                                 len(instance.secondary_nodes),
7684
                                 errors.ECODE_FAULT)
7685

    
7686
    if not self.delay_iallocator:
7687
      self._CheckPrereq2()
7688

    
7689
  def _CheckPrereq2(self):
7690
    """Check prerequisites, second part.
7691

7692
    This function should always be part of CheckPrereq. It was separated and is
7693
    now called from Exec because during node evacuation iallocator was only
7694
    called with an unmodified cluster model, not taking planned changes into
7695
    account.
7696

7697
    """
7698
    instance = self.instance
7699
    secondary_node = instance.secondary_nodes[0]
7700

    
7701
    if self.iallocator_name is None:
7702
      remote_node = self.remote_node
7703
    else:
7704
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7705
                                       instance.name, instance.secondary_nodes)
7706

    
7707
    if remote_node is not None:
7708
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7709
      assert self.remote_node_info is not None, \
7710
        "Cannot retrieve locked node %s" % remote_node
7711
    else:
7712
      self.remote_node_info = None
7713

    
7714
    if remote_node == self.instance.primary_node:
7715
      raise errors.OpPrereqError("The specified node is the primary node of"
7716
                                 " the instance.", errors.ECODE_INVAL)
7717

    
7718
    if remote_node == secondary_node:
7719
      raise errors.OpPrereqError("The specified node is already the"
7720
                                 " secondary node of the instance.",
7721
                                 errors.ECODE_INVAL)
7722

    
7723
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7724
                                    constants.REPLACE_DISK_CHG):
7725
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7726
                                 errors.ECODE_INVAL)
7727

    
7728
    if self.mode == constants.REPLACE_DISK_AUTO:
7729
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7730
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7731

    
7732
      if faulty_primary and faulty_secondary:
7733
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7734
                                   " one node and can not be repaired"
7735
                                   " automatically" % self.instance_name,
7736
                                   errors.ECODE_STATE)
7737

    
7738
      if faulty_primary:
7739
        self.disks = faulty_primary
7740
        self.target_node = instance.primary_node
7741
        self.other_node = secondary_node
7742
        check_nodes = [self.target_node, self.other_node]
7743
      elif faulty_secondary:
7744
        self.disks = faulty_secondary
7745
        self.target_node = secondary_node
7746
        self.other_node = instance.primary_node
7747
        check_nodes = [self.target_node, self.other_node]
7748
      else:
7749
        self.disks = []
7750
        check_nodes = []
7751

    
7752
    else:
7753
      # Non-automatic modes
7754
      if self.mode == constants.REPLACE_DISK_PRI:
7755
        self.target_node = instance.primary_node
7756
        self.other_node = secondary_node
7757
        check_nodes = [self.target_node, self.other_node]
7758

    
7759
      elif self.mode == constants.REPLACE_DISK_SEC:
7760
        self.target_node = secondary_node
7761
        self.other_node = instance.primary_node
7762
        check_nodes = [self.target_node, self.other_node]
7763

    
7764
      elif self.mode == constants.REPLACE_DISK_CHG:
7765
        self.new_node = remote_node
7766
        self.other_node = instance.primary_node
7767
        self.target_node = secondary_node
7768
        check_nodes = [self.new_node, self.other_node]
7769

    
7770
        _CheckNodeNotDrained(self.lu, remote_node)
7771

    
7772
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7773
        assert old_node_info is not None
7774
        if old_node_info.offline and not self.early_release:
7775
          # doesn't make sense to delay the release
7776
          self.early_release = True
7777
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7778
                          " early-release mode", secondary_node)
7779

    
7780
      else:
7781
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7782
                                     self.mode)
7783

    
7784
      # If not specified all disks should be replaced
7785
      if not self.disks:
7786
        self.disks = range(len(self.instance.disks))
7787

    
7788
    for node in check_nodes:
7789
      _CheckNodeOnline(self.lu, node)
7790

    
7791
    # Check whether disks are valid
7792
    for disk_idx in self.disks:
7793
      instance.FindDisk(disk_idx)
7794

    
7795
    # Get secondary node IP addresses
7796
    node_2nd_ip = {}
7797

    
7798
    for node_name in [self.target_node, self.other_node, self.new_node]:
7799
      if node_name is not None:
7800
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7801

    
7802
    self.node_secondary_ip = node_2nd_ip
7803

    
7804
  def Exec(self, feedback_fn):
7805
    """Execute disk replacement.
7806

7807
    This dispatches the disk replacement to the appropriate handler.
7808

7809
    """
7810
    if self.delay_iallocator:
7811
      self._CheckPrereq2()
7812

    
7813
    if not self.disks:
7814
      feedback_fn("No disks need replacement")
7815
      return
7816

    
7817
    feedback_fn("Replacing disk(s) %s for %s" %
7818
                (utils.CommaJoin(self.disks), self.instance.name))
7819

    
7820
    activate_disks = (not self.instance.admin_up)
7821

    
7822
    # Activate the instance disks if we're replacing them on a down instance
7823
    if activate_disks:
7824
      _StartInstanceDisks(self.lu, self.instance, True)
7825

    
7826
    try:
7827
      # Should we replace the secondary node?
7828
      if self.new_node is not None:
7829
        fn = self._ExecDrbd8Secondary
7830
      else:
7831
        fn = self._ExecDrbd8DiskOnly
7832

    
7833
      return fn(feedback_fn)
7834

    
7835
    finally:
7836
      # Deactivate the instance disks if we're replacing them on a
7837
      # down instance
7838
      if activate_disks:
7839
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7840

    
7841
  def _CheckVolumeGroup(self, nodes):
7842
    self.lu.LogInfo("Checking volume groups")
7843

    
7844
    vgname = self.cfg.GetVGName()
7845

    
7846
    # Make sure volume group exists on all involved nodes
7847
    results = self.rpc.call_vg_list(nodes)
7848
    if not results:
7849
      raise errors.OpExecError("Can't list volume groups on the nodes")
7850

    
7851
    for node in nodes:
7852
      res = results[node]
7853
      res.Raise("Error checking node %s" % node)
7854
      if vgname not in res.payload:
7855
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7856
                                 (vgname, node))
7857

    
7858
  def _CheckDisksExistence(self, nodes):
7859
    # Check disk existence
7860
    for idx, dev in enumerate(self.instance.disks):
7861
      if idx not in self.disks:
7862
        continue
7863

    
7864
      for node in nodes:
7865
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7866
        self.cfg.SetDiskID(dev, node)
7867

    
7868
        result = self.rpc.call_blockdev_find(node, dev)
7869

    
7870
        msg = result.fail_msg
7871
        if msg or not result.payload:
7872
          if not msg:
7873
            msg = "disk not found"
7874
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7875
                                   (idx, node, msg))
7876

    
7877
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7878
    for idx, dev in enumerate(self.instance.disks):
7879
      if idx not in self.disks:
7880
        continue
7881

    
7882
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7883
                      (idx, node_name))
7884

    
7885
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7886
                                   ldisk=ldisk):
7887
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7888
                                 " replace disks for instance %s" %
7889
                                 (node_name, self.instance.name))
7890

    
7891
  def _CreateNewStorage(self, node_name):
7892
    vgname = self.cfg.GetVGName()
7893
    iv_names = {}
7894

    
7895
    for idx, dev in enumerate(self.instance.disks):
7896
      if idx not in self.disks:
7897
        continue
7898

    
7899
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7900

    
7901
      self.cfg.SetDiskID(dev, node_name)
7902

    
7903
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7904
      names = _GenerateUniqueNames(self.lu, lv_names)
7905

    
7906
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7907
                             logical_id=(vgname, names[0]))
7908
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7909
                             logical_id=(vgname, names[1]))
7910

    
7911
      new_lvs = [lv_data, lv_meta]
7912
      old_lvs = dev.children
7913
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7914

    
7915
      # we pass force_create=True to force the LVM creation
7916
      for new_lv in new_lvs:
7917
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7918
                        _GetInstanceInfoText(self.instance), False)
7919

    
7920
    return iv_names
7921

    
7922
  def _CheckDevices(self, node_name, iv_names):
7923
    for name, (dev, _, _) in iv_names.iteritems():
7924
      self.cfg.SetDiskID(dev, node_name)
7925

    
7926
      result = self.rpc.call_blockdev_find(node_name, dev)
7927

    
7928
      msg = result.fail_msg
7929
      if msg or not result.payload:
7930
        if not msg:
7931
          msg = "disk not found"
7932
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7933
                                 (name, msg))
7934

    
7935
      if result.payload.is_degraded:
7936
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7937

    
7938
  def _RemoveOldStorage(self, node_name, iv_names):
7939
    for name, (_, old_lvs, _) in iv_names.iteritems():
7940
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7941

    
7942
      for lv in old_lvs:
7943
        self.cfg.SetDiskID(lv, node_name)
7944

    
7945
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7946
        if msg:
7947
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7948
                             hint="remove unused LVs manually")
7949

    
7950
  def _ReleaseNodeLock(self, node_name):
7951
    """Releases the lock for a given node."""
7952
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7953

    
7954
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7955
    """Replace a disk on the primary or secondary for DRBD 8.
7956

7957
    The algorithm for replace is quite complicated:
7958

7959
      1. for each disk to be replaced:
7960

7961
        1. create new LVs on the target node with unique names
7962
        1. detach old LVs from the drbd device
7963
        1. rename old LVs to name_replaced.<time_t>
7964
        1. rename new LVs to old LVs
7965
        1. attach the new LVs (with the old names now) to the drbd device
7966

7967
      1. wait for sync across all devices
7968

7969
      1. for each modified disk:
7970

7971
        1. remove old LVs (which have the name name_replaces.<time_t>)
7972

7973
    Failures are not very well handled.
7974

7975
    """
7976
    steps_total = 6
7977

    
7978
    # Step: check device activation
7979
    self.lu.LogStep(1, steps_total, "Check device existence")
7980
    self._CheckDisksExistence([self.other_node, self.target_node])
7981
    self._CheckVolumeGroup([self.target_node, self.other_node])
7982

    
7983
    # Step: check other node consistency
7984
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7985
    self._CheckDisksConsistency(self.other_node,
7986
                                self.other_node == self.instance.primary_node,
7987
                                False)
7988

    
7989
    # Step: create new storage
7990
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7991
    iv_names = self._CreateNewStorage(self.target_node)
7992

    
7993
    # Step: for each lv, detach+rename*2+attach
7994
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7995
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7996
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7997

    
7998
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7999
                                                     old_lvs)
8000
      result.Raise("Can't detach drbd from local storage on node"
8001
                   " %s for device %s" % (self.target_node, dev.iv_name))
8002
      #dev.children = []
8003
      #cfg.Update(instance)
8004

    
8005
      # ok, we created the new LVs, so now we know we have the needed
8006
      # storage; as such, we proceed on the target node to rename
8007
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
8008
      # using the assumption that logical_id == physical_id (which in
8009
      # turn is the unique_id on that node)
8010

    
8011
      # FIXME(iustin): use a better name for the replaced LVs
8012
      temp_suffix = int(time.time())
8013
      ren_fn = lambda d, suff: (d.physical_id[0],
8014
                                d.physical_id[1] + "_replaced-%s" % suff)
8015

    
8016
      # Build the rename list based on what LVs exist on the node
8017
      rename_old_to_new = []
8018
      for to_ren in old_lvs:
8019
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
8020
        if not result.fail_msg and result.payload:
8021
          # device exists
8022
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
8023

    
8024
      self.lu.LogInfo("Renaming the old LVs on the target node")
8025
      result = self.rpc.call_blockdev_rename(self.target_node,
8026
                                             rename_old_to_new)
8027
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
8028

    
8029
      # Now we rename the new LVs to the old LVs
8030
      self.lu.LogInfo("Renaming the new LVs on the target node")
8031
      rename_new_to_old = [(new, old.physical_id)
8032
                           for old, new in zip(old_lvs, new_lvs)]
8033
      result = self.rpc.call_blockdev_rename(self.target_node,
8034
                                             rename_new_to_old)
8035
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
8036

    
8037
      for old, new in zip(old_lvs, new_lvs):
8038
        new.logical_id = old.logical_id
8039
        self.cfg.SetDiskID(new, self.target_node)
8040

    
8041
      for disk in old_lvs:
8042
        disk.logical_id = ren_fn(disk, temp_suffix)
8043
        self.cfg.SetDiskID(disk, self.target_node)
8044

    
8045
      # Now that the new lvs have the old name, we can add them to the device
8046
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
8047
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
8048
                                                  new_lvs)
8049
      msg = result.fail_msg
8050
      if msg:
8051
        for new_lv in new_lvs:
8052
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
8053
                                               new_lv).fail_msg
8054
          if msg2:
8055
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
8056
                               hint=("cleanup manually the unused logical"
8057
                                     "volumes"))
8058
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
8059

    
8060
      dev.children = new_lvs
8061

    
8062
      self.cfg.Update(self.instance, feedback_fn)
8063

    
8064
    cstep = 5
8065
    if self.early_release:
8066
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8067
      cstep += 1
8068
      self._RemoveOldStorage(self.target_node, iv_names)
8069
      # WARNING: we release both node locks here, do not do other RPCs
8070
      # than WaitForSync to the primary node
8071
      self._ReleaseNodeLock([self.target_node, self.other_node])
8072

    
8073
    # Wait for sync
8074
    # This can fail as the old devices are degraded and _WaitForSync
8075
    # does a combined result over all disks, so we don't check its return value
8076
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8077
    cstep += 1
8078
    _WaitForSync(self.lu, self.instance)
8079

    
8080
    # Check all devices manually
8081
    self._CheckDevices(self.instance.primary_node, iv_names)
8082

    
8083
    # Step: remove old storage
8084
    if not self.early_release:
8085
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8086
      cstep += 1
8087
      self._RemoveOldStorage(self.target_node, iv_names)
8088

    
8089
  def _ExecDrbd8Secondary(self, feedback_fn):
8090
    """Replace the secondary node for DRBD 8.
8091

8092
    The algorithm for replace is quite complicated:
8093
      - for all disks of the instance:
8094
        - create new LVs on the new node with same names
8095
        - shutdown the drbd device on the old secondary
8096
        - disconnect the drbd network on the primary
8097
        - create the drbd device on the new secondary
8098
        - network attach the drbd on the primary, using an artifice:
8099
          the drbd code for Attach() will connect to the network if it
8100
          finds a device which is connected to the good local disks but
8101
          not network enabled
8102
      - wait for sync across all devices
8103
      - remove all disks from the old secondary
8104

8105
    Failures are not very well handled.
8106

8107
    """
8108
    steps_total = 6
8109

    
8110
    # Step: check device activation
8111
    self.lu.LogStep(1, steps_total, "Check device existence")
8112
    self._CheckDisksExistence([self.instance.primary_node])
8113
    self._CheckVolumeGroup([self.instance.primary_node])
8114

    
8115
    # Step: check other node consistency
8116
    self.lu.LogStep(2, steps_total, "Check peer consistency")
8117
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
8118

    
8119
    # Step: create new storage
8120
    self.lu.LogStep(3, steps_total, "Allocate new storage")
8121
    for idx, dev in enumerate(self.instance.disks):
8122
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
8123
                      (self.new_node, idx))
8124
      # we pass force_create=True to force LVM creation
8125
      for new_lv in dev.children:
8126
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
8127
                        _GetInstanceInfoText(self.instance), False)
8128

    
8129
    # Step 4: dbrd minors and drbd setups changes
8130
    # after this, we must manually remove the drbd minors on both the
8131
    # error and the success paths
8132
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
8133
    minors = self.cfg.AllocateDRBDMinor([self.new_node
8134
                                         for dev in self.instance.disks],
8135
                                        self.instance.name)
8136
    logging.debug("Allocated minors %r", minors)
8137

    
8138
    iv_names = {}
8139
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
8140
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
8141
                      (self.new_node, idx))
8142
      # create new devices on new_node; note that we create two IDs:
8143
      # one without port, so the drbd will be activated without
8144
      # networking information on the new node at this stage, and one
8145
      # with network, for the latter activation in step 4
8146
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
8147
      if self.instance.primary_node == o_node1:
8148
        p_minor = o_minor1
8149
      else:
8150
        assert self.instance.primary_node == o_node2, "Three-node instance?"
8151
        p_minor = o_minor2
8152

    
8153
      new_alone_id = (self.instance.primary_node, self.new_node, None,
8154
                      p_minor, new_minor, o_secret)
8155
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
8156
                    p_minor, new_minor, o_secret)
8157

    
8158
      iv_names[idx] = (dev, dev.children, new_net_id)
8159
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
8160
                    new_net_id)
8161
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
8162
                              logical_id=new_alone_id,
8163
                              children=dev.children,
8164
                              size=dev.size)
8165
      try:
8166
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8167
                              _GetInstanceInfoText(self.instance), False)
8168
      except errors.GenericError:
8169
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8170
        raise
8171

    
8172
    # We have new devices, shutdown the drbd on the old secondary
8173
    for idx, dev in enumerate(self.instance.disks):
8174
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8175
      self.cfg.SetDiskID(dev, self.target_node)
8176
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8177
      if msg:
8178
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8179
                           "node: %s" % (idx, msg),
8180
                           hint=("Please cleanup this device manually as"
8181
                                 " soon as possible"))
8182

    
8183
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8184
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8185
                                               self.node_secondary_ip,
8186
                                               self.instance.disks)\
8187
                                              [self.instance.primary_node]
8188

    
8189
    msg = result.fail_msg
8190
    if msg:
8191
      # detaches didn't succeed (unlikely)
8192
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8193
      raise errors.OpExecError("Can't detach the disks from the network on"
8194
                               " old node: %s" % (msg,))
8195

    
8196
    # if we managed to detach at least one, we update all the disks of
8197
    # the instance to point to the new secondary
8198
    self.lu.LogInfo("Updating instance configuration")
8199
    for dev, _, new_logical_id in iv_names.itervalues():
8200
      dev.logical_id = new_logical_id
8201
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8202

    
8203
    self.cfg.Update(self.instance, feedback_fn)
8204

    
8205
    # and now perform the drbd attach
8206
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8207
                    " (standalone => connected)")
8208
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8209
                                            self.new_node],
8210
                                           self.node_secondary_ip,
8211
                                           self.instance.disks,
8212
                                           self.instance.name,
8213
                                           False)
8214
    for to_node, to_result in result.items():
8215
      msg = to_result.fail_msg
8216
      if msg:
8217
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8218
                           to_node, msg,
8219
                           hint=("please do a gnt-instance info to see the"
8220
                                 " status of disks"))
8221
    cstep = 5
8222
    if self.early_release:
8223
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8224
      cstep += 1
8225
      self._RemoveOldStorage(self.target_node, iv_names)
8226
      # WARNING: we release all node locks here, do not do other RPCs
8227
      # than WaitForSync to the primary node
8228
      self._ReleaseNodeLock([self.instance.primary_node,
8229
                             self.target_node,
8230
                             self.new_node])
8231

    
8232
    # Wait for sync
8233
    # This can fail as the old devices are degraded and _WaitForSync
8234
    # does a combined result over all disks, so we don't check its return value
8235
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8236
    cstep += 1
8237
    _WaitForSync(self.lu, self.instance)
8238

    
8239
    # Check all devices manually
8240
    self._CheckDevices(self.instance.primary_node, iv_names)
8241

    
8242
    # Step: remove old storage
8243
    if not self.early_release:
8244
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8245
      self._RemoveOldStorage(self.target_node, iv_names)
8246

    
8247

    
8248
class LURepairNodeStorage(NoHooksLU):
8249
  """Repairs the volume group on a node.
8250

8251
  """
8252
  _OP_PARAMS = [
8253
    _PNodeName,
8254
    ("storage_type", _NoDefault, _CheckStorageType),
8255
    ("name", _NoDefault, _TNonEmptyString),
8256
    ("ignore_consistency", False, _TBool),
8257
    ]
8258
  REQ_BGL = False
8259

    
8260
  def CheckArguments(self):
8261
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8262

    
8263
    storage_type = self.op.storage_type
8264

    
8265
    if (constants.SO_FIX_CONSISTENCY not in
8266
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8267
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8268
                                 " repaired" % storage_type,
8269
                                 errors.ECODE_INVAL)
8270

    
8271
  def ExpandNames(self):
8272
    self.needed_locks = {
8273
      locking.LEVEL_NODE: [self.op.node_name],
8274
      }
8275

    
8276
  def _CheckFaultyDisks(self, instance, node_name):
8277
    """Ensure faulty disks abort the opcode or at least warn."""
8278
    try:
8279
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8280
                                  node_name, True):
8281
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8282
                                   " node '%s'" % (instance.name, node_name),
8283
                                   errors.ECODE_STATE)
8284
    except errors.OpPrereqError, err:
8285
      if self.op.ignore_consistency:
8286
        self.proc.LogWarning(str(err.args[0]))
8287
      else:
8288
        raise
8289

    
8290
  def CheckPrereq(self):
8291
    """Check prerequisites.
8292

8293
    """
8294
    # Check whether any instance on this node has faulty disks
8295
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8296
      if not inst.admin_up:
8297
        continue
8298
      check_nodes = set(inst.all_nodes)
8299
      check_nodes.discard(self.op.node_name)
8300
      for inst_node_name in check_nodes:
8301
        self._CheckFaultyDisks(inst, inst_node_name)
8302

    
8303
  def Exec(self, feedback_fn):
8304
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8305
                (self.op.name, self.op.node_name))
8306

    
8307
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8308
    result = self.rpc.call_storage_execute(self.op.node_name,
8309
                                           self.op.storage_type, st_args,
8310
                                           self.op.name,
8311
                                           constants.SO_FIX_CONSISTENCY)
8312
    result.Raise("Failed to repair storage unit '%s' on %s" %
8313
                 (self.op.name, self.op.node_name))
8314

    
8315

    
8316
class LUNodeEvacuationStrategy(NoHooksLU):
8317
  """Computes the node evacuation strategy.
8318

8319
  """
8320
  _OP_PARAMS = [
8321
    ("nodes", _NoDefault, _TListOf(_TNonEmptyString)),
8322
    ("remote_node", None, _TMaybeString),
8323
    ("iallocator", None, _TMaybeString),
8324
    ]
8325
  REQ_BGL = False
8326

    
8327
  def CheckArguments(self):
8328
    _CheckIAllocatorOrNode(self, "iallocator", "remote_node")
8329

    
8330
  def ExpandNames(self):
8331
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8332
    self.needed_locks = locks = {}
8333
    if self.op.remote_node is None:
8334
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8335
    else:
8336
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8337
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8338

    
8339
  def Exec(self, feedback_fn):
8340
    if self.op.remote_node is not None:
8341
      instances = []
8342
      for node in self.op.nodes:
8343
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8344
      result = []
8345
      for i in instances:
8346
        if i.primary_node == self.op.remote_node:
8347
          raise errors.OpPrereqError("Node %s is the primary node of"
8348
                                     " instance %s, cannot use it as"
8349
                                     " secondary" %
8350
                                     (self.op.remote_node, i.name),
8351
                                     errors.ECODE_INVAL)
8352
        result.append([i.name, self.op.remote_node])
8353
    else:
8354
      ial = IAllocator(self.cfg, self.rpc,
8355
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8356
                       evac_nodes=self.op.nodes)
8357
      ial.Run(self.op.iallocator, validate=True)
8358
      if not ial.success:
8359
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8360
                                 errors.ECODE_NORES)
8361
      result = ial.result
8362
    return result
8363

    
8364

    
8365
class LUGrowDisk(LogicalUnit):
8366
  """Grow a disk of an instance.
8367

8368
  """
8369
  HPATH = "disk-grow"
8370
  HTYPE = constants.HTYPE_INSTANCE
8371
  _OP_PARAMS = [
8372
    _PInstanceName,
8373
    ("disk", _NoDefault, _TInt),
8374
    ("amount", _NoDefault, _TInt),
8375
    ("wait_for_sync", True, _TBool),
8376
    ]
8377
  REQ_BGL = False
8378

    
8379
  def ExpandNames(self):
8380
    self._ExpandAndLockInstance()
8381
    self.needed_locks[locking.LEVEL_NODE] = []
8382
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8383

    
8384
  def DeclareLocks(self, level):
8385
    if level == locking.LEVEL_NODE:
8386
      self._LockInstancesNodes()
8387

    
8388
  def BuildHooksEnv(self):
8389
    """Build hooks env.
8390

8391
    This runs on the master, the primary and all the secondaries.
8392

8393
    """
8394
    env = {
8395
      "DISK": self.op.disk,
8396
      "AMOUNT": self.op.amount,
8397
      }
8398
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8399
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8400
    return env, nl, nl
8401

    
8402
  def CheckPrereq(self):
8403
    """Check prerequisites.
8404

8405
    This checks that the instance is in the cluster.
8406

8407
    """
8408
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8409
    assert instance is not None, \
8410
      "Cannot retrieve locked instance %s" % self.op.instance_name
8411
    nodenames = list(instance.all_nodes)
8412
    for node in nodenames:
8413
      _CheckNodeOnline(self, node)
8414

    
8415
    self.instance = instance
8416

    
8417
    if instance.disk_template not in constants.DTS_GROWABLE:
8418
      raise errors.OpPrereqError("Instance's disk layout does not support"
8419
                                 " growing.", errors.ECODE_INVAL)
8420

    
8421
    self.disk = instance.FindDisk(self.op.disk)
8422

    
8423
    if instance.disk_template != constants.DT_FILE:
8424
      # TODO: check the free disk space for file, when that feature will be
8425
      # supported
8426
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8427

    
8428
  def Exec(self, feedback_fn):
8429
    """Execute disk grow.
8430

8431
    """
8432
    instance = self.instance
8433
    disk = self.disk
8434

    
8435
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8436
    if not disks_ok:
8437
      raise errors.OpExecError("Cannot activate block device to grow")
8438

    
8439
    for node in instance.all_nodes:
8440
      self.cfg.SetDiskID(disk, node)
8441
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8442
      result.Raise("Grow request failed to node %s" % node)
8443

    
8444
      # TODO: Rewrite code to work properly
8445
      # DRBD goes into sync mode for a short amount of time after executing the
8446
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8447
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8448
      # time is a work-around.
8449
      time.sleep(5)
8450

    
8451
    disk.RecordGrow(self.op.amount)
8452
    self.cfg.Update(instance, feedback_fn)
8453
    if self.op.wait_for_sync:
8454
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8455
      if disk_abort:
8456
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8457
                             " status.\nPlease check the instance.")
8458
      if not instance.admin_up:
8459
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8460
    elif not instance.admin_up:
8461
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8462
                           " not supposed to be running because no wait for"
8463
                           " sync mode was requested.")
8464

    
8465

    
8466
class LUQueryInstanceData(NoHooksLU):
8467
  """Query runtime instance data.
8468

8469
  """
8470
  _OP_PARAMS = [
8471
    ("instances", _EmptyList, _TListOf(_TNonEmptyString)),
8472
    ("static", False, _TBool),
8473
    ]
8474
  REQ_BGL = False
8475

    
8476
  def ExpandNames(self):
8477
    self.needed_locks = {}
8478
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8479

    
8480
    if self.op.instances:
8481
      self.wanted_names = []
8482
      for name in self.op.instances:
8483
        full_name = _ExpandInstanceName(self.cfg, name)
8484
        self.wanted_names.append(full_name)
8485
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8486
    else:
8487
      self.wanted_names = None
8488
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8489

    
8490
    self.needed_locks[locking.LEVEL_NODE] = []
8491
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8492

    
8493
  def DeclareLocks(self, level):
8494
    if level == locking.LEVEL_NODE:
8495
      self._LockInstancesNodes()
8496

    
8497
  def CheckPrereq(self):
8498
    """Check prerequisites.
8499

8500
    This only checks the optional instance list against the existing names.
8501

8502
    """
8503
    if self.wanted_names is None:
8504
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8505

    
8506
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8507
                             in self.wanted_names]
8508

    
8509
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8510
    """Returns the status of a block device
8511

8512
    """
8513
    if self.op.static or not node:
8514
      return None
8515

    
8516
    self.cfg.SetDiskID(dev, node)
8517

    
8518
    result = self.rpc.call_blockdev_find(node, dev)
8519
    if result.offline:
8520
      return None
8521

    
8522
    result.Raise("Can't compute disk status for %s" % instance_name)
8523

    
8524
    status = result.payload
8525
    if status is None:
8526
      return None
8527

    
8528
    return (status.dev_path, status.major, status.minor,
8529
            status.sync_percent, status.estimated_time,
8530
            status.is_degraded, status.ldisk_status)
8531

    
8532
  def _ComputeDiskStatus(self, instance, snode, dev):
8533
    """Compute block device status.
8534

8535
    """
8536
    if dev.dev_type in constants.LDS_DRBD:
8537
      # we change the snode then (otherwise we use the one passed in)
8538
      if dev.logical_id[0] == instance.primary_node:
8539
        snode = dev.logical_id[1]
8540
      else:
8541
        snode = dev.logical_id[0]
8542

    
8543
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8544
                                              instance.name, dev)
8545
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8546

    
8547
    if dev.children:
8548
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8549
                      for child in dev.children]
8550
    else:
8551
      dev_children = []
8552

    
8553
    data = {
8554
      "iv_name": dev.iv_name,
8555
      "dev_type": dev.dev_type,
8556
      "logical_id": dev.logical_id,
8557
      "physical_id": dev.physical_id,
8558
      "pstatus": dev_pstatus,
8559
      "sstatus": dev_sstatus,
8560
      "children": dev_children,
8561
      "mode": dev.mode,
8562
      "size": dev.size,
8563
      }
8564

    
8565
    return data
8566

    
8567
  def Exec(self, feedback_fn):
8568
    """Gather and return data"""
8569
    result = {}
8570

    
8571
    cluster = self.cfg.GetClusterInfo()
8572

    
8573
    for instance in self.wanted_instances:
8574
      if not self.op.static:
8575
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8576
                                                  instance.name,
8577
                                                  instance.hypervisor)
8578
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8579
        remote_info = remote_info.payload
8580
        if remote_info and "state" in remote_info:
8581
          remote_state = "up"
8582
        else:
8583
          remote_state = "down"
8584
      else:
8585
        remote_state = None
8586
      if instance.admin_up:
8587
        config_state = "up"
8588
      else:
8589
        config_state = "down"
8590

    
8591
      disks = [self._ComputeDiskStatus(instance, None, device)
8592
               for device in instance.disks]
8593

    
8594
      idict = {
8595
        "name": instance.name,
8596
        "config_state": config_state,
8597
        "run_state": remote_state,
8598
        "pnode": instance.primary_node,
8599
        "snodes": instance.secondary_nodes,
8600
        "os": instance.os,
8601
        # this happens to be the same format used for hooks
8602
        "nics": _NICListToTuple(self, instance.nics),
8603
        "disk_template": instance.disk_template,
8604
        "disks": disks,
8605
        "hypervisor": instance.hypervisor,
8606
        "network_port": instance.network_port,
8607
        "hv_instance": instance.hvparams,
8608
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8609
        "be_instance": instance.beparams,
8610
        "be_actual": cluster.FillBE(instance),
8611
        "os_instance": instance.osparams,
8612
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8613
        "serial_no": instance.serial_no,
8614
        "mtime": instance.mtime,
8615
        "ctime": instance.ctime,
8616
        "uuid": instance.uuid,
8617
        }
8618

    
8619
      result[instance.name] = idict
8620

    
8621
    return result
8622

    
8623

    
8624
class LUSetInstanceParams(LogicalUnit):
8625
  """Modifies an instances's parameters.
8626

8627
  """
8628
  HPATH = "instance-modify"
8629
  HTYPE = constants.HTYPE_INSTANCE
8630
  _OP_PARAMS = [
8631
    _PInstanceName,
8632
    ("nics", _EmptyList, _TList),
8633
    ("disks", _EmptyList, _TList),
8634
    ("beparams", _EmptyDict, _TDict),
8635
    ("hvparams", _EmptyDict, _TDict),
8636
    ("disk_template", None, _TMaybeString),
8637
    ("remote_node", None, _TMaybeString),
8638
    ("os_name", None, _TMaybeString),
8639
    ("force_variant", False, _TBool),
8640
    ("osparams", None, _TOr(_TDict, _TNone)),
8641
    _PForce,
8642
    ]
8643
  REQ_BGL = False
8644

    
8645
  def CheckArguments(self):
8646
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8647
            self.op.hvparams or self.op.beparams or self.op.os_name):
8648
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8649

    
8650
    if self.op.hvparams:
8651
      _CheckGlobalHvParams(self.op.hvparams)
8652

    
8653
    # Disk validation
8654
    disk_addremove = 0
8655
    for disk_op, disk_dict in self.op.disks:
8656
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8657
      if disk_op == constants.DDM_REMOVE:
8658
        disk_addremove += 1
8659
        continue
8660
      elif disk_op == constants.DDM_ADD:
8661
        disk_addremove += 1
8662
      else:
8663
        if not isinstance(disk_op, int):
8664
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8665
        if not isinstance(disk_dict, dict):
8666
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8667
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8668

    
8669
      if disk_op == constants.DDM_ADD:
8670
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8671
        if mode not in constants.DISK_ACCESS_SET:
8672
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8673
                                     errors.ECODE_INVAL)
8674
        size = disk_dict.get('size', None)
8675
        if size is None:
8676
          raise errors.OpPrereqError("Required disk parameter size missing",
8677
                                     errors.ECODE_INVAL)
8678
        try:
8679
          size = int(size)
8680
        except (TypeError, ValueError), err:
8681
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8682
                                     str(err), errors.ECODE_INVAL)
8683
        disk_dict['size'] = size
8684
      else:
8685
        # modification of disk
8686
        if 'size' in disk_dict:
8687
          raise errors.OpPrereqError("Disk size change not possible, use"
8688
                                     " grow-disk", errors.ECODE_INVAL)
8689

    
8690
    if disk_addremove > 1:
8691
      raise errors.OpPrereqError("Only one disk add or remove operation"
8692
                                 " supported at a time", errors.ECODE_INVAL)
8693

    
8694
    if self.op.disks and self.op.disk_template is not None:
8695
      raise errors.OpPrereqError("Disk template conversion and other disk"
8696
                                 " changes not supported at the same time",
8697
                                 errors.ECODE_INVAL)
8698

    
8699
    if self.op.disk_template:
8700
      _CheckDiskTemplate(self.op.disk_template)
8701
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8702
          self.op.remote_node is None):
8703
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8704
                                   " one requires specifying a secondary node",
8705
                                   errors.ECODE_INVAL)
8706

    
8707
    # NIC validation
8708
    nic_addremove = 0
8709
    for nic_op, nic_dict in self.op.nics:
8710
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8711
      if nic_op == constants.DDM_REMOVE:
8712
        nic_addremove += 1
8713
        continue
8714
      elif nic_op == constants.DDM_ADD:
8715
        nic_addremove += 1
8716
      else:
8717
        if not isinstance(nic_op, int):
8718
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8719
        if not isinstance(nic_dict, dict):
8720
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8721
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8722

    
8723
      # nic_dict should be a dict
8724
      nic_ip = nic_dict.get('ip', None)
8725
      if nic_ip is not None:
8726
        if nic_ip.lower() == constants.VALUE_NONE:
8727
          nic_dict['ip'] = None
8728
        else:
8729
          if not netutils.IsValidIP4(nic_ip):
8730
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8731
                                       errors.ECODE_INVAL)
8732

    
8733
      nic_bridge = nic_dict.get('bridge', None)
8734
      nic_link = nic_dict.get('link', None)
8735
      if nic_bridge and nic_link:
8736
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8737
                                   " at the same time", errors.ECODE_INVAL)
8738
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8739
        nic_dict['bridge'] = None
8740
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8741
        nic_dict['link'] = None
8742

    
8743
      if nic_op == constants.DDM_ADD:
8744
        nic_mac = nic_dict.get('mac', None)
8745
        if nic_mac is None:
8746
          nic_dict['mac'] = constants.VALUE_AUTO
8747

    
8748
      if 'mac' in nic_dict:
8749
        nic_mac = nic_dict['mac']
8750
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8751
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8752

    
8753
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8754
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8755
                                     " modifying an existing nic",
8756
                                     errors.ECODE_INVAL)
8757

    
8758
    if nic_addremove > 1:
8759
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8760
                                 " supported at a time", errors.ECODE_INVAL)
8761

    
8762
  def ExpandNames(self):
8763
    self._ExpandAndLockInstance()
8764
    self.needed_locks[locking.LEVEL_NODE] = []
8765
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8766

    
8767
  def DeclareLocks(self, level):
8768
    if level == locking.LEVEL_NODE:
8769
      self._LockInstancesNodes()
8770
      if self.op.disk_template and self.op.remote_node:
8771
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8772
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8773

    
8774
  def BuildHooksEnv(self):
8775
    """Build hooks env.
8776

8777
    This runs on the master, primary and secondaries.
8778

8779
    """
8780
    args = dict()
8781
    if constants.BE_MEMORY in self.be_new:
8782
      args['memory'] = self.be_new[constants.BE_MEMORY]
8783
    if constants.BE_VCPUS in self.be_new:
8784
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8785
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8786
    # information at all.
8787
    if self.op.nics:
8788
      args['nics'] = []
8789
      nic_override = dict(self.op.nics)
8790
      for idx, nic in enumerate(self.instance.nics):
8791
        if idx in nic_override:
8792
          this_nic_override = nic_override[idx]
8793
        else:
8794
          this_nic_override = {}
8795
        if 'ip' in this_nic_override:
8796
          ip = this_nic_override['ip']
8797
        else:
8798
          ip = nic.ip
8799
        if 'mac' in this_nic_override:
8800
          mac = this_nic_override['mac']
8801
        else:
8802
          mac = nic.mac
8803
        if idx in self.nic_pnew:
8804
          nicparams = self.nic_pnew[idx]
8805
        else:
8806
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8807
        mode = nicparams[constants.NIC_MODE]
8808
        link = nicparams[constants.NIC_LINK]
8809
        args['nics'].append((ip, mac, mode, link))
8810
      if constants.DDM_ADD in nic_override:
8811
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8812
        mac = nic_override[constants.DDM_ADD]['mac']
8813
        nicparams = self.nic_pnew[constants.DDM_ADD]
8814
        mode = nicparams[constants.NIC_MODE]
8815
        link = nicparams[constants.NIC_LINK]
8816
        args['nics'].append((ip, mac, mode, link))
8817
      elif constants.DDM_REMOVE in nic_override:
8818
        del args['nics'][-1]
8819

    
8820
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8821
    if self.op.disk_template:
8822
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8823
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8824
    return env, nl, nl
8825

    
8826
  def CheckPrereq(self):
8827
    """Check prerequisites.
8828

8829
    This only checks the instance list against the existing names.
8830

8831
    """
8832
    # checking the new params on the primary/secondary nodes
8833

    
8834
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8835
    cluster = self.cluster = self.cfg.GetClusterInfo()
8836
    assert self.instance is not None, \
8837
      "Cannot retrieve locked instance %s" % self.op.instance_name
8838
    pnode = instance.primary_node
8839
    nodelist = list(instance.all_nodes)
8840

    
8841
    # OS change
8842
    if self.op.os_name and not self.op.force:
8843
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8844
                      self.op.force_variant)
8845
      instance_os = self.op.os_name
8846
    else:
8847
      instance_os = instance.os
8848

    
8849
    if self.op.disk_template:
8850
      if instance.disk_template == self.op.disk_template:
8851
        raise errors.OpPrereqError("Instance already has disk template %s" %
8852
                                   instance.disk_template, errors.ECODE_INVAL)
8853

    
8854
      if (instance.disk_template,
8855
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8856
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8857
                                   " %s to %s" % (instance.disk_template,
8858
                                                  self.op.disk_template),
8859
                                   errors.ECODE_INVAL)
8860
      _CheckInstanceDown(self, instance, "cannot change disk template")
8861
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8862
        if self.op.remote_node == pnode:
8863
          raise errors.OpPrereqError("Given new secondary node %s is the same"
8864
                                     " as the primary node of the instance" %
8865
                                     self.op.remote_node, errors.ECODE_STATE)
8866
        _CheckNodeOnline(self, self.op.remote_node)
8867
        _CheckNodeNotDrained(self, self.op.remote_node)
8868
        disks = [{"size": d.size} for d in instance.disks]
8869
        required = _ComputeDiskSize(self.op.disk_template, disks)
8870
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8871

    
8872
    # hvparams processing
8873
    if self.op.hvparams:
8874
      hv_type = instance.hypervisor
8875
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8876
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8877
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8878

    
8879
      # local check
8880
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8881
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8882
      self.hv_new = hv_new # the new actual values
8883
      self.hv_inst = i_hvdict # the new dict (without defaults)
8884
    else:
8885
      self.hv_new = self.hv_inst = {}
8886

    
8887
    # beparams processing
8888
    if self.op.beparams:
8889
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8890
                                   use_none=True)
8891
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8892
      be_new = cluster.SimpleFillBE(i_bedict)
8893
      self.be_new = be_new # the new actual values
8894
      self.be_inst = i_bedict # the new dict (without defaults)
8895
    else:
8896
      self.be_new = self.be_inst = {}
8897

    
8898
    # osparams processing
8899
    if self.op.osparams:
8900
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8901
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8902
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8903
      self.os_inst = i_osdict # the new dict (without defaults)
8904
    else:
8905
      self.os_new = self.os_inst = {}
8906

    
8907
    self.warn = []
8908

    
8909
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8910
      mem_check_list = [pnode]
8911
      if be_new[constants.BE_AUTO_BALANCE]:
8912
        # either we changed auto_balance to yes or it was from before
8913
        mem_check_list.extend(instance.secondary_nodes)
8914
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8915
                                                  instance.hypervisor)
8916
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8917
                                         instance.hypervisor)
8918
      pninfo = nodeinfo[pnode]
8919
      msg = pninfo.fail_msg
8920
      if msg:
8921
        # Assume the primary node is unreachable and go ahead
8922
        self.warn.append("Can't get info from primary node %s: %s" %
8923
                         (pnode,  msg))
8924
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8925
        self.warn.append("Node data from primary node %s doesn't contain"
8926
                         " free memory information" % pnode)
8927
      elif instance_info.fail_msg:
8928
        self.warn.append("Can't get instance runtime information: %s" %
8929
                        instance_info.fail_msg)
8930
      else:
8931
        if instance_info.payload:
8932
          current_mem = int(instance_info.payload['memory'])
8933
        else:
8934
          # Assume instance not running
8935
          # (there is a slight race condition here, but it's not very probable,
8936
          # and we have no other way to check)
8937
          current_mem = 0
8938
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8939
                    pninfo.payload['memory_free'])
8940
        if miss_mem > 0:
8941
          raise errors.OpPrereqError("This change will prevent the instance"
8942
                                     " from starting, due to %d MB of memory"
8943
                                     " missing on its primary node" % miss_mem,
8944
                                     errors.ECODE_NORES)
8945

    
8946
      if be_new[constants.BE_AUTO_BALANCE]:
8947
        for node, nres in nodeinfo.items():
8948
          if node not in instance.secondary_nodes:
8949
            continue
8950
          msg = nres.fail_msg
8951
          if msg:
8952
            self.warn.append("Can't get info from secondary node %s: %s" %
8953
                             (node, msg))
8954
          elif not isinstance(nres.payload.get('memory_free', None), int):
8955
            self.warn.append("Secondary node %s didn't return free"
8956
                             " memory information" % node)
8957
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8958
            self.warn.append("Not enough memory to failover instance to"
8959
                             " secondary node %s" % node)
8960

    
8961
    # NIC processing
8962
    self.nic_pnew = {}
8963
    self.nic_pinst = {}
8964
    for nic_op, nic_dict in self.op.nics:
8965
      if nic_op == constants.DDM_REMOVE:
8966
        if not instance.nics:
8967
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8968
                                     errors.ECODE_INVAL)
8969
        continue
8970
      if nic_op != constants.DDM_ADD:
8971
        # an existing nic
8972
        if not instance.nics:
8973
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8974
                                     " no NICs" % nic_op,
8975
                                     errors.ECODE_INVAL)
8976
        if nic_op < 0 or nic_op >= len(instance.nics):
8977
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8978
                                     " are 0 to %d" %
8979
                                     (nic_op, len(instance.nics) - 1),
8980
                                     errors.ECODE_INVAL)
8981
        old_nic_params = instance.nics[nic_op].nicparams
8982
        old_nic_ip = instance.nics[nic_op].ip
8983
      else:
8984
        old_nic_params = {}
8985
        old_nic_ip = None
8986

    
8987
      update_params_dict = dict([(key, nic_dict[key])
8988
                                 for key in constants.NICS_PARAMETERS
8989
                                 if key in nic_dict])
8990

    
8991
      if 'bridge' in nic_dict:
8992
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8993

    
8994
      new_nic_params = _GetUpdatedParams(old_nic_params,
8995
                                         update_params_dict)
8996
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8997
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8998
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8999
      self.nic_pinst[nic_op] = new_nic_params
9000
      self.nic_pnew[nic_op] = new_filled_nic_params
9001
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
9002

    
9003
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
9004
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
9005
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
9006
        if msg:
9007
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
9008
          if self.op.force:
9009
            self.warn.append(msg)
9010
          else:
9011
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
9012
      if new_nic_mode == constants.NIC_MODE_ROUTED:
9013
        if 'ip' in nic_dict:
9014
          nic_ip = nic_dict['ip']
9015
        else:
9016
          nic_ip = old_nic_ip
9017
        if nic_ip is None:
9018
          raise errors.OpPrereqError('Cannot set the nic ip to None'
9019
                                     ' on a routed nic', errors.ECODE_INVAL)
9020
      if 'mac' in nic_dict:
9021
        nic_mac = nic_dict['mac']
9022
        if nic_mac is None:
9023
          raise errors.OpPrereqError('Cannot set the nic mac to None',
9024
                                     errors.ECODE_INVAL)
9025
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
9026
          # otherwise generate the mac
9027
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
9028
        else:
9029
          # or validate/reserve the current one
9030
          try:
9031
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
9032
          except errors.ReservationError:
9033
            raise errors.OpPrereqError("MAC address %s already in use"
9034
                                       " in cluster" % nic_mac,
9035
                                       errors.ECODE_NOTUNIQUE)
9036

    
9037
    # DISK processing
9038
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
9039
      raise errors.OpPrereqError("Disk operations not supported for"
9040
                                 " diskless instances",
9041
                                 errors.ECODE_INVAL)
9042
    for disk_op, _ in self.op.disks:
9043
      if disk_op == constants.DDM_REMOVE:
9044
        if len(instance.disks) == 1:
9045
          raise errors.OpPrereqError("Cannot remove the last disk of"
9046
                                     " an instance", errors.ECODE_INVAL)
9047
        _CheckInstanceDown(self, instance, "cannot remove disks")
9048

    
9049
      if (disk_op == constants.DDM_ADD and
9050
          len(instance.nics) >= constants.MAX_DISKS):
9051
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
9052
                                   " add more" % constants.MAX_DISKS,
9053
                                   errors.ECODE_STATE)
9054
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
9055
        # an existing disk
9056
        if disk_op < 0 or disk_op >= len(instance.disks):
9057
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
9058
                                     " are 0 to %d" %
9059
                                     (disk_op, len(instance.disks)),
9060
                                     errors.ECODE_INVAL)
9061

    
9062
    return
9063

    
9064
  def _ConvertPlainToDrbd(self, feedback_fn):
9065
    """Converts an instance from plain to drbd.
9066

9067
    """
9068
    feedback_fn("Converting template to drbd")
9069
    instance = self.instance
9070
    pnode = instance.primary_node
9071
    snode = self.op.remote_node
9072

    
9073
    # create a fake disk info for _GenerateDiskTemplate
9074
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
9075
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
9076
                                      instance.name, pnode, [snode],
9077
                                      disk_info, None, None, 0)
9078
    info = _GetInstanceInfoText(instance)
9079
    feedback_fn("Creating aditional volumes...")
9080
    # first, create the missing data and meta devices
9081
    for disk in new_disks:
9082
      # unfortunately this is... not too nice
9083
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
9084
                            info, True)
9085
      for child in disk.children:
9086
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
9087
    # at this stage, all new LVs have been created, we can rename the
9088
    # old ones
9089
    feedback_fn("Renaming original volumes...")
9090
    rename_list = [(o, n.children[0].logical_id)
9091
                   for (o, n) in zip(instance.disks, new_disks)]
9092
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
9093
    result.Raise("Failed to rename original LVs")
9094

    
9095
    feedback_fn("Initializing DRBD devices...")
9096
    # all child devices are in place, we can now create the DRBD devices
9097
    for disk in new_disks:
9098
      for node in [pnode, snode]:
9099
        f_create = node == pnode
9100
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
9101

    
9102
    # at this point, the instance has been modified
9103
    instance.disk_template = constants.DT_DRBD8
9104
    instance.disks = new_disks
9105
    self.cfg.Update(instance, feedback_fn)
9106

    
9107
    # disks are created, waiting for sync
9108
    disk_abort = not _WaitForSync(self, instance)
9109
    if disk_abort:
9110
      raise errors.OpExecError("There are some degraded disks for"
9111
                               " this instance, please cleanup manually")
9112

    
9113
  def _ConvertDrbdToPlain(self, feedback_fn):
9114
    """Converts an instance from drbd to plain.
9115

9116
    """
9117
    instance = self.instance
9118
    assert len(instance.secondary_nodes) == 1
9119
    pnode = instance.primary_node
9120
    snode = instance.secondary_nodes[0]
9121
    feedback_fn("Converting template to plain")
9122

    
9123
    old_disks = instance.disks
9124
    new_disks = [d.children[0] for d in old_disks]
9125

    
9126
    # copy over size and mode
9127
    for parent, child in zip(old_disks, new_disks):
9128
      child.size = parent.size
9129
      child.mode = parent.mode
9130

    
9131
    # update instance structure
9132
    instance.disks = new_disks
9133
    instance.disk_template = constants.DT_PLAIN
9134
    self.cfg.Update(instance, feedback_fn)
9135

    
9136
    feedback_fn("Removing volumes on the secondary node...")
9137
    for disk in old_disks:
9138
      self.cfg.SetDiskID(disk, snode)
9139
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
9140
      if msg:
9141
        self.LogWarning("Could not remove block device %s on node %s,"
9142
                        " continuing anyway: %s", disk.iv_name, snode, msg)
9143

    
9144
    feedback_fn("Removing unneeded volumes on the primary node...")
9145
    for idx, disk in enumerate(old_disks):
9146
      meta = disk.children[1]
9147
      self.cfg.SetDiskID(meta, pnode)
9148
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
9149
      if msg:
9150
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
9151
                        " continuing anyway: %s", idx, pnode, msg)
9152

    
9153

    
9154
  def Exec(self, feedback_fn):
9155
    """Modifies an instance.
9156

9157
    All parameters take effect only at the next restart of the instance.
9158

9159
    """
9160
    # Process here the warnings from CheckPrereq, as we don't have a
9161
    # feedback_fn there.
9162
    for warn in self.warn:
9163
      feedback_fn("WARNING: %s" % warn)
9164

    
9165
    result = []
9166
    instance = self.instance
9167
    # disk changes
9168
    for disk_op, disk_dict in self.op.disks:
9169
      if disk_op == constants.DDM_REMOVE:
9170
        # remove the last disk
9171
        device = instance.disks.pop()
9172
        device_idx = len(instance.disks)
9173
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9174
          self.cfg.SetDiskID(disk, node)
9175
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9176
          if msg:
9177
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9178
                            " continuing anyway", device_idx, node, msg)
9179
        result.append(("disk/%d" % device_idx, "remove"))
9180
      elif disk_op == constants.DDM_ADD:
9181
        # add a new disk
9182
        if instance.disk_template == constants.DT_FILE:
9183
          file_driver, file_path = instance.disks[0].logical_id
9184
          file_path = os.path.dirname(file_path)
9185
        else:
9186
          file_driver = file_path = None
9187
        disk_idx_base = len(instance.disks)
9188
        new_disk = _GenerateDiskTemplate(self,
9189
                                         instance.disk_template,
9190
                                         instance.name, instance.primary_node,
9191
                                         instance.secondary_nodes,
9192
                                         [disk_dict],
9193
                                         file_path,
9194
                                         file_driver,
9195
                                         disk_idx_base)[0]
9196
        instance.disks.append(new_disk)
9197
        info = _GetInstanceInfoText(instance)
9198

    
9199
        logging.info("Creating volume %s for instance %s",
9200
                     new_disk.iv_name, instance.name)
9201
        # Note: this needs to be kept in sync with _CreateDisks
9202
        #HARDCODE
9203
        for node in instance.all_nodes:
9204
          f_create = node == instance.primary_node
9205
          try:
9206
            _CreateBlockDev(self, node, instance, new_disk,
9207
                            f_create, info, f_create)
9208
          except errors.OpExecError, err:
9209
            self.LogWarning("Failed to create volume %s (%s) on"
9210
                            " node %s: %s",
9211
                            new_disk.iv_name, new_disk, node, err)
9212
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9213
                       (new_disk.size, new_disk.mode)))
9214
      else:
9215
        # change a given disk
9216
        instance.disks[disk_op].mode = disk_dict['mode']
9217
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9218

    
9219
    if self.op.disk_template:
9220
      r_shut = _ShutdownInstanceDisks(self, instance)
9221
      if not r_shut:
9222
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9223
                                 " proceed with disk template conversion")
9224
      mode = (instance.disk_template, self.op.disk_template)
9225
      try:
9226
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9227
      except:
9228
        self.cfg.ReleaseDRBDMinors(instance.name)
9229
        raise
9230
      result.append(("disk_template", self.op.disk_template))
9231

    
9232
    # NIC changes
9233
    for nic_op, nic_dict in self.op.nics:
9234
      if nic_op == constants.DDM_REMOVE:
9235
        # remove the last nic
9236
        del instance.nics[-1]
9237
        result.append(("nic.%d" % len(instance.nics), "remove"))
9238
      elif nic_op == constants.DDM_ADD:
9239
        # mac and bridge should be set, by now
9240
        mac = nic_dict['mac']
9241
        ip = nic_dict.get('ip', None)
9242
        nicparams = self.nic_pinst[constants.DDM_ADD]
9243
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9244
        instance.nics.append(new_nic)
9245
        result.append(("nic.%d" % (len(instance.nics) - 1),
9246
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9247
                       (new_nic.mac, new_nic.ip,
9248
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9249
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9250
                       )))
9251
      else:
9252
        for key in 'mac', 'ip':
9253
          if key in nic_dict:
9254
            setattr(instance.nics[nic_op], key, nic_dict[key])
9255
        if nic_op in self.nic_pinst:
9256
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9257
        for key, val in nic_dict.iteritems():
9258
          result.append(("nic.%s/%d" % (key, nic_op), val))
9259

    
9260
    # hvparams changes
9261
    if self.op.hvparams:
9262
      instance.hvparams = self.hv_inst
9263
      for key, val in self.op.hvparams.iteritems():
9264
        result.append(("hv/%s" % key, val))
9265

    
9266
    # beparams changes
9267
    if self.op.beparams:
9268
      instance.beparams = self.be_inst
9269
      for key, val in self.op.beparams.iteritems():
9270
        result.append(("be/%s" % key, val))
9271

    
9272
    # OS change
9273
    if self.op.os_name:
9274
      instance.os = self.op.os_name
9275

    
9276
    # osparams changes
9277
    if self.op.osparams:
9278
      instance.osparams = self.os_inst
9279
      for key, val in self.op.osparams.iteritems():
9280
        result.append(("os/%s" % key, val))
9281

    
9282
    self.cfg.Update(instance, feedback_fn)
9283

    
9284
    return result
9285

    
9286
  _DISK_CONVERSIONS = {
9287
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9288
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9289
    }
9290

    
9291

    
9292
class LUQueryExports(NoHooksLU):
9293
  """Query the exports list
9294

9295
  """
9296
  _OP_PARAMS = [
9297
    ("nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9298
    ("use_locking", False, _TBool),
9299
    ]
9300
  REQ_BGL = False
9301

    
9302
  def ExpandNames(self):
9303
    self.needed_locks = {}
9304
    self.share_locks[locking.LEVEL_NODE] = 1
9305
    if not self.op.nodes:
9306
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9307
    else:
9308
      self.needed_locks[locking.LEVEL_NODE] = \
9309
        _GetWantedNodes(self, self.op.nodes)
9310

    
9311
  def Exec(self, feedback_fn):
9312
    """Compute the list of all the exported system images.
9313

9314
    @rtype: dict
9315
    @return: a dictionary with the structure node->(export-list)
9316
        where export-list is a list of the instances exported on
9317
        that node.
9318

9319
    """
9320
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9321
    rpcresult = self.rpc.call_export_list(self.nodes)
9322
    result = {}
9323
    for node in rpcresult:
9324
      if rpcresult[node].fail_msg:
9325
        result[node] = False
9326
      else:
9327
        result[node] = rpcresult[node].payload
9328

    
9329
    return result
9330

    
9331

    
9332
class LUPrepareExport(NoHooksLU):
9333
  """Prepares an instance for an export and returns useful information.
9334

9335
  """
9336
  _OP_PARAMS = [
9337
    _PInstanceName,
9338
    ("mode", _NoDefault, _TElemOf(constants.EXPORT_MODES)),
9339
    ]
9340
  REQ_BGL = False
9341

    
9342
  def ExpandNames(self):
9343
    self._ExpandAndLockInstance()
9344

    
9345
  def CheckPrereq(self):
9346
    """Check prerequisites.
9347

9348
    """
9349
    instance_name = self.op.instance_name
9350

    
9351
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9352
    assert self.instance is not None, \
9353
          "Cannot retrieve locked instance %s" % self.op.instance_name
9354
    _CheckNodeOnline(self, self.instance.primary_node)
9355

    
9356
    self._cds = _GetClusterDomainSecret()
9357

    
9358
  def Exec(self, feedback_fn):
9359
    """Prepares an instance for an export.
9360

9361
    """
9362
    instance = self.instance
9363

    
9364
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9365
      salt = utils.GenerateSecret(8)
9366

    
9367
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9368
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9369
                                              constants.RIE_CERT_VALIDITY)
9370
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9371

    
9372
      (name, cert_pem) = result.payload
9373

    
9374
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9375
                                             cert_pem)
9376

    
9377
      return {
9378
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9379
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9380
                          salt),
9381
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9382
        }
9383

    
9384
    return None
9385

    
9386

    
9387
class LUExportInstance(LogicalUnit):
9388
  """Export an instance to an image in the cluster.
9389

9390
  """
9391
  HPATH = "instance-export"
9392
  HTYPE = constants.HTYPE_INSTANCE
9393
  _OP_PARAMS = [
9394
    _PInstanceName,
9395
    ("target_node", _NoDefault, _TOr(_TNonEmptyString, _TList)),
9396
    ("shutdown", True, _TBool),
9397
    _PShutdownTimeout,
9398
    ("remove_instance", False, _TBool),
9399
    ("ignore_remove_failures", False, _TBool),
9400
    ("mode", constants.EXPORT_MODE_LOCAL, _TElemOf(constants.EXPORT_MODES)),
9401
    ("x509_key_name", None, _TOr(_TList, _TNone)),
9402
    ("destination_x509_ca", None, _TMaybeString),
9403
    ]
9404
  REQ_BGL = False
9405

    
9406
  def CheckArguments(self):
9407
    """Check the arguments.
9408

9409
    """
9410
    self.x509_key_name = self.op.x509_key_name
9411
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9412

    
9413
    if self.op.remove_instance and not self.op.shutdown:
9414
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9415
                                 " down before")
9416

    
9417
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9418
      if not self.x509_key_name:
9419
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9420
                                   errors.ECODE_INVAL)
9421

    
9422
      if not self.dest_x509_ca_pem:
9423
        raise errors.OpPrereqError("Missing destination X509 CA",
9424
                                   errors.ECODE_INVAL)
9425

    
9426
  def ExpandNames(self):
9427
    self._ExpandAndLockInstance()
9428

    
9429
    # Lock all nodes for local exports
9430
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9431
      # FIXME: lock only instance primary and destination node
9432
      #
9433
      # Sad but true, for now we have do lock all nodes, as we don't know where
9434
      # the previous export might be, and in this LU we search for it and
9435
      # remove it from its current node. In the future we could fix this by:
9436
      #  - making a tasklet to search (share-lock all), then create the
9437
      #    new one, then one to remove, after
9438
      #  - removing the removal operation altogether
9439
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9440

    
9441
  def DeclareLocks(self, level):
9442
    """Last minute lock declaration."""
9443
    # All nodes are locked anyway, so nothing to do here.
9444

    
9445
  def BuildHooksEnv(self):
9446
    """Build hooks env.
9447

9448
    This will run on the master, primary node and target node.
9449

9450
    """
9451
    env = {
9452
      "EXPORT_MODE": self.op.mode,
9453
      "EXPORT_NODE": self.op.target_node,
9454
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9455
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9456
      # TODO: Generic function for boolean env variables
9457
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9458
      }
9459

    
9460
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9461

    
9462
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9463

    
9464
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9465
      nl.append(self.op.target_node)
9466

    
9467
    return env, nl, nl
9468

    
9469
  def CheckPrereq(self):
9470
    """Check prerequisites.
9471

9472
    This checks that the instance and node names are valid.
9473

9474
    """
9475
    instance_name = self.op.instance_name
9476

    
9477
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9478
    assert self.instance is not None, \
9479
          "Cannot retrieve locked instance %s" % self.op.instance_name
9480
    _CheckNodeOnline(self, self.instance.primary_node)
9481

    
9482
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9483
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9484
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9485
      assert self.dst_node is not None
9486

    
9487
      _CheckNodeOnline(self, self.dst_node.name)
9488
      _CheckNodeNotDrained(self, self.dst_node.name)
9489

    
9490
      self._cds = None
9491
      self.dest_disk_info = None
9492
      self.dest_x509_ca = None
9493

    
9494
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9495
      self.dst_node = None
9496

    
9497
      if len(self.op.target_node) != len(self.instance.disks):
9498
        raise errors.OpPrereqError(("Received destination information for %s"
9499
                                    " disks, but instance %s has %s disks") %
9500
                                   (len(self.op.target_node), instance_name,
9501
                                    len(self.instance.disks)),
9502
                                   errors.ECODE_INVAL)
9503

    
9504
      cds = _GetClusterDomainSecret()
9505

    
9506
      # Check X509 key name
9507
      try:
9508
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9509
      except (TypeError, ValueError), err:
9510
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9511

    
9512
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9513
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9514
                                   errors.ECODE_INVAL)
9515

    
9516
      # Load and verify CA
9517
      try:
9518
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9519
      except OpenSSL.crypto.Error, err:
9520
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9521
                                   (err, ), errors.ECODE_INVAL)
9522

    
9523
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9524
      if errcode is not None:
9525
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9526
                                   (msg, ), errors.ECODE_INVAL)
9527

    
9528
      self.dest_x509_ca = cert
9529

    
9530
      # Verify target information
9531
      disk_info = []
9532
      for idx, disk_data in enumerate(self.op.target_node):
9533
        try:
9534
          (host, port, magic) = \
9535
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9536
        except errors.GenericError, err:
9537
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9538
                                     (idx, err), errors.ECODE_INVAL)
9539

    
9540
        disk_info.append((host, port, magic))
9541

    
9542
      assert len(disk_info) == len(self.op.target_node)
9543
      self.dest_disk_info = disk_info
9544

    
9545
    else:
9546
      raise errors.ProgrammerError("Unhandled export mode %r" %
9547
                                   self.op.mode)
9548

    
9549
    # instance disk type verification
9550
    # TODO: Implement export support for file-based disks
9551
    for disk in self.instance.disks:
9552
      if disk.dev_type == constants.LD_FILE:
9553
        raise errors.OpPrereqError("Export not supported for instances with"
9554
                                   " file-based disks", errors.ECODE_INVAL)
9555

    
9556
  def _CleanupExports(self, feedback_fn):
9557
    """Removes exports of current instance from all other nodes.
9558

9559
    If an instance in a cluster with nodes A..D was exported to node C, its
9560
    exports will be removed from the nodes A, B and D.
9561

9562
    """
9563
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9564

    
9565
    nodelist = self.cfg.GetNodeList()
9566
    nodelist.remove(self.dst_node.name)
9567

    
9568
    # on one-node clusters nodelist will be empty after the removal
9569
    # if we proceed the backup would be removed because OpQueryExports
9570
    # substitutes an empty list with the full cluster node list.
9571
    iname = self.instance.name
9572
    if nodelist:
9573
      feedback_fn("Removing old exports for instance %s" % iname)
9574
      exportlist = self.rpc.call_export_list(nodelist)
9575
      for node in exportlist:
9576
        if exportlist[node].fail_msg:
9577
          continue
9578
        if iname in exportlist[node].payload:
9579
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9580
          if msg:
9581
            self.LogWarning("Could not remove older export for instance %s"
9582
                            " on node %s: %s", iname, node, msg)
9583

    
9584
  def Exec(self, feedback_fn):
9585
    """Export an instance to an image in the cluster.
9586

9587
    """
9588
    assert self.op.mode in constants.EXPORT_MODES
9589

    
9590
    instance = self.instance
9591
    src_node = instance.primary_node
9592

    
9593
    if self.op.shutdown:
9594
      # shutdown the instance, but not the disks
9595
      feedback_fn("Shutting down instance %s" % instance.name)
9596
      result = self.rpc.call_instance_shutdown(src_node, instance,
9597
                                               self.op.shutdown_timeout)
9598
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9599
      result.Raise("Could not shutdown instance %s on"
9600
                   " node %s" % (instance.name, src_node))
9601

    
9602
    # set the disks ID correctly since call_instance_start needs the
9603
    # correct drbd minor to create the symlinks
9604
    for disk in instance.disks:
9605
      self.cfg.SetDiskID(disk, src_node)
9606

    
9607
    activate_disks = (not instance.admin_up)
9608

    
9609
    if activate_disks:
9610
      # Activate the instance disks if we'exporting a stopped instance
9611
      feedback_fn("Activating disks for %s" % instance.name)
9612
      _StartInstanceDisks(self, instance, None)
9613

    
9614
    try:
9615
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9616
                                                     instance)
9617

    
9618
      helper.CreateSnapshots()
9619
      try:
9620
        if (self.op.shutdown and instance.admin_up and
9621
            not self.op.remove_instance):
9622
          assert not activate_disks
9623
          feedback_fn("Starting instance %s" % instance.name)
9624
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9625
          msg = result.fail_msg
9626
          if msg:
9627
            feedback_fn("Failed to start instance: %s" % msg)
9628
            _ShutdownInstanceDisks(self, instance)
9629
            raise errors.OpExecError("Could not start instance: %s" % msg)
9630

    
9631
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9632
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9633
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9634
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9635
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9636

    
9637
          (key_name, _, _) = self.x509_key_name
9638

    
9639
          dest_ca_pem = \
9640
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9641
                                            self.dest_x509_ca)
9642

    
9643
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9644
                                                     key_name, dest_ca_pem,
9645
                                                     timeouts)
9646
      finally:
9647
        helper.Cleanup()
9648

    
9649
      # Check for backwards compatibility
9650
      assert len(dresults) == len(instance.disks)
9651
      assert compat.all(isinstance(i, bool) for i in dresults), \
9652
             "Not all results are boolean: %r" % dresults
9653

    
9654
    finally:
9655
      if activate_disks:
9656
        feedback_fn("Deactivating disks for %s" % instance.name)
9657
        _ShutdownInstanceDisks(self, instance)
9658

    
9659
    if not (compat.all(dresults) and fin_resu):
9660
      failures = []
9661
      if not fin_resu:
9662
        failures.append("export finalization")
9663
      if not compat.all(dresults):
9664
        fdsk = utils.CommaJoin(idx for (idx, dsk) in enumerate(dresults)
9665
                               if not dsk)
9666
        failures.append("disk export: disk(s) %s" % fdsk)
9667

    
9668
      raise errors.OpExecError("Export failed, errors in %s" %
9669
                               utils.CommaJoin(failures))
9670

    
9671
    # At this point, the export was successful, we can cleanup/finish
9672

    
9673
    # Remove instance if requested
9674
    if self.op.remove_instance:
9675
      feedback_fn("Removing instance %s" % instance.name)
9676
      _RemoveInstance(self, feedback_fn, instance,
9677
                      self.op.ignore_remove_failures)
9678

    
9679
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9680
      self._CleanupExports(feedback_fn)
9681

    
9682
    return fin_resu, dresults
9683

    
9684

    
9685
class LURemoveExport(NoHooksLU):
9686
  """Remove exports related to the named instance.
9687

9688
  """
9689
  _OP_PARAMS = [
9690
    _PInstanceName,
9691
    ]
9692
  REQ_BGL = False
9693

    
9694
  def ExpandNames(self):
9695
    self.needed_locks = {}
9696
    # We need all nodes to be locked in order for RemoveExport to work, but we
9697
    # don't need to lock the instance itself, as nothing will happen to it (and
9698
    # we can remove exports also for a removed instance)
9699
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9700

    
9701
  def Exec(self, feedback_fn):
9702
    """Remove any export.
9703

9704
    """
9705
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9706
    # If the instance was not found we'll try with the name that was passed in.
9707
    # This will only work if it was an FQDN, though.
9708
    fqdn_warn = False
9709
    if not instance_name:
9710
      fqdn_warn = True
9711
      instance_name = self.op.instance_name
9712

    
9713
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9714
    exportlist = self.rpc.call_export_list(locked_nodes)
9715
    found = False
9716
    for node in exportlist:
9717
      msg = exportlist[node].fail_msg
9718
      if msg:
9719
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9720
        continue
9721
      if instance_name in exportlist[node].payload:
9722
        found = True
9723
        result = self.rpc.call_export_remove(node, instance_name)
9724
        msg = result.fail_msg
9725
        if msg:
9726
          logging.error("Could not remove export for instance %s"
9727
                        " on node %s: %s", instance_name, node, msg)
9728

    
9729
    if fqdn_warn and not found:
9730
      feedback_fn("Export not found. If trying to remove an export belonging"
9731
                  " to a deleted instance please use its Fully Qualified"
9732
                  " Domain Name.")
9733

    
9734

    
9735
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9736
  """Generic tags LU.
9737

9738
  This is an abstract class which is the parent of all the other tags LUs.
9739

9740
  """
9741

    
9742
  def ExpandNames(self):
9743
    self.needed_locks = {}
9744
    if self.op.kind == constants.TAG_NODE:
9745
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9746
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9747
    elif self.op.kind == constants.TAG_INSTANCE:
9748
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9749
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9750

    
9751
  def CheckPrereq(self):
9752
    """Check prerequisites.
9753

9754
    """
9755
    if self.op.kind == constants.TAG_CLUSTER:
9756
      self.target = self.cfg.GetClusterInfo()
9757
    elif self.op.kind == constants.TAG_NODE:
9758
      self.target = self.cfg.GetNodeInfo(self.op.name)
9759
    elif self.op.kind == constants.TAG_INSTANCE:
9760
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9761
    else:
9762
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9763
                                 str(self.op.kind), errors.ECODE_INVAL)
9764

    
9765

    
9766
class LUGetTags(TagsLU):
9767
  """Returns the tags of a given object.
9768

9769
  """
9770
  _OP_PARAMS = [
9771
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9772
    # Name is only meaningful for nodes and instances
9773
    ("name", _NoDefault, _TMaybeString),
9774
    ]
9775
  REQ_BGL = False
9776

    
9777
  def Exec(self, feedback_fn):
9778
    """Returns the tag list.
9779

9780
    """
9781
    return list(self.target.GetTags())
9782

    
9783

    
9784
class LUSearchTags(NoHooksLU):
9785
  """Searches the tags for a given pattern.
9786

9787
  """
9788
  _OP_PARAMS = [
9789
    ("pattern", _NoDefault, _TNonEmptyString),
9790
    ]
9791
  REQ_BGL = False
9792

    
9793
  def ExpandNames(self):
9794
    self.needed_locks = {}
9795

    
9796
  def CheckPrereq(self):
9797
    """Check prerequisites.
9798

9799
    This checks the pattern passed for validity by compiling it.
9800

9801
    """
9802
    try:
9803
      self.re = re.compile(self.op.pattern)
9804
    except re.error, err:
9805
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9806
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9807

    
9808
  def Exec(self, feedback_fn):
9809
    """Returns the tag list.
9810

9811
    """
9812
    cfg = self.cfg
9813
    tgts = [("/cluster", cfg.GetClusterInfo())]
9814
    ilist = cfg.GetAllInstancesInfo().values()
9815
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9816
    nlist = cfg.GetAllNodesInfo().values()
9817
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9818
    results = []
9819
    for path, target in tgts:
9820
      for tag in target.GetTags():
9821
        if self.re.search(tag):
9822
          results.append((path, tag))
9823
    return results
9824

    
9825

    
9826
class LUAddTags(TagsLU):
9827
  """Sets a tag on a given object.
9828

9829
  """
9830
  _OP_PARAMS = [
9831
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9832
    # Name is only meaningful for nodes and instances
9833
    ("name", _NoDefault, _TMaybeString),
9834
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9835
    ]
9836
  REQ_BGL = False
9837

    
9838
  def CheckPrereq(self):
9839
    """Check prerequisites.
9840

9841
    This checks the type and length of the tag name and value.
9842

9843
    """
9844
    TagsLU.CheckPrereq(self)
9845
    for tag in self.op.tags:
9846
      objects.TaggableObject.ValidateTag(tag)
9847

    
9848
  def Exec(self, feedback_fn):
9849
    """Sets the tag.
9850

9851
    """
9852
    try:
9853
      for tag in self.op.tags:
9854
        self.target.AddTag(tag)
9855
    except errors.TagError, err:
9856
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9857
    self.cfg.Update(self.target, feedback_fn)
9858

    
9859

    
9860
class LUDelTags(TagsLU):
9861
  """Delete a list of tags from a given object.
9862

9863
  """
9864
  _OP_PARAMS = [
9865
    ("kind", _NoDefault, _TElemOf(constants.VALID_TAG_TYPES)),
9866
    # Name is only meaningful for nodes and instances
9867
    ("name", _NoDefault, _TMaybeString),
9868
    ("tags", _NoDefault, _TListOf(_TNonEmptyString)),
9869
    ]
9870
  REQ_BGL = False
9871

    
9872
  def CheckPrereq(self):
9873
    """Check prerequisites.
9874

9875
    This checks that we have the given tag.
9876

9877
    """
9878
    TagsLU.CheckPrereq(self)
9879
    for tag in self.op.tags:
9880
      objects.TaggableObject.ValidateTag(tag)
9881
    del_tags = frozenset(self.op.tags)
9882
    cur_tags = self.target.GetTags()
9883
    if not del_tags <= cur_tags:
9884
      diff_tags = del_tags - cur_tags
9885
      diff_names = ["'%s'" % tag for tag in diff_tags]
9886
      diff_names.sort()
9887
      raise errors.OpPrereqError("Tag(s) %s not found" %
9888
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9889

    
9890
  def Exec(self, feedback_fn):
9891
    """Remove the tag from the object.
9892

9893
    """
9894
    for tag in self.op.tags:
9895
      self.target.RemoveTag(tag)
9896
    self.cfg.Update(self.target, feedback_fn)
9897

    
9898

    
9899
class LUTestDelay(NoHooksLU):
9900
  """Sleep for a specified amount of time.
9901

9902
  This LU sleeps on the master and/or nodes for a specified amount of
9903
  time.
9904

9905
  """
9906
  _OP_PARAMS = [
9907
    ("duration", _NoDefault, _TFloat),
9908
    ("on_master", True, _TBool),
9909
    ("on_nodes", _EmptyList, _TListOf(_TNonEmptyString)),
9910
    ("repeat", 0, _TPositiveInt)
9911
    ]
9912
  REQ_BGL = False
9913

    
9914
  def ExpandNames(self):
9915
    """Expand names and set required locks.
9916

9917
    This expands the node list, if any.
9918

9919
    """
9920
    self.needed_locks = {}
9921
    if self.op.on_nodes:
9922
      # _GetWantedNodes can be used here, but is not always appropriate to use
9923
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9924
      # more information.
9925
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9926
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9927

    
9928
  def _TestDelay(self):
9929
    """Do the actual sleep.
9930

9931
    """
9932
    if self.op.on_master:
9933
      if not utils.TestDelay(self.op.duration):
9934
        raise errors.OpExecError("Error during master delay test")
9935
    if self.op.on_nodes:
9936
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9937
      for node, node_result in result.items():
9938
        node_result.Raise("Failure during rpc call to node %s" % node)
9939

    
9940
  def Exec(self, feedback_fn):
9941
    """Execute the test delay opcode, with the wanted repetitions.
9942

9943
    """
9944
    if self.op.repeat == 0:
9945
      self._TestDelay()
9946
    else:
9947
      top_value = self.op.repeat - 1
9948
      for i in range(self.op.repeat):
9949
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9950
        self._TestDelay()
9951

    
9952

    
9953
class LUTestJobqueue(NoHooksLU):
9954
  """Utility LU to test some aspects of the job queue.
9955

9956
  """
9957
  _OP_PARAMS = [
9958
    ("notify_waitlock", False, _TBool),
9959
    ("notify_exec", False, _TBool),
9960
    ("log_messages", _EmptyList, _TListOf(_TString)),
9961
    ("fail", False, _TBool),
9962
    ]
9963
  REQ_BGL = False
9964

    
9965
  # Must be lower than default timeout for WaitForJobChange to see whether it
9966
  # notices changed jobs
9967
  _CLIENT_CONNECT_TIMEOUT = 20.0
9968
  _CLIENT_CONFIRM_TIMEOUT = 60.0
9969

    
9970
  @classmethod
9971
  def _NotifyUsingSocket(cls, cb, errcls):
9972
    """Opens a Unix socket and waits for another program to connect.
9973

9974
    @type cb: callable
9975
    @param cb: Callback to send socket name to client
9976
    @type errcls: class
9977
    @param errcls: Exception class to use for errors
9978

9979
    """
9980
    # Using a temporary directory as there's no easy way to create temporary
9981
    # sockets without writing a custom loop around tempfile.mktemp and
9982
    # socket.bind
9983
    tmpdir = tempfile.mkdtemp()
9984
    try:
9985
      tmpsock = utils.PathJoin(tmpdir, "sock")
9986

    
9987
      logging.debug("Creating temporary socket at %s", tmpsock)
9988
      sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
9989
      try:
9990
        sock.bind(tmpsock)
9991
        sock.listen(1)
9992

    
9993
        # Send details to client
9994
        cb(tmpsock)
9995

    
9996
        # Wait for client to connect before continuing
9997
        sock.settimeout(cls._CLIENT_CONNECT_TIMEOUT)
9998
        try:
9999
          (conn, _) = sock.accept()
10000
        except socket.error, err:
10001
          raise errcls("Client didn't connect in time (%s)" % err)
10002
      finally:
10003
        sock.close()
10004
    finally:
10005
      # Remove as soon as client is connected
10006
      shutil.rmtree(tmpdir)
10007

    
10008
    # Wait for client to close
10009
    try:
10010
      try:
10011
        # pylint: disable-msg=E1101
10012
        # Instance of '_socketobject' has no ... member
10013
        conn.settimeout(cls._CLIENT_CONFIRM_TIMEOUT)
10014
        conn.recv(1)
10015
      except socket.error, err:
10016
        raise errcls("Client failed to confirm notification (%s)" % err)
10017
    finally:
10018
      conn.close()
10019

    
10020
  def _SendNotification(self, test, arg, sockname):
10021
    """Sends a notification to the client.
10022

10023
    @type test: string
10024
    @param test: Test name
10025
    @param arg: Test argument (depends on test)
10026
    @type sockname: string
10027
    @param sockname: Socket path
10028

10029
    """
10030
    self.Log(constants.ELOG_JQUEUE_TEST, (sockname, test, arg))
10031

    
10032
  def _Notify(self, prereq, test, arg):
10033
    """Notifies the client of a test.
10034

10035
    @type prereq: bool
10036
    @param prereq: Whether this is a prereq-phase test
10037
    @type test: string
10038
    @param test: Test name
10039
    @param arg: Test argument (depends on test)
10040

10041
    """
10042
    if prereq:
10043
      errcls = errors.OpPrereqError
10044
    else:
10045
      errcls = errors.OpExecError
10046

    
10047
    return self._NotifyUsingSocket(compat.partial(self._SendNotification,
10048
                                                  test, arg),
10049
                                   errcls)
10050

    
10051
  def CheckArguments(self):
10052
    self.checkargs_calls = getattr(self, "checkargs_calls", 0) + 1
10053
    self.expandnames_calls = 0
10054

    
10055
  def ExpandNames(self):
10056
    checkargs_calls = getattr(self, "checkargs_calls", 0)
10057
    if checkargs_calls < 1:
10058
      raise errors.ProgrammerError("CheckArguments was not called")
10059

    
10060
    self.expandnames_calls += 1
10061

    
10062
    if self.op.notify_waitlock:
10063
      self._Notify(True, constants.JQT_EXPANDNAMES, None)
10064

    
10065
    self.LogInfo("Expanding names")
10066

    
10067
    # Get lock on master node (just to get a lock, not for a particular reason)
10068
    self.needed_locks = {
10069
      locking.LEVEL_NODE: self.cfg.GetMasterNode(),
10070
      }
10071

    
10072
  def Exec(self, feedback_fn):
10073
    if self.expandnames_calls < 1:
10074
      raise errors.ProgrammerError("ExpandNames was not called")
10075

    
10076
    if self.op.notify_exec:
10077
      self._Notify(False, constants.JQT_EXEC, None)
10078

    
10079
    self.LogInfo("Executing")
10080

    
10081
    if self.op.log_messages:
10082
      self._Notify(False, constants.JQT_STARTMSG, len(self.op.log_messages))
10083
      for idx, msg in enumerate(self.op.log_messages):
10084
        self.LogInfo("Sending log message %s", idx + 1)
10085
        feedback_fn(constants.JQT_MSGPREFIX + msg)
10086
        # Report how many test messages have been sent
10087
        self._Notify(False, constants.JQT_LOGMSG, idx + 1)
10088

    
10089
    if self.op.fail:
10090
      raise errors.OpExecError("Opcode failure was requested")
10091

    
10092
    return True
10093

    
10094

    
10095
class IAllocator(object):
10096
  """IAllocator framework.
10097

10098
  An IAllocator instance has three sets of attributes:
10099
    - cfg that is needed to query the cluster
10100
    - input data (all members of the _KEYS class attribute are required)
10101
    - four buffer attributes (in|out_data|text), that represent the
10102
      input (to the external script) in text and data structure format,
10103
      and the output from it, again in two formats
10104
    - the result variables from the script (success, info, nodes) for
10105
      easy usage
10106

10107
  """
10108
  # pylint: disable-msg=R0902
10109
  # lots of instance attributes
10110
  _ALLO_KEYS = [
10111
    "name", "mem_size", "disks", "disk_template",
10112
    "os", "tags", "nics", "vcpus", "hypervisor",
10113
    ]
10114
  _RELO_KEYS = [
10115
    "name", "relocate_from",
10116
    ]
10117
  _EVAC_KEYS = [
10118
    "evac_nodes",
10119
    ]
10120

    
10121
  def __init__(self, cfg, rpc, mode, **kwargs):
10122
    self.cfg = cfg
10123
    self.rpc = rpc
10124
    # init buffer variables
10125
    self.in_text = self.out_text = self.in_data = self.out_data = None
10126
    # init all input fields so that pylint is happy
10127
    self.mode = mode
10128
    self.mem_size = self.disks = self.disk_template = None
10129
    self.os = self.tags = self.nics = self.vcpus = None
10130
    self.hypervisor = None
10131
    self.relocate_from = None
10132
    self.name = None
10133
    self.evac_nodes = None
10134
    # computed fields
10135
    self.required_nodes = None
10136
    # init result fields
10137
    self.success = self.info = self.result = None
10138
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10139
      keyset = self._ALLO_KEYS
10140
      fn = self._AddNewInstance
10141
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10142
      keyset = self._RELO_KEYS
10143
      fn = self._AddRelocateInstance
10144
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10145
      keyset = self._EVAC_KEYS
10146
      fn = self._AddEvacuateNodes
10147
    else:
10148
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
10149
                                   " IAllocator" % self.mode)
10150
    for key in kwargs:
10151
      if key not in keyset:
10152
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
10153
                                     " IAllocator" % key)
10154
      setattr(self, key, kwargs[key])
10155

    
10156
    for key in keyset:
10157
      if key not in kwargs:
10158
        raise errors.ProgrammerError("Missing input parameter '%s' to"
10159
                                     " IAllocator" % key)
10160
    self._BuildInputData(fn)
10161

    
10162
  def _ComputeClusterData(self):
10163
    """Compute the generic allocator input data.
10164

10165
    This is the data that is independent of the actual operation.
10166

10167
    """
10168
    cfg = self.cfg
10169
    cluster_info = cfg.GetClusterInfo()
10170
    # cluster data
10171
    data = {
10172
      "version": constants.IALLOCATOR_VERSION,
10173
      "cluster_name": cfg.GetClusterName(),
10174
      "cluster_tags": list(cluster_info.GetTags()),
10175
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
10176
      # we don't have job IDs
10177
      }
10178
    iinfo = cfg.GetAllInstancesInfo().values()
10179
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
10180

    
10181
    # node data
10182
    node_results = {}
10183
    node_list = cfg.GetNodeList()
10184

    
10185
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
10186
      hypervisor_name = self.hypervisor
10187
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
10188
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
10189
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
10190
      hypervisor_name = cluster_info.enabled_hypervisors[0]
10191

    
10192
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
10193
                                        hypervisor_name)
10194
    node_iinfo = \
10195
      self.rpc.call_all_instances_info(node_list,
10196
                                       cluster_info.enabled_hypervisors)
10197
    for nname, nresult in node_data.items():
10198
      # first fill in static (config-based) values
10199
      ninfo = cfg.GetNodeInfo(nname)
10200
      pnr = {
10201
        "tags": list(ninfo.GetTags()),
10202
        "primary_ip": ninfo.primary_ip,
10203
        "secondary_ip": ninfo.secondary_ip,
10204
        "offline": ninfo.offline,
10205
        "drained": ninfo.drained,
10206
        "master_candidate": ninfo.master_candidate,
10207
        }
10208

    
10209
      if not (ninfo.offline or ninfo.drained):
10210
        nresult.Raise("Can't get data for node %s" % nname)
10211
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
10212
                                nname)
10213
        remote_info = nresult.payload
10214

    
10215
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
10216
                     'vg_size', 'vg_free', 'cpu_total']:
10217
          if attr not in remote_info:
10218
            raise errors.OpExecError("Node '%s' didn't return attribute"
10219
                                     " '%s'" % (nname, attr))
10220
          if not isinstance(remote_info[attr], int):
10221
            raise errors.OpExecError("Node '%s' returned invalid value"
10222
                                     " for '%s': %s" %
10223
                                     (nname, attr, remote_info[attr]))
10224
        # compute memory used by primary instances
10225
        i_p_mem = i_p_up_mem = 0
10226
        for iinfo, beinfo in i_list:
10227
          if iinfo.primary_node == nname:
10228
            i_p_mem += beinfo[constants.BE_MEMORY]
10229
            if iinfo.name not in node_iinfo[nname].payload:
10230
              i_used_mem = 0
10231
            else:
10232
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
10233
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
10234
            remote_info['memory_free'] -= max(0, i_mem_diff)
10235

    
10236
            if iinfo.admin_up:
10237
              i_p_up_mem += beinfo[constants.BE_MEMORY]
10238

    
10239
        # compute memory used by instances
10240
        pnr_dyn = {
10241
          "total_memory": remote_info['memory_total'],
10242
          "reserved_memory": remote_info['memory_dom0'],
10243
          "free_memory": remote_info['memory_free'],
10244
          "total_disk": remote_info['vg_size'],
10245
          "free_disk": remote_info['vg_free'],
10246
          "total_cpus": remote_info['cpu_total'],
10247
          "i_pri_memory": i_p_mem,
10248
          "i_pri_up_memory": i_p_up_mem,
10249
          }
10250
        pnr.update(pnr_dyn)
10251

    
10252
      node_results[nname] = pnr
10253
    data["nodes"] = node_results
10254

    
10255
    # instance data
10256
    instance_data = {}
10257
    for iinfo, beinfo in i_list:
10258
      nic_data = []
10259
      for nic in iinfo.nics:
10260
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
10261
        nic_dict = {"mac": nic.mac,
10262
                    "ip": nic.ip,
10263
                    "mode": filled_params[constants.NIC_MODE],
10264
                    "link": filled_params[constants.NIC_LINK],
10265
                   }
10266
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
10267
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
10268
        nic_data.append(nic_dict)
10269
      pir = {
10270
        "tags": list(iinfo.GetTags()),
10271
        "admin_up": iinfo.admin_up,
10272
        "vcpus": beinfo[constants.BE_VCPUS],
10273
        "memory": beinfo[constants.BE_MEMORY],
10274
        "os": iinfo.os,
10275
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
10276
        "nics": nic_data,
10277
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
10278
        "disk_template": iinfo.disk_template,
10279
        "hypervisor": iinfo.hypervisor,
10280
        }
10281
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
10282
                                                 pir["disks"])
10283
      instance_data[iinfo.name] = pir
10284

    
10285
    data["instances"] = instance_data
10286

    
10287
    self.in_data = data
10288

    
10289
  def _AddNewInstance(self):
10290
    """Add new instance data to allocator structure.
10291

10292
    This in combination with _AllocatorGetClusterData will create the
10293
    correct structure needed as input for the allocator.
10294

10295
    The checks for the completeness of the opcode must have already been
10296
    done.
10297

10298
    """
10299
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
10300

    
10301
    if self.disk_template in constants.DTS_NET_MIRROR:
10302
      self.required_nodes = 2
10303
    else:
10304
      self.required_nodes = 1
10305
    request = {
10306
      "name": self.name,
10307
      "disk_template": self.disk_template,
10308
      "tags": self.tags,
10309
      "os": self.os,
10310
      "vcpus": self.vcpus,
10311
      "memory": self.mem_size,
10312
      "disks": self.disks,
10313
      "disk_space_total": disk_space,
10314
      "nics": self.nics,
10315
      "required_nodes": self.required_nodes,
10316
      }
10317
    return request
10318

    
10319
  def _AddRelocateInstance(self):
10320
    """Add relocate instance data to allocator structure.
10321

10322
    This in combination with _IAllocatorGetClusterData will create the
10323
    correct structure needed as input for the allocator.
10324

10325
    The checks for the completeness of the opcode must have already been
10326
    done.
10327

10328
    """
10329
    instance = self.cfg.GetInstanceInfo(self.name)
10330
    if instance is None:
10331
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10332
                                   " IAllocator" % self.name)
10333

    
10334
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10335
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10336
                                 errors.ECODE_INVAL)
10337

    
10338
    if len(instance.secondary_nodes) != 1:
10339
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10340
                                 errors.ECODE_STATE)
10341

    
10342
    self.required_nodes = 1
10343
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10344
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10345

    
10346
    request = {
10347
      "name": self.name,
10348
      "disk_space_total": disk_space,
10349
      "required_nodes": self.required_nodes,
10350
      "relocate_from": self.relocate_from,
10351
      }
10352
    return request
10353

    
10354
  def _AddEvacuateNodes(self):
10355
    """Add evacuate nodes data to allocator structure.
10356

10357
    """
10358
    request = {
10359
      "evac_nodes": self.evac_nodes
10360
      }
10361
    return request
10362

    
10363
  def _BuildInputData(self, fn):
10364
    """Build input data structures.
10365

10366
    """
10367
    self._ComputeClusterData()
10368

    
10369
    request = fn()
10370
    request["type"] = self.mode
10371
    self.in_data["request"] = request
10372

    
10373
    self.in_text = serializer.Dump(self.in_data)
10374

    
10375
  def Run(self, name, validate=True, call_fn=None):
10376
    """Run an instance allocator and return the results.
10377

10378
    """
10379
    if call_fn is None:
10380
      call_fn = self.rpc.call_iallocator_runner
10381

    
10382
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10383
    result.Raise("Failure while running the iallocator script")
10384

    
10385
    self.out_text = result.payload
10386
    if validate:
10387
      self._ValidateResult()
10388

    
10389
  def _ValidateResult(self):
10390
    """Process the allocator results.
10391

10392
    This will process and if successful save the result in
10393
    self.out_data and the other parameters.
10394

10395
    """
10396
    try:
10397
      rdict = serializer.Load(self.out_text)
10398
    except Exception, err:
10399
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10400

    
10401
    if not isinstance(rdict, dict):
10402
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10403

    
10404
    # TODO: remove backwards compatiblity in later versions
10405
    if "nodes" in rdict and "result" not in rdict:
10406
      rdict["result"] = rdict["nodes"]
10407
      del rdict["nodes"]
10408

    
10409
    for key in "success", "info", "result":
10410
      if key not in rdict:
10411
        raise errors.OpExecError("Can't parse iallocator results:"
10412
                                 " missing key '%s'" % key)
10413
      setattr(self, key, rdict[key])
10414

    
10415
    if not isinstance(rdict["result"], list):
10416
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10417
                               " is not a list")
10418
    self.out_data = rdict
10419

    
10420

    
10421
class LUTestAllocator(NoHooksLU):
10422
  """Run allocator tests.
10423

10424
  This LU runs the allocator tests
10425

10426
  """
10427
  _OP_PARAMS = [
10428
    ("direction", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10429
    ("mode", _NoDefault, _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10430
    ("name", _NoDefault, _TNonEmptyString),
10431
    ("nics", _NoDefault, _TOr(_TNone, _TListOf(
10432
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10433
               _TOr(_TNone, _TNonEmptyString))))),
10434
    ("disks", _NoDefault, _TOr(_TNone, _TList)),
10435
    ("hypervisor", None, _TMaybeString),
10436
    ("allocator", None, _TMaybeString),
10437
    ("tags", _EmptyList, _TListOf(_TNonEmptyString)),
10438
    ("mem_size", None, _TOr(_TNone, _TPositiveInt)),
10439
    ("vcpus", None, _TOr(_TNone, _TPositiveInt)),
10440
    ("os", None, _TMaybeString),
10441
    ("disk_template", None, _TMaybeString),
10442
    ("evac_nodes", None, _TOr(_TNone, _TListOf(_TNonEmptyString))),
10443
    ]
10444

    
10445
  def CheckPrereq(self):
10446
    """Check prerequisites.
10447

10448
    This checks the opcode parameters depending on the director and mode test.
10449

10450
    """
10451
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10452
      for attr in ["mem_size", "disks", "disk_template",
10453
                   "os", "tags", "nics", "vcpus"]:
10454
        if not hasattr(self.op, attr):
10455
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10456
                                     attr, errors.ECODE_INVAL)
10457
      iname = self.cfg.ExpandInstanceName(self.op.name)
10458
      if iname is not None:
10459
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10460
                                   iname, errors.ECODE_EXISTS)
10461
      if not isinstance(self.op.nics, list):
10462
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10463
                                   errors.ECODE_INVAL)
10464
      if not isinstance(self.op.disks, list):
10465
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10466
                                   errors.ECODE_INVAL)
10467
      for row in self.op.disks:
10468
        if (not isinstance(row, dict) or
10469
            "size" not in row or
10470
            not isinstance(row["size"], int) or
10471
            "mode" not in row or
10472
            row["mode"] not in ['r', 'w']):
10473
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10474
                                     " parameter", errors.ECODE_INVAL)
10475
      if self.op.hypervisor is None:
10476
        self.op.hypervisor = self.cfg.GetHypervisorType()
10477
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10478
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10479
      self.op.name = fname
10480
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10481
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10482
      if not hasattr(self.op, "evac_nodes"):
10483
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10484
                                   " opcode input", errors.ECODE_INVAL)
10485
    else:
10486
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10487
                                 self.op.mode, errors.ECODE_INVAL)
10488

    
10489
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10490
      if self.op.allocator is None:
10491
        raise errors.OpPrereqError("Missing allocator name",
10492
                                   errors.ECODE_INVAL)
10493
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10494
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10495
                                 self.op.direction, errors.ECODE_INVAL)
10496

    
10497
  def Exec(self, feedback_fn):
10498
    """Run the allocator test.
10499

10500
    """
10501
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10502
      ial = IAllocator(self.cfg, self.rpc,
10503
                       mode=self.op.mode,
10504
                       name=self.op.name,
10505
                       mem_size=self.op.mem_size,
10506
                       disks=self.op.disks,
10507
                       disk_template=self.op.disk_template,
10508
                       os=self.op.os,
10509
                       tags=self.op.tags,
10510
                       nics=self.op.nics,
10511
                       vcpus=self.op.vcpus,
10512
                       hypervisor=self.op.hypervisor,
10513
                       )
10514
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10515
      ial = IAllocator(self.cfg, self.rpc,
10516
                       mode=self.op.mode,
10517
                       name=self.op.name,
10518
                       relocate_from=list(self.relocate_from),
10519
                       )
10520
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10521
      ial = IAllocator(self.cfg, self.rpc,
10522
                       mode=self.op.mode,
10523
                       evac_nodes=self.op.evac_nodes)
10524
    else:
10525
      raise errors.ProgrammerError("Uncatched mode %s in"
10526
                                   " LUTestAllocator.Exec", self.op.mode)
10527

    
10528
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10529
      result = ial.in_text
10530
    else:
10531
      ial.Run(self.op.allocator, validate=False)
10532
      result = ial.out_text
10533
    return result