Statistics
| Branch: | Tag: | Revision:

root / lib / cmdlib.py @ 3d16a983

History | View | Annotate | Download (354.4 kB)

1
#
2
#
3

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

    
21

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

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

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

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

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

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

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

    
55

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

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

62
  """
63
  return []
64

    
65

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

69
  """
70
  return {}
71

    
72

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

    
76

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

    
80

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

85
  """
86
  return val is not None
87

    
88

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

92
  """
93
  return val is None
94

    
95

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

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

    
102

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

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

    
109

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

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

    
116

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

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

    
123

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

127
  """
128
  return bool(val)
129

    
130

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

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

    
137

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

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

    
145

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

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

    
152

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

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

    
162

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

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

    
171

    
172
# Type aliases
173

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

    
177

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

    
181

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

    
185

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

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

    
192

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

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

    
200

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

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

    
210

    
211
# Common opcode attributes
212

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

    
216

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

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

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

    
227

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

    
231

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

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

245
  Note that all commands require root permissions.
246

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

252
  """
253
  HPATH = None
254
  HTYPE = None
255
  _OP_REQP = []
256
  _OP_DEFS = []
257
  REQ_BGL = True
258

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

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

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

    
291
    # Tasklets
292
    self.tasklets = None
293

    
294
    for aname, aval in self._OP_DEFS:
295
      if not hasattr(self.op, aname):
296
        if callable(aval):
297
          dval = aval()
298
        else:
299
          dval = aval
300
        setattr(self.op, aname, dval)
301

    
302
    for attr_name, test in self._OP_REQP:
303
      if not hasattr(op, attr_name):
304
        raise errors.OpPrereqError("Required parameter '%s' missing" %
305
                                   attr_name, errors.ECODE_INVAL)
306
      attr_val = getattr(op, attr_name, None)
307
      if not callable(test):
308
        raise errors.ProgrammerError("Validation for parameter '%s' failed,"
309
                                     " given type is not a proper type (%s)" %
310
                                     (attr_name, test))
311
      if not test(attr_val):
312
        logging.error("OpCode %s, parameter %s, has invalid type %s/value %s",
313
                      self.op.OP_ID, attr_name, type(attr_val), attr_val)
314
        raise errors.OpPrereqError("Parameter '%s' has invalid type" %
315
                                   attr_name, errors.ECODE_INVAL)
316

    
317
    self.CheckArguments()
318

    
319
  def __GetSSH(self):
320
    """Returns the SshRunner object
321

322
    """
323
    if not self.__ssh:
324
      self.__ssh = ssh.SshRunner(self.cfg.GetClusterName())
325
    return self.__ssh
326

    
327
  ssh = property(fget=__GetSSH)
328

    
329
  def CheckArguments(self):
330
    """Check syntactic validity for the opcode arguments.
331

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

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

341
    The function is allowed to change the self.op attribute so that
342
    later methods can no longer worry about missing parameters.
343

344
    """
345
    pass
346

    
347
  def ExpandNames(self):
348
    """Expand names for this LU.
349

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

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

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

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

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

372
    Examples::
373

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

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

    
395
  def DeclareLocks(self, level):
396
    """Declare LU locking needs for a level
397

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

405
    This function is only called if you have something already set in
406
    self.needed_locks for the level.
407

408
    @param level: Locking level which is going to be locked
409
    @type level: member of ganeti.locking.LEVELS
410

411
    """
412

    
413
  def CheckPrereq(self):
414
    """Check prerequisites for this LU.
415

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

421
    The method should raise errors.OpPrereqError in case something is
422
    not fulfilled. Its return value is ignored.
423

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

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

    
436
  def Exec(self, feedback_fn):
437
    """Execute the LU.
438

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

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

    
451
  def BuildHooksEnv(self):
452
    """Build hooks environment for this LU.
453

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

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

465
    No nodes should be returned as an empty list (and not None).
466

467
    Note that if the HPATH for a LU class is None, this function will
468
    not be called.
469

470
    """
471
    raise NotImplementedError
472

    
473
  def HooksCallBack(self, phase, hook_results, feedback_fn, lu_result):
474
    """Notify the LU about the results of its hooks.
475

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

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

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

    
497
  def _ExpandAndLockInstance(self):
498
    """Helper function to expand and lock an instance.
499

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

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

    
516
  def _LockInstancesNodes(self, primary_only=False):
517
    """Helper function to declare instances' nodes for locking.
518

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

524
    It should be called from DeclareLocks, and for safety only works if
525
    self.recalculate_locks[locking.LEVEL_NODE] is set.
526

527
    In the future it may grow parameters to just lock some instance's nodes, or
528
    to just lock primaries or secondary nodes, if needed.
529

530
    If should be called in DeclareLocks in a way similar to::
531

532
      if level == locking.LEVEL_NODE:
533
        self._LockInstancesNodes()
534

535
    @type primary_only: boolean
536
    @param primary_only: only lock primary nodes of locked instances
537

538
    """
539
    assert locking.LEVEL_NODE in self.recalculate_locks, \
540
      "_LockInstancesNodes helper function called with no nodes to recalculate"
541

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

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

    
554
    if self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_REPLACE:
555
      self.needed_locks[locking.LEVEL_NODE] = wanted_nodes
556
    elif self.recalculate_locks[locking.LEVEL_NODE] == constants.LOCKS_APPEND:
557
      self.needed_locks[locking.LEVEL_NODE].extend(wanted_nodes)
558

    
559
    del self.recalculate_locks[locking.LEVEL_NODE]
560

    
561

    
562
class NoHooksLU(LogicalUnit): # pylint: disable-msg=W0223
563
  """Simple LU which runs no hooks.
564

565
  This LU is intended as a parent for other LogicalUnits which will
566
  run no hooks, in order to reduce duplicate code.
567

568
  """
569
  HPATH = None
570
  HTYPE = None
571

    
572
  def BuildHooksEnv(self):
573
    """Empty BuildHooksEnv for NoHooksLu.
574

575
    This just raises an error.
576

577
    """
578
    assert False, "BuildHooksEnv called for NoHooksLUs"
579

    
580

    
581
class Tasklet:
582
  """Tasklet base class.
583

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

588
  Subclasses must follow these rules:
589
    - Implement CheckPrereq
590
    - Implement Exec
591

592
  """
593
  def __init__(self, lu):
594
    self.lu = lu
595

    
596
    # Shortcuts
597
    self.cfg = lu.cfg
598
    self.rpc = lu.rpc
599

    
600
  def CheckPrereq(self):
601
    """Check prerequisites for this tasklets.
602

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

607
    The method should raise errors.OpPrereqError in case something is not
608
    fulfilled. Its return value is ignored.
609

610
    This method should also update all parameters to their canonical form if it
611
    hasn't been done before.
612

613
    """
614
    pass
615

    
616
  def Exec(self, feedback_fn):
617
    """Execute the tasklet.
618

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

623
    """
624
    raise NotImplementedError
625

    
626

    
627
def _GetWantedNodes(lu, nodes):
628
  """Returns list of checked and expanded node names.
629

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

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

    
643
  wanted = [_ExpandNodeName(lu.cfg, name) for name in nodes]
644
  return utils.NiceSort(wanted)
645

    
646

    
647
def _GetWantedInstances(lu, instances):
648
  """Returns list of checked and expanded instance names.
649

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

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

    
666

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

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

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

    
699

    
700
def _CheckOutputFields(static, dynamic, selected):
701
  """Checks whether all selected fields are valid.
702

703
  @type static: L{utils.FieldSet}
704
  @param static: static fields set
705
  @type dynamic: L{utils.FieldSet}
706
  @param dynamic: dynamic fields set
707

708
  """
709
  f = utils.FieldSet()
710
  f.Extend(static)
711
  f.Extend(dynamic)
712

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

    
718

    
719
def _CheckBooleanOpField(op, name):
720
  """Validates boolean opcode parameters.
721

722
  This will ensure that an opcode parameter is either a boolean value,
723
  or None (but that it always exists).
724

725
  """
726
  val = getattr(op, name, None)
727
  if not (val is None or isinstance(val, bool)):
728
    raise errors.OpPrereqError("Invalid boolean parameter '%s' (%s)" %
729
                               (name, str(val)), errors.ECODE_INVAL)
730
  setattr(op, name, val)
731

    
732

    
733
def _CheckGlobalHvParams(params):
734
  """Validates that given hypervisor params are not global ones.
735

736
  This will ensure that instances don't get customised versions of
737
  global params.
738

739
  """
740
  used_globals = constants.HVC_GLOBALS.intersection(params)
741
  if used_globals:
742
    msg = ("The following hypervisor parameters are global and cannot"
743
           " be customized at instance level, please modify them at"
744
           " cluster level: %s" % utils.CommaJoin(used_globals))
745
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
746

    
747

    
748
def _CheckNodeOnline(lu, node):
749
  """Ensure that a given node is online.
750

751
  @param lu: the LU on behalf of which we make the check
752
  @param node: the node to check
753
  @raise errors.OpPrereqError: if the node is offline
754

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

    
760

    
761
def _CheckNodeNotDrained(lu, node):
762
  """Ensure that a given node is not drained.
763

764
  @param lu: the LU on behalf of which we make the check
765
  @param node: the node to check
766
  @raise errors.OpPrereqError: if the node is drained
767

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

    
773

    
774
def _CheckNodeHasOS(lu, node, os_name, force_variant):
775
  """Ensure that a node supports a given OS.
776

777
  @param lu: the LU on behalf of which we make the check
778
  @param node: the node to check
779
  @param os_name: the OS to query about
780
  @param force_variant: whether to ignore variant errors
781
  @raise errors.OpPrereqError: if the node is not supporting the OS
782

783
  """
784
  result = lu.rpc.call_os_get(node, os_name)
785
  result.Raise("OS '%s' not in supported OS list for node %s" %
786
               (os_name, node),
787
               prereq=True, ecode=errors.ECODE_INVAL)
788
  if not force_variant:
789
    _CheckOSVariant(result.payload, os_name)
790

    
791

    
792
def _RequireFileStorage():
793
  """Checks that file storage is enabled.
794

795
  @raise errors.OpPrereqError: when file storage is disabled
796

797
  """
798
  if not constants.ENABLE_FILE_STORAGE:
799
    raise errors.OpPrereqError("File storage disabled at configure time",
800
                               errors.ECODE_INVAL)
801

    
802

    
803
def _CheckDiskTemplate(template):
804
  """Ensure a given disk template is valid.
805

806
  """
807
  if template not in constants.DISK_TEMPLATES:
808
    msg = ("Invalid disk template name '%s', valid templates are: %s" %
809
           (template, utils.CommaJoin(constants.DISK_TEMPLATES)))
810
    raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
811
  if template == constants.DT_FILE:
812
    _RequireFileStorage()
813

    
814

    
815
def _CheckStorageType(storage_type):
816
  """Ensure a given storage type is valid.
817

818
  """
819
  if storage_type not in constants.VALID_STORAGE_TYPES:
820
    raise errors.OpPrereqError("Unknown storage type: %s" % storage_type,
821
                               errors.ECODE_INVAL)
822
  if storage_type == constants.ST_FILE:
823
    _RequireFileStorage()
824
  return True
825

    
826

    
827
def _GetClusterDomainSecret():
828
  """Reads the cluster domain secret.
829

830
  """
831
  return utils.ReadOneLineFile(constants.CLUSTER_DOMAIN_SECRET_FILE,
832
                               strict=True)
833

    
834

    
835
def _CheckInstanceDown(lu, instance, reason):
836
  """Ensure that an instance is not running."""
837
  if instance.admin_up:
838
    raise errors.OpPrereqError("Instance %s is marked to be up, %s" %
839
                               (instance.name, reason), errors.ECODE_STATE)
840

    
841
  pnode = instance.primary_node
842
  ins_l = lu.rpc.call_instance_list([pnode], [instance.hypervisor])[pnode]
843
  ins_l.Raise("Can't contact node %s for instance information" % pnode,
844
              prereq=True, ecode=errors.ECODE_ENVIRON)
845

    
846
  if instance.name in ins_l.payload:
847
    raise errors.OpPrereqError("Instance %s is running, %s" %
848
                               (instance.name, reason), errors.ECODE_STATE)
849

    
850

    
851
def _ExpandItemName(fn, name, kind):
852
  """Expand an item name.
853

854
  @param fn: the function to use for expansion
855
  @param name: requested item name
856
  @param kind: text description ('Node' or 'Instance')
857
  @return: the resolved (full) name
858
  @raise errors.OpPrereqError: if the item is not found
859

860
  """
861
  full_name = fn(name)
862
  if full_name is None:
863
    raise errors.OpPrereqError("%s '%s' not known" % (kind, name),
864
                               errors.ECODE_NOENT)
865
  return full_name
866

    
867

    
868
def _ExpandNodeName(cfg, name):
869
  """Wrapper over L{_ExpandItemName} for nodes."""
870
  return _ExpandItemName(cfg.ExpandNodeName, name, "Node")
871

    
872

    
873
def _ExpandInstanceName(cfg, name):
874
  """Wrapper over L{_ExpandItemName} for instance."""
875
  return _ExpandItemName(cfg.ExpandInstanceName, name, "Instance")
876

    
877

    
878
def _BuildInstanceHookEnv(name, primary_node, secondary_nodes, os_type, status,
879
                          memory, vcpus, nics, disk_template, disks,
880
                          bep, hvp, hypervisor_name):
881
  """Builds instance related env variables for hooks
882

883
  This builds the hook environment from individual variables.
884

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

915
  """
916
  if status:
917
    str_status = "up"
918
  else:
919
    str_status = "down"
920
  env = {
921
    "OP_TARGET": name,
922
    "INSTANCE_NAME": name,
923
    "INSTANCE_PRIMARY": primary_node,
924
    "INSTANCE_SECONDARIES": " ".join(secondary_nodes),
925
    "INSTANCE_OS_TYPE": os_type,
926
    "INSTANCE_STATUS": str_status,
927
    "INSTANCE_MEMORY": memory,
928
    "INSTANCE_VCPUS": vcpus,
929
    "INSTANCE_DISK_TEMPLATE": disk_template,
930
    "INSTANCE_HYPERVISOR": hypervisor_name,
931
  }
932

    
933
  if nics:
934
    nic_count = len(nics)
935
    for idx, (ip, mac, mode, link) in enumerate(nics):
936
      if ip is None:
937
        ip = ""
938
      env["INSTANCE_NIC%d_IP" % idx] = ip
939
      env["INSTANCE_NIC%d_MAC" % idx] = mac
940
      env["INSTANCE_NIC%d_MODE" % idx] = mode
941
      env["INSTANCE_NIC%d_LINK" % idx] = link
942
      if mode == constants.NIC_MODE_BRIDGED:
943
        env["INSTANCE_NIC%d_BRIDGE" % idx] = link
944
  else:
945
    nic_count = 0
946

    
947
  env["INSTANCE_NIC_COUNT"] = nic_count
948

    
949
  if disks:
950
    disk_count = len(disks)
951
    for idx, (size, mode) in enumerate(disks):
952
      env["INSTANCE_DISK%d_SIZE" % idx] = size
953
      env["INSTANCE_DISK%d_MODE" % idx] = mode
954
  else:
955
    disk_count = 0
956

    
957
  env["INSTANCE_DISK_COUNT"] = disk_count
958

    
959
  for source, kind in [(bep, "BE"), (hvp, "HV")]:
960
    for key, value in source.items():
961
      env["INSTANCE_%s_%s" % (kind, key)] = value
962

    
963
  return env
964

    
965

    
966
def _NICListToTuple(lu, nics):
967
  """Build a list of nic information tuples.
968

969
  This list is suitable to be passed to _BuildInstanceHookEnv or as a return
970
  value in LUQueryInstanceData.
971

972
  @type lu:  L{LogicalUnit}
973
  @param lu: the logical unit on whose behalf we execute
974
  @type nics: list of L{objects.NIC}
975
  @param nics: list of nics to convert to hooks tuples
976

977
  """
978
  hooks_nics = []
979
  cluster = lu.cfg.GetClusterInfo()
980
  for nic in nics:
981
    ip = nic.ip
982
    mac = nic.mac
983
    filled_params = cluster.SimpleFillNIC(nic.nicparams)
984
    mode = filled_params[constants.NIC_MODE]
985
    link = filled_params[constants.NIC_LINK]
986
    hooks_nics.append((ip, mac, mode, link))
987
  return hooks_nics
988

    
989

    
990
def _BuildInstanceHookEnvByObject(lu, instance, override=None):
991
  """Builds instance related env variables for hooks from an object.
992

993
  @type lu: L{LogicalUnit}
994
  @param lu: the logical unit on whose behalf we execute
995
  @type instance: L{objects.Instance}
996
  @param instance: the instance for which we should build the
997
      environment
998
  @type override: dict
999
  @param override: dictionary with key/values that will override
1000
      our values
1001
  @rtype: dict
1002
  @return: the hook environment dictionary
1003

1004
  """
1005
  cluster = lu.cfg.GetClusterInfo()
1006
  bep = cluster.FillBE(instance)
1007
  hvp = cluster.FillHV(instance)
1008
  args = {
1009
    'name': instance.name,
1010
    'primary_node': instance.primary_node,
1011
    'secondary_nodes': instance.secondary_nodes,
1012
    'os_type': instance.os,
1013
    'status': instance.admin_up,
1014
    'memory': bep[constants.BE_MEMORY],
1015
    'vcpus': bep[constants.BE_VCPUS],
1016
    'nics': _NICListToTuple(lu, instance.nics),
1017
    'disk_template': instance.disk_template,
1018
    'disks': [(disk.size, disk.mode) for disk in instance.disks],
1019
    'bep': bep,
1020
    'hvp': hvp,
1021
    'hypervisor_name': instance.hypervisor,
1022
  }
1023
  if override:
1024
    args.update(override)
1025
  return _BuildInstanceHookEnv(**args) # pylint: disable-msg=W0142
1026

    
1027

    
1028
def _AdjustCandidatePool(lu, exceptions):
1029
  """Adjust the candidate pool after node operations.
1030

1031
  """
1032
  mod_list = lu.cfg.MaintainCandidatePool(exceptions)
1033
  if mod_list:
1034
    lu.LogInfo("Promoted nodes to master candidate role: %s",
1035
               utils.CommaJoin(node.name for node in mod_list))
1036
    for name in mod_list:
1037
      lu.context.ReaddNode(name)
1038
  mc_now, mc_max, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1039
  if mc_now > mc_max:
1040
    lu.LogInfo("Note: more nodes are candidates (%d) than desired (%d)" %
1041
               (mc_now, mc_max))
1042

    
1043

    
1044
def _DecideSelfPromotion(lu, exceptions=None):
1045
  """Decide whether I should promote myself as a master candidate.
1046

1047
  """
1048
  cp_size = lu.cfg.GetClusterInfo().candidate_pool_size
1049
  mc_now, mc_should, _ = lu.cfg.GetMasterCandidateStats(exceptions)
1050
  # the new node will increase mc_max with one, so:
1051
  mc_should = min(mc_should + 1, cp_size)
1052
  return mc_now < mc_should
1053

    
1054

    
1055
def _CheckNicsBridgesExist(lu, target_nics, target_node):
1056
  """Check that the brigdes needed by a list of nics exist.
1057

1058
  """
1059
  cluster = lu.cfg.GetClusterInfo()
1060
  paramslist = [cluster.SimpleFillNIC(nic.nicparams) for nic in target_nics]
1061
  brlist = [params[constants.NIC_LINK] for params in paramslist
1062
            if params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED]
1063
  if brlist:
1064
    result = lu.rpc.call_bridges_exist(target_node, brlist)
1065
    result.Raise("Error checking bridges on destination node '%s'" %
1066
                 target_node, prereq=True, ecode=errors.ECODE_ENVIRON)
1067

    
1068

    
1069
def _CheckInstanceBridgesExist(lu, instance, node=None):
1070
  """Check that the brigdes needed by an instance exist.
1071

1072
  """
1073
  if node is None:
1074
    node = instance.primary_node
1075
  _CheckNicsBridgesExist(lu, instance.nics, node)
1076

    
1077

    
1078
def _CheckOSVariant(os_obj, name):
1079
  """Check whether an OS name conforms to the os variants specification.
1080

1081
  @type os_obj: L{objects.OS}
1082
  @param os_obj: OS object to check
1083
  @type name: string
1084
  @param name: OS name passed by the user, to check for validity
1085

1086
  """
1087
  if not os_obj.supported_variants:
1088
    return
1089
  try:
1090
    variant = name.split("+", 1)[1]
1091
  except IndexError:
1092
    raise errors.OpPrereqError("OS name must include a variant",
1093
                               errors.ECODE_INVAL)
1094

    
1095
  if variant not in os_obj.supported_variants:
1096
    raise errors.OpPrereqError("Unsupported OS variant", errors.ECODE_INVAL)
1097

    
1098

    
1099
def _GetNodeInstancesInner(cfg, fn):
1100
  return [i for i in cfg.GetAllInstancesInfo().values() if fn(i)]
1101

    
1102

    
1103
def _GetNodeInstances(cfg, node_name):
1104
  """Returns a list of all primary and secondary instances on a node.
1105

1106
  """
1107

    
1108
  return _GetNodeInstancesInner(cfg, lambda inst: node_name in inst.all_nodes)
1109

    
1110

    
1111
def _GetNodePrimaryInstances(cfg, node_name):
1112
  """Returns primary instances on a node.
1113

1114
  """
1115
  return _GetNodeInstancesInner(cfg,
1116
                                lambda inst: node_name == inst.primary_node)
1117

    
1118

    
1119
def _GetNodeSecondaryInstances(cfg, node_name):
1120
  """Returns secondary instances on a node.
1121

1122
  """
1123
  return _GetNodeInstancesInner(cfg,
1124
                                lambda inst: node_name in inst.secondary_nodes)
1125

    
1126

    
1127
def _GetStorageTypeArgs(cfg, storage_type):
1128
  """Returns the arguments for a storage type.
1129

1130
  """
1131
  # Special case for file storage
1132
  if storage_type == constants.ST_FILE:
1133
    # storage.FileStorage wants a list of storage directories
1134
    return [[cfg.GetFileStorageDir()]]
1135

    
1136
  return []
1137

    
1138

    
1139
def _FindFaultyInstanceDisks(cfg, rpc, instance, node_name, prereq):
1140
  faulty = []
1141

    
1142
  for dev in instance.disks:
1143
    cfg.SetDiskID(dev, node_name)
1144

    
1145
  result = rpc.call_blockdev_getmirrorstatus(node_name, instance.disks)
1146
  result.Raise("Failed to get disk status from node %s" % node_name,
1147
               prereq=prereq, ecode=errors.ECODE_ENVIRON)
1148

    
1149
  for idx, bdev_status in enumerate(result.payload):
1150
    if bdev_status and bdev_status.ldisk_status == constants.LDS_FAULTY:
1151
      faulty.append(idx)
1152

    
1153
  return faulty
1154

    
1155

    
1156
class LUPostInitCluster(LogicalUnit):
1157
  """Logical unit for running hooks after cluster initialization.
1158

1159
  """
1160
  HPATH = "cluster-init"
1161
  HTYPE = constants.HTYPE_CLUSTER
1162
  _OP_REQP = []
1163

    
1164
  def BuildHooksEnv(self):
1165
    """Build hooks env.
1166

1167
    """
1168
    env = {"OP_TARGET": self.cfg.GetClusterName()}
1169
    mn = self.cfg.GetMasterNode()
1170
    return env, [], [mn]
1171

    
1172
  def Exec(self, feedback_fn):
1173
    """Nothing to do.
1174

1175
    """
1176
    return True
1177

    
1178

    
1179
class LUDestroyCluster(LogicalUnit):
1180
  """Logical unit for destroying the cluster.
1181

1182
  """
1183
  HPATH = "cluster-destroy"
1184
  HTYPE = constants.HTYPE_CLUSTER
1185
  _OP_REQP = []
1186

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

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

    
1194
  def CheckPrereq(self):
1195
    """Check prerequisites.
1196

1197
    This checks whether the cluster is empty.
1198

1199
    Any errors are signaled by raising errors.OpPrereqError.
1200

1201
    """
1202
    master = self.cfg.GetMasterNode()
1203

    
1204
    nodelist = self.cfg.GetNodeList()
1205
    if len(nodelist) != 1 or nodelist[0] != master:
1206
      raise errors.OpPrereqError("There are still %d node(s) in"
1207
                                 " this cluster." % (len(nodelist) - 1),
1208
                                 errors.ECODE_INVAL)
1209
    instancelist = self.cfg.GetInstanceList()
1210
    if instancelist:
1211
      raise errors.OpPrereqError("There are still %d instance(s) in"
1212
                                 " this cluster." % len(instancelist),
1213
                                 errors.ECODE_INVAL)
1214

    
1215
  def Exec(self, feedback_fn):
1216
    """Destroys the cluster.
1217

1218
    """
1219
    master = self.cfg.GetMasterNode()
1220
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
1221

    
1222
    # Run post hooks on master node before it's removed
1223
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
1224
    try:
1225
      hm.RunPhase(constants.HOOKS_PHASE_POST, [master])
1226
    except:
1227
      # pylint: disable-msg=W0702
1228
      self.LogWarning("Errors occurred running hooks on %s" % master)
1229

    
1230
    result = self.rpc.call_node_stop_master(master, False)
1231
    result.Raise("Could not disable the master role")
1232

    
1233
    if modify_ssh_setup:
1234
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
1235
      utils.CreateBackup(priv_key)
1236
      utils.CreateBackup(pub_key)
1237

    
1238
    return master
1239

    
1240

    
1241
def _VerifyCertificate(filename):
1242
  """Verifies a certificate for LUVerifyCluster.
1243

1244
  @type filename: string
1245
  @param filename: Path to PEM file
1246

1247
  """
1248
  try:
1249
    cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
1250
                                           utils.ReadFile(filename))
1251
  except Exception, err: # pylint: disable-msg=W0703
1252
    return (LUVerifyCluster.ETYPE_ERROR,
1253
            "Failed to load X509 certificate %s: %s" % (filename, err))
1254

    
1255
  (errcode, msg) = \
1256
    utils.VerifyX509Certificate(cert, constants.SSL_CERT_EXPIRATION_WARN,
1257
                                constants.SSL_CERT_EXPIRATION_ERROR)
1258

    
1259
  if msg:
1260
    fnamemsg = "While verifying %s: %s" % (filename, msg)
1261
  else:
1262
    fnamemsg = None
1263

    
1264
  if errcode is None:
1265
    return (None, fnamemsg)
1266
  elif errcode == utils.CERT_WARNING:
1267
    return (LUVerifyCluster.ETYPE_WARNING, fnamemsg)
1268
  elif errcode == utils.CERT_ERROR:
1269
    return (LUVerifyCluster.ETYPE_ERROR, fnamemsg)
1270

    
1271
  raise errors.ProgrammerError("Unhandled certificate error code %r" % errcode)
1272

    
1273

    
1274
class LUVerifyCluster(LogicalUnit):
1275
  """Verifies the cluster status.
1276

1277
  """
1278
  HPATH = "cluster-verify"
1279
  HTYPE = constants.HTYPE_CLUSTER
1280
  _OP_REQP = [
1281
    ("skip_checks", _TListOf(_TElemOf(constants.VERIFY_OPTIONAL_CHECKS))),
1282
    ("verbose", _TBool),
1283
    ("error_codes", _TBool),
1284
    ("debug_simulate_errors", _TBool),
1285
    ]
1286
  REQ_BGL = False
1287

    
1288
  TCLUSTER = "cluster"
1289
  TNODE = "node"
1290
  TINSTANCE = "instance"
1291

    
1292
  ECLUSTERCFG = (TCLUSTER, "ECLUSTERCFG")
1293
  ECLUSTERCERT = (TCLUSTER, "ECLUSTERCERT")
1294
  EINSTANCEBADNODE = (TINSTANCE, "EINSTANCEBADNODE")
1295
  EINSTANCEDOWN = (TINSTANCE, "EINSTANCEDOWN")
1296
  EINSTANCELAYOUT = (TINSTANCE, "EINSTANCELAYOUT")
1297
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1298
  EINSTANCEMISSINGDISK = (TINSTANCE, "EINSTANCEMISSINGDISK")
1299
  EINSTANCEWRONGNODE = (TINSTANCE, "EINSTANCEWRONGNODE")
1300
  ENODEDRBD = (TNODE, "ENODEDRBD")
1301
  ENODEFILECHECK = (TNODE, "ENODEFILECHECK")
1302
  ENODEHOOKS = (TNODE, "ENODEHOOKS")
1303
  ENODEHV = (TNODE, "ENODEHV")
1304
  ENODELVM = (TNODE, "ENODELVM")
1305
  ENODEN1 = (TNODE, "ENODEN1")
1306
  ENODENET = (TNODE, "ENODENET")
1307
  ENODEOS = (TNODE, "ENODEOS")
1308
  ENODEORPHANINSTANCE = (TNODE, "ENODEORPHANINSTANCE")
1309
  ENODEORPHANLV = (TNODE, "ENODEORPHANLV")
1310
  ENODERPC = (TNODE, "ENODERPC")
1311
  ENODESSH = (TNODE, "ENODESSH")
1312
  ENODEVERSION = (TNODE, "ENODEVERSION")
1313
  ENODESETUP = (TNODE, "ENODESETUP")
1314
  ENODETIME = (TNODE, "ENODETIME")
1315

    
1316
  ETYPE_FIELD = "code"
1317
  ETYPE_ERROR = "ERROR"
1318
  ETYPE_WARNING = "WARNING"
1319

    
1320
  class NodeImage(object):
1321
    """A class representing the logical and physical status of a node.
1322

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

1349
    """
1350
    def __init__(self, offline=False, name=None):
1351
      self.name = name
1352
      self.volumes = {}
1353
      self.instances = []
1354
      self.pinst = []
1355
      self.sinst = []
1356
      self.sbp = {}
1357
      self.mfree = 0
1358
      self.dfree = 0
1359
      self.offline = offline
1360
      self.rpc_fail = False
1361
      self.lvm_fail = False
1362
      self.hyp_fail = False
1363
      self.ghost = False
1364
      self.os_fail = False
1365
      self.oslist = {}
1366

    
1367
  def ExpandNames(self):
1368
    self.needed_locks = {
1369
      locking.LEVEL_NODE: locking.ALL_SET,
1370
      locking.LEVEL_INSTANCE: locking.ALL_SET,
1371
    }
1372
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
1373

    
1374
  def _Error(self, ecode, item, msg, *args, **kwargs):
1375
    """Format an error message.
1376

1377
    Based on the opcode's error_codes parameter, either format a
1378
    parseable error code, or a simpler error string.
1379

1380
    This must be called only from Exec and functions called from Exec.
1381

1382
    """
1383
    ltype = kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR)
1384
    itype, etxt = ecode
1385
    # first complete the msg
1386
    if args:
1387
      msg = msg % args
1388
    # then format the whole message
1389
    if self.op.error_codes:
1390
      msg = "%s:%s:%s:%s:%s" % (ltype, etxt, itype, item, msg)
1391
    else:
1392
      if item:
1393
        item = " " + item
1394
      else:
1395
        item = ""
1396
      msg = "%s: %s%s: %s" % (ltype, itype, item, msg)
1397
    # and finally report it via the feedback_fn
1398
    self._feedback_fn("  - %s" % msg)
1399

    
1400
  def _ErrorIf(self, cond, *args, **kwargs):
1401
    """Log an error message if the passed condition is True.
1402

1403
    """
1404
    cond = bool(cond) or self.op.debug_simulate_errors
1405
    if cond:
1406
      self._Error(*args, **kwargs)
1407
    # do not mark the operation as failed for WARN cases only
1408
    if kwargs.get(self.ETYPE_FIELD, self.ETYPE_ERROR) == self.ETYPE_ERROR:
1409
      self.bad = self.bad or cond
1410

    
1411
  def _VerifyNode(self, ninfo, nresult):
1412
    """Run multiple tests against a node.
1413

1414
    Test list:
1415

1416
      - compares ganeti version
1417
      - checks vg existence and size > 20G
1418
      - checks config file checksum
1419
      - checks ssh to other nodes
1420

1421
    @type ninfo: L{objects.Node}
1422
    @param ninfo: the node to check
1423
    @param nresult: the results from the node
1424
    @rtype: boolean
1425
    @return: whether overall this call was successful (and we can expect
1426
         reasonable values in the respose)
1427

1428
    """
1429
    node = ninfo.name
1430
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1431

    
1432
    # main result, nresult should be a non-empty dict
1433
    test = not nresult or not isinstance(nresult, dict)
1434
    _ErrorIf(test, self.ENODERPC, node,
1435
                  "unable to verify node: no data returned")
1436
    if test:
1437
      return False
1438

    
1439
    # compares ganeti version
1440
    local_version = constants.PROTOCOL_VERSION
1441
    remote_version = nresult.get("version", None)
1442
    test = not (remote_version and
1443
                isinstance(remote_version, (list, tuple)) and
1444
                len(remote_version) == 2)
1445
    _ErrorIf(test, self.ENODERPC, node,
1446
             "connection to node returned invalid data")
1447
    if test:
1448
      return False
1449

    
1450
    test = local_version != remote_version[0]
1451
    _ErrorIf(test, self.ENODEVERSION, node,
1452
             "incompatible protocol versions: master %s,"
1453
             " node %s", local_version, remote_version[0])
1454
    if test:
1455
      return False
1456

    
1457
    # node seems compatible, we can actually try to look into its results
1458

    
1459
    # full package version
1460
    self._ErrorIf(constants.RELEASE_VERSION != remote_version[1],
1461
                  self.ENODEVERSION, node,
1462
                  "software version mismatch: master %s, node %s",
1463
                  constants.RELEASE_VERSION, remote_version[1],
1464
                  code=self.ETYPE_WARNING)
1465

    
1466
    hyp_result = nresult.get(constants.NV_HYPERVISOR, None)
1467
    if isinstance(hyp_result, dict):
1468
      for hv_name, hv_result in hyp_result.iteritems():
1469
        test = hv_result is not None
1470
        _ErrorIf(test, self.ENODEHV, node,
1471
                 "hypervisor %s verify failure: '%s'", hv_name, hv_result)
1472

    
1473

    
1474
    test = nresult.get(constants.NV_NODESETUP,
1475
                           ["Missing NODESETUP results"])
1476
    _ErrorIf(test, self.ENODESETUP, node, "node setup error: %s",
1477
             "; ".join(test))
1478

    
1479
    return True
1480

    
1481
  def _VerifyNodeTime(self, ninfo, nresult,
1482
                      nvinfo_starttime, nvinfo_endtime):
1483
    """Check the node time.
1484

1485
    @type ninfo: L{objects.Node}
1486
    @param ninfo: the node to check
1487
    @param nresult: the remote results for the node
1488
    @param nvinfo_starttime: the start time of the RPC call
1489
    @param nvinfo_endtime: the end time of the RPC call
1490

1491
    """
1492
    node = ninfo.name
1493
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1494

    
1495
    ntime = nresult.get(constants.NV_TIME, None)
1496
    try:
1497
      ntime_merged = utils.MergeTime(ntime)
1498
    except (ValueError, TypeError):
1499
      _ErrorIf(True, self.ENODETIME, node, "Node returned invalid time")
1500
      return
1501

    
1502
    if ntime_merged < (nvinfo_starttime - constants.NODE_MAX_CLOCK_SKEW):
1503
      ntime_diff = "%.01fs" % abs(nvinfo_starttime - ntime_merged)
1504
    elif ntime_merged > (nvinfo_endtime + constants.NODE_MAX_CLOCK_SKEW):
1505
      ntime_diff = "%.01fs" % abs(ntime_merged - nvinfo_endtime)
1506
    else:
1507
      ntime_diff = None
1508

    
1509
    _ErrorIf(ntime_diff is not None, self.ENODETIME, node,
1510
             "Node time diverges by at least %s from master node time",
1511
             ntime_diff)
1512

    
1513
  def _VerifyNodeLVM(self, ninfo, nresult, vg_name):
1514
    """Check the node time.
1515

1516
    @type ninfo: L{objects.Node}
1517
    @param ninfo: the node to check
1518
    @param nresult: the remote results for the node
1519
    @param vg_name: the configured VG name
1520

1521
    """
1522
    if vg_name is None:
1523
      return
1524

    
1525
    node = ninfo.name
1526
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1527

    
1528
    # checks vg existence and size > 20G
1529
    vglist = nresult.get(constants.NV_VGLIST, None)
1530
    test = not vglist
1531
    _ErrorIf(test, self.ENODELVM, node, "unable to check volume groups")
1532
    if not test:
1533
      vgstatus = utils.CheckVolumeGroupSize(vglist, vg_name,
1534
                                            constants.MIN_VG_SIZE)
1535
      _ErrorIf(vgstatus, self.ENODELVM, node, vgstatus)
1536

    
1537
    # check pv names
1538
    pvlist = nresult.get(constants.NV_PVLIST, None)
1539
    test = pvlist is None
1540
    _ErrorIf(test, self.ENODELVM, node, "Can't get PV list from node")
1541
    if not test:
1542
      # check that ':' is not present in PV names, since it's a
1543
      # special character for lvcreate (denotes the range of PEs to
1544
      # use on the PV)
1545
      for _, pvname, owner_vg in pvlist:
1546
        test = ":" in pvname
1547
        _ErrorIf(test, self.ENODELVM, node, "Invalid character ':' in PV"
1548
                 " '%s' of VG '%s'", pvname, owner_vg)
1549

    
1550
  def _VerifyNodeNetwork(self, ninfo, nresult):
1551
    """Check the node time.
1552

1553
    @type ninfo: L{objects.Node}
1554
    @param ninfo: the node to check
1555
    @param nresult: the remote results for the node
1556

1557
    """
1558
    node = ninfo.name
1559
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1560

    
1561
    test = constants.NV_NODELIST not in nresult
1562
    _ErrorIf(test, self.ENODESSH, node,
1563
             "node hasn't returned node ssh connectivity data")
1564
    if not test:
1565
      if nresult[constants.NV_NODELIST]:
1566
        for a_node, a_msg in nresult[constants.NV_NODELIST].items():
1567
          _ErrorIf(True, self.ENODESSH, node,
1568
                   "ssh communication with node '%s': %s", a_node, a_msg)
1569

    
1570
    test = constants.NV_NODENETTEST not in nresult
1571
    _ErrorIf(test, self.ENODENET, node,
1572
             "node hasn't returned node tcp connectivity data")
1573
    if not test:
1574
      if nresult[constants.NV_NODENETTEST]:
1575
        nlist = utils.NiceSort(nresult[constants.NV_NODENETTEST].keys())
1576
        for anode in nlist:
1577
          _ErrorIf(True, self.ENODENET, node,
1578
                   "tcp communication with node '%s': %s",
1579
                   anode, nresult[constants.NV_NODENETTEST][anode])
1580

    
1581
    test = constants.NV_MASTERIP not in nresult
1582
    _ErrorIf(test, self.ENODENET, node,
1583
             "node hasn't returned node master IP reachability data")
1584
    if not test:
1585
      if not nresult[constants.NV_MASTERIP]:
1586
        if node == self.master_node:
1587
          msg = "the master node cannot reach the master IP (not configured?)"
1588
        else:
1589
          msg = "cannot reach the master IP"
1590
        _ErrorIf(True, self.ENODENET, node, msg)
1591

    
1592

    
1593
  def _VerifyInstance(self, instance, instanceconfig, node_image):
1594
    """Verify an instance.
1595

1596
    This function checks to see if the required block devices are
1597
    available on the instance's node.
1598

1599
    """
1600
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1601
    node_current = instanceconfig.primary_node
1602

    
1603
    node_vol_should = {}
1604
    instanceconfig.MapLVsByNode(node_vol_should)
1605

    
1606
    for node in node_vol_should:
1607
      n_img = node_image[node]
1608
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1609
        # ignore missing volumes on offline or broken nodes
1610
        continue
1611
      for volume in node_vol_should[node]:
1612
        test = volume not in n_img.volumes
1613
        _ErrorIf(test, self.EINSTANCEMISSINGDISK, instance,
1614
                 "volume %s missing on node %s", volume, node)
1615

    
1616
    if instanceconfig.admin_up:
1617
      pri_img = node_image[node_current]
1618
      test = instance not in pri_img.instances and not pri_img.offline
1619
      _ErrorIf(test, self.EINSTANCEDOWN, instance,
1620
               "instance not running on its primary node %s",
1621
               node_current)
1622

    
1623
    for node, n_img in node_image.items():
1624
      if (not node == node_current):
1625
        test = instance in n_img.instances
1626
        _ErrorIf(test, self.EINSTANCEWRONGNODE, instance,
1627
                 "instance should not run on node %s", node)
1628

    
1629
  def _VerifyOrphanVolumes(self, node_vol_should, node_image):
1630
    """Verify if there are any unknown volumes in the cluster.
1631

1632
    The .os, .swap and backup volumes are ignored. All other volumes are
1633
    reported as unknown.
1634

1635
    """
1636
    for node, n_img in node_image.items():
1637
      if n_img.offline or n_img.rpc_fail or n_img.lvm_fail:
1638
        # skip non-healthy nodes
1639
        continue
1640
      for volume in n_img.volumes:
1641
        test = (node not in node_vol_should or
1642
                volume not in node_vol_should[node])
1643
        self._ErrorIf(test, self.ENODEORPHANLV, node,
1644
                      "volume %s is unknown", volume)
1645

    
1646
  def _VerifyOrphanInstances(self, instancelist, node_image):
1647
    """Verify the list of running instances.
1648

1649
    This checks what instances are running but unknown to the cluster.
1650

1651
    """
1652
    for node, n_img in node_image.items():
1653
      for o_inst in n_img.instances:
1654
        test = o_inst not in instancelist
1655
        self._ErrorIf(test, self.ENODEORPHANINSTANCE, node,
1656
                      "instance %s on node %s should not exist", o_inst, node)
1657

    
1658
  def _VerifyNPlusOneMemory(self, node_image, instance_cfg):
1659
    """Verify N+1 Memory Resilience.
1660

1661
    Check that if one single node dies we can still start all the
1662
    instances it was primary for.
1663

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

    
1685
  def _VerifyNodeFiles(self, ninfo, nresult, file_list, local_cksum,
1686
                       master_files):
1687
    """Verifies and computes the node required file checksums.
1688

1689
    @type ninfo: L{objects.Node}
1690
    @param ninfo: the node to check
1691
    @param nresult: the remote results for the node
1692
    @param file_list: required list of files
1693
    @param local_cksum: dictionary of local files and their checksums
1694
    @param master_files: list of files that only masters should have
1695

1696
    """
1697
    node = ninfo.name
1698
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1699

    
1700
    remote_cksum = nresult.get(constants.NV_FILELIST, None)
1701
    test = not isinstance(remote_cksum, dict)
1702
    _ErrorIf(test, self.ENODEFILECHECK, node,
1703
             "node hasn't returned file checksum data")
1704
    if test:
1705
      return
1706

    
1707
    for file_name in file_list:
1708
      node_is_mc = ninfo.master_candidate
1709
      must_have = (file_name not in master_files) or node_is_mc
1710
      # missing
1711
      test1 = file_name not in remote_cksum
1712
      # invalid checksum
1713
      test2 = not test1 and remote_cksum[file_name] != local_cksum[file_name]
1714
      # existing and good
1715
      test3 = not test1 and remote_cksum[file_name] == local_cksum[file_name]
1716
      _ErrorIf(test1 and must_have, self.ENODEFILECHECK, node,
1717
               "file '%s' missing", file_name)
1718
      _ErrorIf(test2 and must_have, self.ENODEFILECHECK, node,
1719
               "file '%s' has wrong checksum", file_name)
1720
      # not candidate and this is not a must-have file
1721
      _ErrorIf(test2 and not must_have, self.ENODEFILECHECK, node,
1722
               "file '%s' should not exist on non master"
1723
               " candidates (and the file is outdated)", file_name)
1724
      # all good, except non-master/non-must have combination
1725
      _ErrorIf(test3 and not must_have, self.ENODEFILECHECK, node,
1726
               "file '%s' should not exist"
1727
               " on non master candidates", file_name)
1728

    
1729
  def _VerifyNodeDrbd(self, ninfo, nresult, instanceinfo, drbd_map):
1730
    """Verifies and the node DRBD status.
1731

1732
    @type ninfo: L{objects.Node}
1733
    @param ninfo: the node to check
1734
    @param nresult: the remote results for the node
1735
    @param instanceinfo: the dict of instances
1736
    @param drbd_map: the DRBD map as returned by
1737
        L{ganeti.config.ConfigWriter.ComputeDRBDMap}
1738

1739
    """
1740
    node = ninfo.name
1741
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1742

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

    
1758
    # and now check them
1759
    used_minors = nresult.get(constants.NV_DRBDLIST, [])
1760
    test = not isinstance(used_minors, (tuple, list))
1761
    _ErrorIf(test, self.ENODEDRBD, node,
1762
             "cannot parse drbd status file: %s", str(used_minors))
1763
    if test:
1764
      # we cannot check drbd status
1765
      return
1766

    
1767
    for minor, (iname, must_exist) in node_drbd.items():
1768
      test = minor not in used_minors and must_exist
1769
      _ErrorIf(test, self.ENODEDRBD, node,
1770
               "drbd minor %d of instance %s is not active", minor, iname)
1771
    for minor in used_minors:
1772
      test = minor not in node_drbd
1773
      _ErrorIf(test, self.ENODEDRBD, node,
1774
               "unallocated drbd minor %d is in use", minor)
1775

    
1776
  def _UpdateNodeOS(self, ninfo, nresult, nimg):
1777
    """Builds the node OS structures.
1778

1779
    @type ninfo: L{objects.Node}
1780
    @param ninfo: the node to check
1781
    @param nresult: the remote results for the node
1782
    @param nimg: the node image object
1783

1784
    """
1785
    node = ninfo.name
1786
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1787

    
1788
    remote_os = nresult.get(constants.NV_OSLIST, None)
1789
    test = (not isinstance(remote_os, list) or
1790
            not compat.all(isinstance(v, list) and len(v) == 7
1791
                           for v in remote_os))
1792

    
1793
    _ErrorIf(test, self.ENODEOS, node,
1794
             "node hasn't returned valid OS data")
1795

    
1796
    nimg.os_fail = test
1797

    
1798
    if test:
1799
      return
1800

    
1801
    os_dict = {}
1802

    
1803
    for (name, os_path, status, diagnose,
1804
         variants, parameters, api_ver) in nresult[constants.NV_OSLIST]:
1805

    
1806
      if name not in os_dict:
1807
        os_dict[name] = []
1808

    
1809
      # parameters is a list of lists instead of list of tuples due to
1810
      # JSON lacking a real tuple type, fix it:
1811
      parameters = [tuple(v) for v in parameters]
1812
      os_dict[name].append((os_path, status, diagnose,
1813
                            set(variants), set(parameters), set(api_ver)))
1814

    
1815
    nimg.oslist = os_dict
1816

    
1817
  def _VerifyNodeOS(self, ninfo, nimg, base):
1818
    """Verifies the node OS list.
1819

1820
    @type ninfo: L{objects.Node}
1821
    @param ninfo: the node to check
1822
    @param nimg: the node image object
1823
    @param base: the 'template' node we match against (e.g. from the master)
1824

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

    
1829
    assert not nimg.os_fail, "Entered _VerifyNodeOS with failed OS rpc?"
1830

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

    
1864
    # check any missing OSes
1865
    missing = set(base.oslist.keys()).difference(nimg.oslist.keys())
1866
    _ErrorIf(missing, self.ENODEOS, node,
1867
             "OSes present on reference node %s but missing on this node: %s",
1868
             base.name, utils.CommaJoin(missing))
1869

    
1870
  def _UpdateNodeVolumes(self, ninfo, nresult, nimg, vg_name):
1871
    """Verifies and updates the node volume data.
1872

1873
    This function will update a L{NodeImage}'s internal structures
1874
    with data from the remote call.
1875

1876
    @type ninfo: L{objects.Node}
1877
    @param ninfo: the node to check
1878
    @param nresult: the remote results for the node
1879
    @param nimg: the node image object
1880
    @param vg_name: the configured VG name
1881

1882
    """
1883
    node = ninfo.name
1884
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1885

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

    
1899
  def _UpdateNodeInstances(self, ninfo, nresult, nimg):
1900
    """Verifies and updates the node instance list.
1901

1902
    If the listing was successful, then updates this node's instance
1903
    list. Otherwise, it marks the RPC call as failed for the instance
1904
    list key.
1905

1906
    @type ninfo: L{objects.Node}
1907
    @param ninfo: the node to check
1908
    @param nresult: the remote results for the node
1909
    @param nimg: the node image object
1910

1911
    """
1912
    idata = nresult.get(constants.NV_INSTANCELIST, None)
1913
    test = not isinstance(idata, list)
1914
    self._ErrorIf(test, self.ENODEHV, ninfo.name, "rpc call to node failed"
1915
                  " (instancelist): %s", utils.SafeEncode(str(idata)))
1916
    if test:
1917
      nimg.hyp_fail = True
1918
    else:
1919
      nimg.instances = idata
1920

    
1921
  def _UpdateNodeInfo(self, ninfo, nresult, nimg, vg_name):
1922
    """Verifies and computes a node information map
1923

1924
    @type ninfo: L{objects.Node}
1925
    @param ninfo: the node to check
1926
    @param nresult: the remote results for the node
1927
    @param nimg: the node image object
1928
    @param vg_name: the configured VG name
1929

1930
    """
1931
    node = ninfo.name
1932
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1933

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

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

    
1959
  def BuildHooksEnv(self):
1960
    """Build hooks env.
1961

1962
    Cluster-Verify hooks just ran in the post phase and their failure makes
1963
    the output be logged in the verify output and the verification to fail.
1964

1965
    """
1966
    all_nodes = self.cfg.GetNodeList()
1967
    env = {
1968
      "CLUSTER_TAGS": " ".join(self.cfg.GetClusterInfo().GetTags())
1969
      }
1970
    for node in self.cfg.GetAllNodesInfo().values():
1971
      env["NODE_TAGS_%s" % node.name] = " ".join(node.GetTags())
1972

    
1973
    return env, [], all_nodes
1974

    
1975
  def Exec(self, feedback_fn):
1976
    """Verify integrity of cluster, performing various test on nodes.
1977

1978
    """
1979
    self.bad = False
1980
    _ErrorIf = self._ErrorIf # pylint: disable-msg=C0103
1981
    verbose = self.op.verbose
1982
    self._feedback_fn = feedback_fn
1983
    feedback_fn("* Verifying global settings")
1984
    for msg in self.cfg.VerifyConfig():
1985
      _ErrorIf(True, self.ECLUSTERCFG, None, msg)
1986

    
1987
    # Check the cluster certificates
1988
    for cert_filename in constants.ALL_CERT_FILES:
1989
      (errcode, msg) = _VerifyCertificate(cert_filename)
1990
      _ErrorIf(errcode, self.ECLUSTERCERT, None, msg, code=errcode)
1991

    
1992
    vg_name = self.cfg.GetVGName()
1993
    hypervisors = self.cfg.GetClusterInfo().enabled_hypervisors
1994
    cluster = self.cfg.GetClusterInfo()
1995
    nodelist = utils.NiceSort(self.cfg.GetNodeList())
1996
    nodeinfo = [self.cfg.GetNodeInfo(nname) for nname in nodelist]
1997
    instancelist = utils.NiceSort(self.cfg.GetInstanceList())
1998
    instanceinfo = dict((iname, self.cfg.GetInstanceInfo(iname))
1999
                        for iname in instancelist)
2000
    i_non_redundant = [] # Non redundant instances
2001
    i_non_a_balanced = [] # Non auto-balanced instances
2002
    n_offline = 0 # Count of offline nodes
2003
    n_drained = 0 # Count of nodes being drained
2004
    node_vol_should = {}
2005

    
2006
    # FIXME: verify OS list
2007
    # do local checksums
2008
    master_files = [constants.CLUSTER_CONF_FILE]
2009
    master_node = self.master_node = self.cfg.GetMasterNode()
2010
    master_ip = self.cfg.GetMasterIP()
2011

    
2012
    file_names = ssconf.SimpleStore().GetFileList()
2013
    file_names.extend(constants.ALL_CERT_FILES)
2014
    file_names.extend(master_files)
2015
    if cluster.modify_etc_hosts:
2016
      file_names.append(constants.ETC_HOSTS)
2017

    
2018
    local_checksums = utils.FingerprintFiles(file_names)
2019

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

    
2038
    if vg_name is not None:
2039
      node_verify_param[constants.NV_VGLIST] = None
2040
      node_verify_param[constants.NV_LVLIST] = vg_name
2041
      node_verify_param[constants.NV_PVLIST] = [vg_name]
2042
      node_verify_param[constants.NV_DRBDLIST] = None
2043

    
2044
    # Build our expected cluster state
2045
    node_image = dict((node.name, self.NodeImage(offline=node.offline,
2046
                                                 name=node.name))
2047
                      for node in nodeinfo)
2048

    
2049
    for instance in instancelist:
2050
      inst_config = instanceinfo[instance]
2051

    
2052
      for nname in inst_config.all_nodes:
2053
        if nname not in node_image:
2054
          # ghost node
2055
          gnode = self.NodeImage(name=nname)
2056
          gnode.ghost = True
2057
          node_image[nname] = gnode
2058

    
2059
      inst_config.MapLVsByNode(node_vol_should)
2060

    
2061
      pnode = inst_config.primary_node
2062
      node_image[pnode].pinst.append(instance)
2063

    
2064
      for snode in inst_config.secondary_nodes:
2065
        nimg = node_image[snode]
2066
        nimg.sinst.append(instance)
2067
        if pnode not in nimg.sbp:
2068
          nimg.sbp[pnode] = []
2069
        nimg.sbp[pnode].append(instance)
2070

    
2071
    # At this point, we have the in-memory data structures complete,
2072
    # except for the runtime information, which we'll gather next
2073

    
2074
    # Due to the way our RPC system works, exact response times cannot be
2075
    # guaranteed (e.g. a broken node could run into a timeout). By keeping the
2076
    # time before and after executing the request, we can at least have a time
2077
    # window.
2078
    nvinfo_starttime = time.time()
2079
    all_nvinfo = self.rpc.call_node_verify(nodelist, node_verify_param,
2080
                                           self.cfg.GetClusterName())
2081
    nvinfo_endtime = time.time()
2082

    
2083
    all_drbd_map = self.cfg.ComputeDRBDMap()
2084

    
2085
    feedback_fn("* Verifying node status")
2086

    
2087
    refos_img = None
2088

    
2089
    for node_i in nodeinfo:
2090
      node = node_i.name
2091
      nimg = node_image[node]
2092

    
2093
      if node_i.offline:
2094
        if verbose:
2095
          feedback_fn("* Skipping offline node %s" % (node,))
2096
        n_offline += 1
2097
        continue
2098

    
2099
      if node == master_node:
2100
        ntype = "master"
2101
      elif node_i.master_candidate:
2102
        ntype = "master candidate"
2103
      elif node_i.drained:
2104
        ntype = "drained"
2105
        n_drained += 1
2106
      else:
2107
        ntype = "regular"
2108
      if verbose:
2109
        feedback_fn("* Verifying node %s (%s)" % (node, ntype))
2110

    
2111
      msg = all_nvinfo[node].fail_msg
2112
      _ErrorIf(msg, self.ENODERPC, node, "while contacting node: %s", msg)
2113
      if msg:
2114
        nimg.rpc_fail = True
2115
        continue
2116

    
2117
      nresult = all_nvinfo[node].payload
2118

    
2119
      nimg.call_ok = self._VerifyNode(node_i, nresult)
2120
      self._VerifyNodeNetwork(node_i, nresult)
2121
      self._VerifyNodeLVM(node_i, nresult, vg_name)
2122
      self._VerifyNodeFiles(node_i, nresult, file_names, local_checksums,
2123
                            master_files)
2124
      self._VerifyNodeDrbd(node_i, nresult, instanceinfo, all_drbd_map)
2125
      self._VerifyNodeTime(node_i, nresult, nvinfo_starttime, nvinfo_endtime)
2126

    
2127
      self._UpdateNodeVolumes(node_i, nresult, nimg, vg_name)
2128
      self._UpdateNodeInstances(node_i, nresult, nimg)
2129
      self._UpdateNodeInfo(node_i, nresult, nimg, vg_name)
2130
      self._UpdateNodeOS(node_i, nresult, nimg)
2131
      if not nimg.os_fail:
2132
        if refos_img is None:
2133
          refos_img = nimg
2134
        self._VerifyNodeOS(node_i, nimg, refos_img)
2135

    
2136
    feedback_fn("* Verifying instance status")
2137
    for instance in instancelist:
2138
      if verbose:
2139
        feedback_fn("* Verifying instance %s" % instance)
2140
      inst_config = instanceinfo[instance]
2141
      self._VerifyInstance(instance, inst_config, node_image)
2142
      inst_nodes_offline = []
2143

    
2144
      pnode = inst_config.primary_node
2145
      pnode_img = node_image[pnode]
2146
      _ErrorIf(pnode_img.rpc_fail and not pnode_img.offline,
2147
               self.ENODERPC, pnode, "instance %s, connection to"
2148
               " primary node failed", instance)
2149

    
2150
      if pnode_img.offline:
2151
        inst_nodes_offline.append(pnode)
2152

    
2153
      # If the instance is non-redundant we cannot survive losing its primary
2154
      # node, so we are not N+1 compliant. On the other hand we have no disk
2155
      # templates with more than one secondary so that situation is not well
2156
      # supported either.
2157
      # FIXME: does not support file-backed instances
2158
      if not inst_config.secondary_nodes:
2159
        i_non_redundant.append(instance)
2160
      _ErrorIf(len(inst_config.secondary_nodes) > 1, self.EINSTANCELAYOUT,
2161
               instance, "instance has multiple secondary nodes: %s",
2162
               utils.CommaJoin(inst_config.secondary_nodes),
2163
               code=self.ETYPE_WARNING)
2164

    
2165
      if not cluster.FillBE(inst_config)[constants.BE_AUTO_BALANCE]:
2166
        i_non_a_balanced.append(instance)
2167

    
2168
      for snode in inst_config.secondary_nodes:
2169
        s_img = node_image[snode]
2170
        _ErrorIf(s_img.rpc_fail and not s_img.offline, self.ENODERPC, snode,
2171
                 "instance %s, connection to secondary node failed", instance)
2172

    
2173
        if s_img.offline:
2174
          inst_nodes_offline.append(snode)
2175

    
2176
      # warn that the instance lives on offline nodes
2177
      _ErrorIf(inst_nodes_offline, self.EINSTANCEBADNODE, instance,
2178
               "instance lives on offline node(s) %s",
2179
               utils.CommaJoin(inst_nodes_offline))
2180
      # ... or ghost nodes
2181
      for node in inst_config.all_nodes:
2182
        _ErrorIf(node_image[node].ghost, self.EINSTANCEBADNODE, instance,
2183
                 "instance lives on ghost node %s", node)
2184

    
2185
    feedback_fn("* Verifying orphan volumes")
2186
    self._VerifyOrphanVolumes(node_vol_should, node_image)
2187

    
2188
    feedback_fn("* Verifying orphan instances")
2189
    self._VerifyOrphanInstances(instancelist, node_image)
2190

    
2191
    if constants.VERIFY_NPLUSONE_MEM not in self.op.skip_checks:
2192
      feedback_fn("* Verifying N+1 Memory redundancy")
2193
      self._VerifyNPlusOneMemory(node_image, instanceinfo)
2194

    
2195
    feedback_fn("* Other Notes")
2196
    if i_non_redundant:
2197
      feedback_fn("  - NOTICE: %d non-redundant instance(s) found."
2198
                  % len(i_non_redundant))
2199

    
2200
    if i_non_a_balanced:
2201
      feedback_fn("  - NOTICE: %d non-auto-balanced instance(s) found."
2202
                  % len(i_non_a_balanced))
2203

    
2204
    if n_offline:
2205
      feedback_fn("  - NOTICE: %d offline node(s) found." % n_offline)
2206

    
2207
    if n_drained:
2208
      feedback_fn("  - NOTICE: %d drained node(s) found." % n_drained)
2209

    
2210
    return not self.bad
2211

    
2212
  def HooksCallBack(self, phase, hooks_results, feedback_fn, lu_result):
2213
    """Analyze the post-hooks' result
2214

2215
    This method analyses the hook result, handles it, and sends some
2216
    nicely-formatted feedback back to the user.
2217

2218
    @param phase: one of L{constants.HOOKS_PHASE_POST} or
2219
        L{constants.HOOKS_PHASE_PRE}; it denotes the hooks phase
2220
    @param hooks_results: the results of the multi-node hooks rpc call
2221
    @param feedback_fn: function used send feedback back to the caller
2222
    @param lu_result: previous Exec result
2223
    @return: the new Exec result, based on the previous result
2224
        and hook results
2225

2226
    """
2227
    # We only really run POST phase hooks, and are only interested in
2228
    # their results
2229
    if phase == constants.HOOKS_PHASE_POST:
2230
      # Used to change hooks' output to proper indentation
2231
      indent_re = re.compile('^', re.M)
2232
      feedback_fn("* Hooks Results")
2233
      assert hooks_results, "invalid result from hooks"
2234

    
2235
      for node_name in hooks_results:
2236
        res = hooks_results[node_name]
2237
        msg = res.fail_msg
2238
        test = msg and not res.offline
2239
        self._ErrorIf(test, self.ENODEHOOKS, node_name,
2240
                      "Communication failure in hooks execution: %s", msg)
2241
        if res.offline or msg:
2242
          # No need to investigate payload if node is offline or gave an error.
2243
          # override manually lu_result here as _ErrorIf only
2244
          # overrides self.bad
2245
          lu_result = 1
2246
          continue
2247
        for script, hkr, output in res.payload:
2248
          test = hkr == constants.HKR_FAIL
2249
          self._ErrorIf(test, self.ENODEHOOKS, node_name,
2250
                        "Script %s failed, output:", script)
2251
          if test:
2252
            output = indent_re.sub('      ', output)
2253
            feedback_fn("%s" % output)
2254
            lu_result = 0
2255

    
2256
      return lu_result
2257

    
2258

    
2259
class LUVerifyDisks(NoHooksLU):
2260
  """Verifies the cluster disks status.
2261

2262
  """
2263
  _OP_REQP = []
2264
  REQ_BGL = False
2265

    
2266
  def ExpandNames(self):
2267
    self.needed_locks = {
2268
      locking.LEVEL_NODE: locking.ALL_SET,
2269
      locking.LEVEL_INSTANCE: locking.ALL_SET,
2270
    }
2271
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
2272

    
2273
  def Exec(self, feedback_fn):
2274
    """Verify integrity of cluster disks.
2275

2276
    @rtype: tuple of three items
2277
    @return: a tuple of (dict of node-to-node_error, list of instances
2278
        which need activate-disks, dict of instance: (node, volume) for
2279
        missing volumes
2280

2281
    """
2282
    result = res_nodes, res_instances, res_missing = {}, [], {}
2283

    
2284
    vg_name = self.cfg.GetVGName()
2285
    nodes = utils.NiceSort(self.cfg.GetNodeList())
2286
    instances = [self.cfg.GetInstanceInfo(name)
2287
                 for name in self.cfg.GetInstanceList()]
2288

    
2289
    nv_dict = {}
2290
    for inst in instances:
2291
      inst_lvs = {}
2292
      if (not inst.admin_up or
2293
          inst.disk_template not in constants.DTS_NET_MIRROR):
2294
        continue
2295
      inst.MapLVsByNode(inst_lvs)
2296
      # transform { iname: {node: [vol,],},} to {(node, vol): iname}
2297
      for node, vol_list in inst_lvs.iteritems():
2298
        for vol in vol_list:
2299
          nv_dict[(node, vol)] = inst
2300

    
2301
    if not nv_dict:
2302
      return result
2303

    
2304
    node_lvs = self.rpc.call_lv_list(nodes, vg_name)
2305

    
2306
    for node in nodes:
2307
      # node_volume
2308
      node_res = node_lvs[node]
2309
      if node_res.offline:
2310
        continue
2311
      msg = node_res.fail_msg
2312
      if msg:
2313
        logging.warning("Error enumerating LVs on node %s: %s", node, msg)
2314
        res_nodes[node] = msg
2315
        continue
2316

    
2317
      lvs = node_res.payload
2318
      for lv_name, (_, _, lv_online) in lvs.items():
2319
        inst = nv_dict.pop((node, lv_name), None)
2320
        if (not lv_online and inst is not None
2321
            and inst.name not in res_instances):
2322
          res_instances.append(inst.name)
2323

    
2324
    # any leftover items in nv_dict are missing LVs, let's arrange the
2325
    # data better
2326
    for key, inst in nv_dict.iteritems():
2327
      if inst.name not in res_missing:
2328
        res_missing[inst.name] = []
2329
      res_missing[inst.name].append(key)
2330

    
2331
    return result
2332

    
2333

    
2334
class LURepairDiskSizes(NoHooksLU):
2335
  """Verifies the cluster disks sizes.
2336

2337
  """
2338
  _OP_REQP = [("instances", _TListOf(_TNonEmptyString))]
2339
  REQ_BGL = False
2340

    
2341
  def ExpandNames(self):
2342
    if self.op.instances:
2343
      self.wanted_names = []
2344
      for name in self.op.instances:
2345
        full_name = _ExpandInstanceName(self.cfg, name)
2346
        self.wanted_names.append(full_name)
2347
      self.needed_locks = {
2348
        locking.LEVEL_NODE: [],
2349
        locking.LEVEL_INSTANCE: self.wanted_names,
2350
        }
2351
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
2352
    else:
2353
      self.wanted_names = None
2354
      self.needed_locks = {
2355
        locking.LEVEL_NODE: locking.ALL_SET,
2356
        locking.LEVEL_INSTANCE: locking.ALL_SET,
2357
        }
2358
    self.share_locks = dict(((i, 1) for i in locking.LEVELS))
2359

    
2360
  def DeclareLocks(self, level):
2361
    if level == locking.LEVEL_NODE and self.wanted_names is not None:
2362
      self._LockInstancesNodes(primary_only=True)
2363

    
2364
  def CheckPrereq(self):
2365
    """Check prerequisites.
2366

2367
    This only checks the optional instance list against the existing names.
2368

2369
    """
2370
    if self.wanted_names is None:
2371
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
2372

    
2373
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
2374
                             in self.wanted_names]
2375

    
2376
  def _EnsureChildSizes(self, disk):
2377
    """Ensure children of the disk have the needed disk size.
2378

2379
    This is valid mainly for DRBD8 and fixes an issue where the
2380
    children have smaller disk size.
2381

2382
    @param disk: an L{ganeti.objects.Disk} object
2383

2384
    """
2385
    if disk.dev_type == constants.LD_DRBD8:
2386
      assert disk.children, "Empty children for DRBD8?"
2387
      fchild = disk.children[0]
2388
      mismatch = fchild.size < disk.size
2389
      if mismatch:
2390
        self.LogInfo("Child disk has size %d, parent %d, fixing",
2391
                     fchild.size, disk.size)
2392
        fchild.size = disk.size
2393

    
2394
      # and we recurse on this child only, not on the metadev
2395
      return self._EnsureChildSizes(fchild) or mismatch
2396
    else:
2397
      return False
2398

    
2399
  def Exec(self, feedback_fn):
2400
    """Verify the size of cluster disks.
2401

2402
    """
2403
    # TODO: check child disks too
2404
    # TODO: check differences in size between primary/secondary nodes
2405
    per_node_disks = {}
2406
    for instance in self.wanted_instances:
2407
      pnode = instance.primary_node
2408
      if pnode not in per_node_disks:
2409
        per_node_disks[pnode] = []
2410
      for idx, disk in enumerate(instance.disks):
2411
        per_node_disks[pnode].append((instance, idx, disk))
2412

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

    
2449

    
2450
class LURenameCluster(LogicalUnit):
2451
  """Rename the cluster.
2452

2453
  """
2454
  HPATH = "cluster-rename"
2455
  HTYPE = constants.HTYPE_CLUSTER
2456
  _OP_REQP = [("name", _TNonEmptyString)]
2457

    
2458
  def BuildHooksEnv(self):
2459
    """Build hooks env.
2460

2461
    """
2462
    env = {
2463
      "OP_TARGET": self.cfg.GetClusterName(),
2464
      "NEW_NAME": self.op.name,
2465
      }
2466
    mn = self.cfg.GetMasterNode()
2467
    all_nodes = self.cfg.GetNodeList()
2468
    return env, [mn], all_nodes
2469

    
2470
  def CheckPrereq(self):
2471
    """Verify that the passed name is a valid one.
2472

2473
    """
2474
    hostname = utils.GetHostInfo(self.op.name)
2475

    
2476
    new_name = hostname.name
2477
    self.ip = new_ip = hostname.ip
2478
    old_name = self.cfg.GetClusterName()
2479
    old_ip = self.cfg.GetMasterIP()
2480
    if new_name == old_name and new_ip == old_ip:
2481
      raise errors.OpPrereqError("Neither the name nor the IP address of the"
2482
                                 " cluster has changed",
2483
                                 errors.ECODE_INVAL)
2484
    if new_ip != old_ip:
2485
      if utils.TcpPing(new_ip, constants.DEFAULT_NODED_PORT):
2486
        raise errors.OpPrereqError("The given cluster IP address (%s) is"
2487
                                   " reachable on the network. Aborting." %
2488
                                   new_ip, errors.ECODE_NOTUNIQUE)
2489

    
2490
    self.op.name = new_name
2491

    
2492
  def Exec(self, feedback_fn):
2493
    """Rename the cluster.
2494

2495
    """
2496
    clustername = self.op.name
2497
    ip = self.ip
2498

    
2499
    # shutdown the master IP
2500
    master = self.cfg.GetMasterNode()
2501
    result = self.rpc.call_node_stop_master(master, False)
2502
    result.Raise("Could not disable the master role")
2503

    
2504
    try:
2505
      cluster = self.cfg.GetClusterInfo()
2506
      cluster.cluster_name = clustername
2507
      cluster.master_ip = ip
2508
      self.cfg.Update(cluster, feedback_fn)
2509

    
2510
      # update the known hosts file
2511
      ssh.WriteKnownHostsFile(self.cfg, constants.SSH_KNOWN_HOSTS_FILE)
2512
      node_list = self.cfg.GetNodeList()
2513
      try:
2514
        node_list.remove(master)
2515
      except ValueError:
2516
        pass
2517
      result = self.rpc.call_upload_file(node_list,
2518
                                         constants.SSH_KNOWN_HOSTS_FILE)
2519
      for to_node, to_result in result.iteritems():
2520
        msg = to_result.fail_msg
2521
        if msg:
2522
          msg = ("Copy of file %s to node %s failed: %s" %
2523
                 (constants.SSH_KNOWN_HOSTS_FILE, to_node, msg))
2524
          self.proc.LogWarning(msg)
2525

    
2526
    finally:
2527
      result = self.rpc.call_node_start_master(master, False, False)
2528
      msg = result.fail_msg
2529
      if msg:
2530
        self.LogWarning("Could not re-enable the master role on"
2531
                        " the master, please restart manually: %s", msg)
2532

    
2533

    
2534
def _RecursiveCheckIfLVMBased(disk):
2535
  """Check if the given disk or its children are lvm-based.
2536

2537
  @type disk: L{objects.Disk}
2538
  @param disk: the disk to check
2539
  @rtype: boolean
2540
  @return: boolean indicating whether a LD_LV dev_type was found or not
2541

2542
  """
2543
  if disk.children:
2544
    for chdisk in disk.children:
2545
      if _RecursiveCheckIfLVMBased(chdisk):
2546
        return True
2547
  return disk.dev_type == constants.LD_LV
2548

    
2549

    
2550
class LUSetClusterParams(LogicalUnit):
2551
  """Change the parameters of the cluster.
2552

2553
  """
2554
  HPATH = "cluster-modify"
2555
  HTYPE = constants.HTYPE_CLUSTER
2556
  _OP_REQP = [
2557
    ("hvparams", _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2558
    ("os_hvp", _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2559
    ("osparams", _TOr(_TDictOf(_TNonEmptyString, _TDict), _TNone)),
2560
    ("enabled_hypervisors",
2561
     _TOr(_TAnd(_TListOf(_TElemOf(constants.HYPER_TYPES)), _TTrue), _TNone)),
2562
    ]
2563
  _OP_DEFS = [
2564
    ("candidate_pool_size", None),
2565
    ("uid_pool", None),
2566
    ("add_uids", None),
2567
    ("remove_uids", None),
2568
    ("hvparams", None),
2569
    ("os_hvp", None),
2570
    ("osparams", None),
2571
    ]
2572
  REQ_BGL = False
2573

    
2574
  def CheckArguments(self):
2575
    """Check parameters
2576

2577
    """
2578
    if self.op.candidate_pool_size is not None:
2579
      try:
2580
        self.op.candidate_pool_size = int(self.op.candidate_pool_size)
2581
      except (ValueError, TypeError), err:
2582
        raise errors.OpPrereqError("Invalid candidate_pool_size value: %s" %
2583
                                   str(err), errors.ECODE_INVAL)
2584
      if self.op.candidate_pool_size < 1:
2585
        raise errors.OpPrereqError("At least one master candidate needed",
2586
                                   errors.ECODE_INVAL)
2587

    
2588
    _CheckBooleanOpField(self.op, "maintain_node_health")
2589

    
2590
    if self.op.uid_pool:
2591
      uidpool.CheckUidPool(self.op.uid_pool)
2592

    
2593
    if self.op.add_uids:
2594
      uidpool.CheckUidPool(self.op.add_uids)
2595

    
2596
    if self.op.remove_uids:
2597
      uidpool.CheckUidPool(self.op.remove_uids)
2598

    
2599
  def ExpandNames(self):
2600
    # FIXME: in the future maybe other cluster params won't require checking on
2601
    # all nodes to be modified.
2602
    self.needed_locks = {
2603
      locking.LEVEL_NODE: locking.ALL_SET,
2604
    }
2605
    self.share_locks[locking.LEVEL_NODE] = 1
2606

    
2607
  def BuildHooksEnv(self):
2608
    """Build hooks env.
2609

2610
    """
2611
    env = {
2612
      "OP_TARGET": self.cfg.GetClusterName(),
2613
      "NEW_VG_NAME": self.op.vg_name,
2614
      }
2615
    mn = self.cfg.GetMasterNode()
2616
    return env, [mn], [mn]
2617

    
2618
  def CheckPrereq(self):
2619
    """Check prerequisites.
2620

2621
    This checks whether the given params don't conflict and
2622
    if the given volume group is valid.
2623

2624
    """
2625
    if self.op.vg_name is not None and not self.op.vg_name:
2626
      instances = self.cfg.GetAllInstancesInfo().values()
2627
      for inst in instances:
2628
        for disk in inst.disks:
2629
          if _RecursiveCheckIfLVMBased(disk):
2630
            raise errors.OpPrereqError("Cannot disable lvm storage while"
2631
                                       " lvm-based instances exist",
2632
                                       errors.ECODE_INVAL)
2633

    
2634
    node_list = self.acquired_locks[locking.LEVEL_NODE]
2635

    
2636
    # if vg_name not None, checks given volume group on all nodes
2637
    if self.op.vg_name:
2638
      vglist = self.rpc.call_vg_list(node_list)
2639
      for node in node_list:
2640
        msg = vglist[node].fail_msg
2641
        if msg:
2642
          # ignoring down node
2643
          self.LogWarning("Error while gathering data on node %s"
2644
                          " (ignoring node): %s", node, msg)
2645
          continue
2646
        vgstatus = utils.CheckVolumeGroupSize(vglist[node].payload,
2647
                                              self.op.vg_name,
2648
                                              constants.MIN_VG_SIZE)
2649
        if vgstatus:
2650
          raise errors.OpPrereqError("Error on node '%s': %s" %
2651
                                     (node, vgstatus), errors.ECODE_ENVIRON)
2652

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

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

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

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

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

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

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

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

    
2716
        self.new_osp[os_name] = _GetUpdatedParams(self.new_osp[os_name], osp,
2717
                                                  use_none=True)
2718

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

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

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

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

    
2768

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

2772
    """
2773
    if self.op.vg_name is not None:
2774
      new_volume = self.op.vg_name
2775
      if not new_volume:
2776
        new_volume = None
2777
      if new_volume != self.cfg.GetVGName():
2778
        self.cfg.SetVGName(new_volume)
2779
      else:
2780
        feedback_fn("Cluster LVM configuration already in desired"
2781
                    " state, not changing")
2782
    if self.op.hvparams:
2783
      self.cluster.hvparams = self.new_hvparams
2784
    if self.op.os_hvp:
2785
      self.cluster.os_hvp = self.new_os_hvp
2786
    if self.op.enabled_hypervisors is not None:
2787
      self.cluster.hvparams = self.new_hvparams
2788
      self.cluster.enabled_hypervisors = self.op.enabled_hypervisors
2789
    if self.op.beparams:
2790
      self.cluster.beparams[constants.PP_DEFAULT] = self.new_beparams
2791
    if self.op.nicparams:
2792
      self.cluster.nicparams[constants.PP_DEFAULT] = self.new_nicparams
2793
    if self.op.osparams:
2794
      self.cluster.osparams = self.new_osp
2795

    
2796
    if self.op.candidate_pool_size is not None:
2797
      self.cluster.candidate_pool_size = self.op.candidate_pool_size
2798
      # we need to update the pool size here, otherwise the save will fail
2799
      _AdjustCandidatePool(self, [])
2800

    
2801
    if self.op.maintain_node_health is not None:
2802
      self.cluster.maintain_node_health = self.op.maintain_node_health
2803

    
2804
    if self.op.add_uids is not None:
2805
      uidpool.AddToUidPool(self.cluster.uid_pool, self.op.add_uids)
2806

    
2807
    if self.op.remove_uids is not None:
2808
      uidpool.RemoveFromUidPool(self.cluster.uid_pool, self.op.remove_uids)
2809

    
2810
    if self.op.uid_pool is not None:
2811
      self.cluster.uid_pool = self.op.uid_pool
2812

    
2813
    self.cfg.Update(self.cluster, feedback_fn)
2814

    
2815

    
2816
def _RedistributeAncillaryFiles(lu, additional_nodes=None):
2817
  """Distribute additional files which are part of the cluster configuration.
2818

2819
  ConfigWriter takes care of distributing the config and ssconf files, but
2820
  there are more files which should be distributed to all nodes. This function
2821
  makes sure those are copied.
2822

2823
  @param lu: calling logical unit
2824
  @param additional_nodes: list of nodes not in the config to distribute to
2825

2826
  """
2827
  # 1. Gather target nodes
2828
  myself = lu.cfg.GetNodeInfo(lu.cfg.GetMasterNode())
2829
  dist_nodes = lu.cfg.GetOnlineNodeList()
2830
  if additional_nodes is not None:
2831
    dist_nodes.extend(additional_nodes)
2832
  if myself.name in dist_nodes:
2833
    dist_nodes.remove(myself.name)
2834

    
2835
  # 2. Gather files to distribute
2836
  dist_files = set([constants.ETC_HOSTS,
2837
                    constants.SSH_KNOWN_HOSTS_FILE,
2838
                    constants.RAPI_CERT_FILE,
2839
                    constants.RAPI_USERS_FILE,
2840
                    constants.CONFD_HMAC_KEY,
2841
                    constants.CLUSTER_DOMAIN_SECRET_FILE,
2842
                   ])
2843

    
2844
  enabled_hypervisors = lu.cfg.GetClusterInfo().enabled_hypervisors
2845
  for hv_name in enabled_hypervisors:
2846
    hv_class = hypervisor.GetHypervisor(hv_name)
2847
    dist_files.update(hv_class.GetAncillaryFiles())
2848

    
2849
  # 3. Perform the files upload
2850
  for fname in dist_files:
2851
    if os.path.exists(fname):
2852
      result = lu.rpc.call_upload_file(dist_nodes, fname)
2853
      for to_node, to_result in result.items():
2854
        msg = to_result.fail_msg
2855
        if msg:
2856
          msg = ("Copy of file %s to node %s failed: %s" %
2857
                 (fname, to_node, msg))
2858
          lu.proc.LogWarning(msg)
2859

    
2860

    
2861
class LURedistributeConfig(NoHooksLU):
2862
  """Force the redistribution of cluster configuration.
2863

2864
  This is a very simple LU.
2865

2866
  """
2867
  _OP_REQP = []
2868
  REQ_BGL = False
2869

    
2870
  def ExpandNames(self):
2871
    self.needed_locks = {
2872
      locking.LEVEL_NODE: locking.ALL_SET,
2873
    }
2874
    self.share_locks[locking.LEVEL_NODE] = 1
2875

    
2876
  def Exec(self, feedback_fn):
2877
    """Redistribute the configuration.
2878

2879
    """
2880
    self.cfg.Update(self.cfg.GetClusterInfo(), feedback_fn)
2881
    _RedistributeAncillaryFiles(self)
2882

    
2883

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

2887
  """
2888
  if not instance.disks or disks is not None and not disks:
2889
    return True
2890

    
2891
  disks = _ExpandCheckDisks(instance, disks)
2892

    
2893
  if not oneshot:
2894
    lu.proc.LogInfo("Waiting for instance %s to sync disks." % instance.name)
2895

    
2896
  node = instance.primary_node
2897

    
2898
  for dev in disks:
2899
    lu.cfg.SetDiskID(dev, node)
2900

    
2901
  # TODO: Convert to utils.Retry
2902

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

    
2927
      cumul_degraded = (cumul_degraded or
2928
                        (mstat.is_degraded and mstat.sync_percent is None))
2929
      if mstat.sync_percent is not None:
2930
        done = False
2931
        if mstat.estimated_time is not None:
2932
          rem_time = ("%s remaining (estimated)" %
2933
                      utils.FormatSeconds(mstat.estimated_time))
2934
          max_time = mstat.estimated_time
2935
        else:
2936
          rem_time = "no time estimate"
2937
        lu.proc.LogInfo("- device %s: %5.2f%% done, %s" %
2938
                        (disks[i].iv_name, mstat.sync_percent, rem_time))
2939

    
2940
    # if we're done but degraded, let's do a few small retries, to
2941
    # make sure we see a stable and not transient situation; therefore
2942
    # we force restart of the loop
2943
    if (done or oneshot) and cumul_degraded and degr_retries > 0:
2944
      logging.info("Degraded disks found, %d retries left", degr_retries)
2945
      degr_retries -= 1
2946
      time.sleep(1)
2947
      continue
2948

    
2949
    if done or oneshot:
2950
      break
2951

    
2952
    time.sleep(min(60, max_time))
2953

    
2954
  if done:
2955
    lu.proc.LogInfo("Instance %s's disks are in sync." % instance.name)
2956
  return not cumul_degraded
2957

    
2958

    
2959
def _CheckDiskConsistency(lu, dev, node, on_primary, ldisk=False):
2960
  """Check that mirrors are not degraded.
2961

2962
  The ldisk parameter, if True, will change the test from the
2963
  is_degraded attribute (which represents overall non-ok status for
2964
  the device(s)) to the ldisk (representing the local storage status).
2965

2966
  """
2967
  lu.cfg.SetDiskID(dev, node)
2968

    
2969
  result = True
2970

    
2971
  if on_primary or dev.AssembleOnSecondary():
2972
    rstats = lu.rpc.call_blockdev_find(node, dev)
2973
    msg = rstats.fail_msg
2974
    if msg:
2975
      lu.LogWarning("Can't find disk on node %s: %s", node, msg)
2976
      result = False
2977
    elif not rstats.payload:
2978
      lu.LogWarning("Can't find disk on node %s", node)
2979
      result = False
2980
    else:
2981
      if ldisk:
2982
        result = result and rstats.payload.ldisk_status == constants.LDS_OKAY
2983
      else:
2984
        result = result and not rstats.payload.is_degraded
2985

    
2986
  if dev.children:
2987
    for child in dev.children:
2988
      result = result and _CheckDiskConsistency(lu, child, node, on_primary)
2989

    
2990
  return result
2991

    
2992

    
2993
class LUDiagnoseOS(NoHooksLU):
2994
  """Logical unit for OS diagnose/query.
2995

2996
  """
2997
  _OP_REQP = [
2998
    ("output_fields", _TListOf(_TNonEmptyString)),
2999
    ("names", _TListOf(_TNonEmptyString)),
3000
    ]
3001
  REQ_BGL = False
3002
  _FIELDS_STATIC = utils.FieldSet()
3003
  _FIELDS_DYNAMIC = utils.FieldSet("name", "valid", "node_status", "variants",
3004
                                   "parameters", "api_versions")
3005

    
3006
  def CheckArguments(self):
3007
    if self.op.names:
3008
      raise errors.OpPrereqError("Selective OS query not supported",
3009
                                 errors.ECODE_INVAL)
3010

    
3011
    _CheckOutputFields(static=self._FIELDS_STATIC,
3012
                       dynamic=self._FIELDS_DYNAMIC,
3013
                       selected=self.op.output_fields)
3014

    
3015
  def ExpandNames(self):
3016
    # Lock all nodes, in shared mode
3017
    # Temporary removal of locks, should be reverted later
3018
    # TODO: reintroduce locks when they are lighter-weight
3019
    self.needed_locks = {}
3020
    #self.share_locks[locking.LEVEL_NODE] = 1
3021
    #self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3022

    
3023
  @staticmethod
3024
  def _DiagnoseByOS(rlist):
3025
    """Remaps a per-node return list into an a per-os per-node dictionary
3026

3027
    @param rlist: a map with node names as keys and OS objects as values
3028

3029
    @rtype: dict
3030
    @return: a dictionary with osnames as keys and as value another
3031
        map, with nodes as keys and tuples of (path, status, diagnose,
3032
        variants, parameters, api_versions) as values, eg::
3033

3034
          {"debian-etch": {"node1": [(/usr/lib/..., True, "", [], []),
3035
                                     (/srv/..., False, "invalid api")],
3036
                           "node2": [(/srv/..., True, "", [], [])]}
3037
          }
3038

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

    
3063
  def Exec(self, feedback_fn):
3064
    """Compute the list of OSes.
3065

3066
    """
3067
    valid_nodes = [node for node in self.cfg.GetOnlineNodeList()]
3068
    node_data = self.rpc.call_os_diagnose(valid_nodes)
3069
    pol = self._DiagnoseByOS(node_data)
3070
    output = []
3071

    
3072
    for os_name, os_data in pol.items():
3073
      row = []
3074
      valid = True
3075
      (variants, params, api_versions) = null_state = (set(), set(), set())
3076
      for idx, osl in enumerate(os_data.values()):
3077
        valid = bool(valid and osl and osl[0][1])
3078
        if not valid:
3079
          (variants, params, api_versions) = null_state
3080
          break
3081
        node_variants, node_params, node_api = osl[0][3:6]
3082
        if idx == 0: # first entry
3083
          variants = set(node_variants)
3084
          params = set(node_params)
3085
          api_versions = set(node_api)
3086
        else: # keep consistency
3087
          variants.intersection_update(node_variants)
3088
          params.intersection_update(node_params)
3089
          api_versions.intersection_update(node_api)
3090

    
3091
      for field in self.op.output_fields:
3092
        if field == "name":
3093
          val = os_name
3094
        elif field == "valid":
3095
          val = valid
3096
        elif field == "node_status":
3097
          # this is just a copy of the dict
3098
          val = {}
3099
          for node_name, nos_list in os_data.items():
3100
            val[node_name] = nos_list
3101
        elif field == "variants":
3102
          val = list(variants)
3103
        elif field == "parameters":
3104
          val = list(params)
3105
        elif field == "api_versions":
3106
          val = list(api_versions)
3107
        else:
3108
          raise errors.ParameterError(field)
3109
        row.append(val)
3110
      output.append(row)
3111

    
3112
    return output
3113

    
3114

    
3115
class LURemoveNode(LogicalUnit):
3116
  """Logical unit for removing a node.
3117

3118
  """
3119
  HPATH = "node-remove"
3120
  HTYPE = constants.HTYPE_NODE
3121
  _OP_REQP = [("node_name", _TNonEmptyString)]
3122

    
3123
  def BuildHooksEnv(self):
3124
    """Build hooks env.
3125

3126
    This doesn't run on the target node in the pre phase as a failed
3127
    node would then be impossible to remove.
3128

3129
    """
3130
    env = {
3131
      "OP_TARGET": self.op.node_name,
3132
      "NODE_NAME": self.op.node_name,
3133
      }
3134
    all_nodes = self.cfg.GetNodeList()
3135
    try:
3136
      all_nodes.remove(self.op.node_name)
3137
    except ValueError:
3138
      logging.warning("Node %s which is about to be removed not found"
3139
                      " in the all nodes list", self.op.node_name)
3140
    return env, all_nodes, all_nodes
3141

    
3142
  def CheckPrereq(self):
3143
    """Check prerequisites.
3144

3145
    This checks:
3146
     - the node exists in the configuration
3147
     - it does not have primary or secondary instances
3148
     - it's not the master
3149

3150
    Any errors are signaled by raising errors.OpPrereqError.
3151

3152
    """
3153
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3154
    node = self.cfg.GetNodeInfo(self.op.node_name)
3155
    assert node is not None
3156

    
3157
    instance_list = self.cfg.GetInstanceList()
3158

    
3159
    masternode = self.cfg.GetMasterNode()
3160
    if node.name == masternode:
3161
      raise errors.OpPrereqError("Node is the master node,"
3162
                                 " you need to failover first.",
3163
                                 errors.ECODE_INVAL)
3164

    
3165
    for instance_name in instance_list:
3166
      instance = self.cfg.GetInstanceInfo(instance_name)
3167
      if node.name in instance.all_nodes:
3168
        raise errors.OpPrereqError("Instance %s is still running on the node,"
3169
                                   " please remove first." % instance_name,
3170
                                   errors.ECODE_INVAL)
3171
    self.op.node_name = node.name
3172
    self.node = node
3173

    
3174
  def Exec(self, feedback_fn):
3175
    """Removes the node from the cluster.
3176

3177
    """
3178
    node = self.node
3179
    logging.info("Stopping the node daemon and removing configs from node %s",
3180
                 node.name)
3181

    
3182
    modify_ssh_setup = self.cfg.GetClusterInfo().modify_ssh_setup
3183

    
3184
    # Promote nodes to master candidate as needed
3185
    _AdjustCandidatePool(self, exceptions=[node.name])
3186
    self.context.RemoveNode(node.name)
3187

    
3188
    # Run post hooks on the node before it's removed
3189
    hm = self.proc.hmclass(self.rpc.call_hooks_runner, self)
3190
    try:
3191
      hm.RunPhase(constants.HOOKS_PHASE_POST, [node.name])
3192
    except:
3193
      # pylint: disable-msg=W0702
3194
      self.LogWarning("Errors occurred running hooks on %s" % node.name)
3195

    
3196
    result = self.rpc.call_node_leave_cluster(node.name, modify_ssh_setup)
3197
    msg = result.fail_msg
3198
    if msg:
3199
      self.LogWarning("Errors encountered on the remote node while leaving"
3200
                      " the cluster: %s", msg)
3201

    
3202
    # Remove node from our /etc/hosts
3203
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3204
      # FIXME: this should be done via an rpc call to node daemon
3205
      utils.RemoveHostFromEtcHosts(node.name)
3206
      _RedistributeAncillaryFiles(self)
3207

    
3208

    
3209
class LUQueryNodes(NoHooksLU):
3210
  """Logical unit for querying nodes.
3211

3212
  """
3213
  # pylint: disable-msg=W0142
3214
  _OP_REQP = [
3215
    ("output_fields", _TListOf(_TNonEmptyString)),
3216
    ("names", _TListOf(_TNonEmptyString)),
3217
    ("use_locking", _TBool),
3218
    ]
3219
  REQ_BGL = False
3220

    
3221
  _SIMPLE_FIELDS = ["name", "serial_no", "ctime", "mtime", "uuid",
3222
                    "master_candidate", "offline", "drained"]
3223

    
3224
  _FIELDS_DYNAMIC = utils.FieldSet(
3225
    "dtotal", "dfree",
3226
    "mtotal", "mnode", "mfree",
3227
    "bootid",
3228
    "ctotal", "cnodes", "csockets",
3229
    )
3230

    
3231
  _FIELDS_STATIC = utils.FieldSet(*[
3232
    "pinst_cnt", "sinst_cnt",
3233
    "pinst_list", "sinst_list",
3234
    "pip", "sip", "tags",
3235
    "master",
3236
    "role"] + _SIMPLE_FIELDS
3237
    )
3238

    
3239
  def CheckArguments(self):
3240
    _CheckOutputFields(static=self._FIELDS_STATIC,
3241
                       dynamic=self._FIELDS_DYNAMIC,
3242
                       selected=self.op.output_fields)
3243

    
3244
  def ExpandNames(self):
3245
    self.needed_locks = {}
3246
    self.share_locks[locking.LEVEL_NODE] = 1
3247

    
3248
    if self.op.names:
3249
      self.wanted = _GetWantedNodes(self, self.op.names)
3250
    else:
3251
      self.wanted = locking.ALL_SET
3252

    
3253
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
3254
    self.do_locking = self.do_node_query and self.op.use_locking
3255
    if self.do_locking:
3256
      # if we don't request only static fields, we need to lock the nodes
3257
      self.needed_locks[locking.LEVEL_NODE] = self.wanted
3258

    
3259
  def Exec(self, feedback_fn):
3260
    """Computes the list of nodes and their attributes.
3261

3262
    """
3263
    all_info = self.cfg.GetAllNodesInfo()
3264
    if self.do_locking:
3265
      nodenames = self.acquired_locks[locking.LEVEL_NODE]
3266
    elif self.wanted != locking.ALL_SET:
3267
      nodenames = self.wanted
3268
      missing = set(nodenames).difference(all_info.keys())
3269
      if missing:
3270
        raise errors.OpExecError(
3271
          "Some nodes were removed before retrieving their data: %s" % missing)
3272
    else:
3273
      nodenames = all_info.keys()
3274

    
3275
    nodenames = utils.NiceSort(nodenames)
3276
    nodelist = [all_info[name] for name in nodenames]
3277

    
3278
    # begin data gathering
3279

    
3280
    if self.do_node_query:
3281
      live_data = {}
3282
      node_data = self.rpc.call_node_info(nodenames, self.cfg.GetVGName(),
3283
                                          self.cfg.GetHypervisorType())
3284
      for name in nodenames:
3285
        nodeinfo = node_data[name]
3286
        if not nodeinfo.fail_msg and nodeinfo.payload:
3287
          nodeinfo = nodeinfo.payload
3288
          fn = utils.TryConvert
3289
          live_data[name] = {
3290
            "mtotal": fn(int, nodeinfo.get('memory_total', None)),
3291
            "mnode": fn(int, nodeinfo.get('memory_dom0', None)),
3292
            "mfree": fn(int, nodeinfo.get('memory_free', None)),
3293
            "dtotal": fn(int, nodeinfo.get('vg_size', None)),
3294
            "dfree": fn(int, nodeinfo.get('vg_free', None)),
3295
            "ctotal": fn(int, nodeinfo.get('cpu_total', None)),
3296
            "bootid": nodeinfo.get('bootid', None),
3297
            "cnodes": fn(int, nodeinfo.get('cpu_nodes', None)),
3298
            "csockets": fn(int, nodeinfo.get('cpu_sockets', None)),
3299
            }
3300
        else:
3301
          live_data[name] = {}
3302
    else:
3303
      live_data = dict.fromkeys(nodenames, {})
3304

    
3305
    node_to_primary = dict([(name, set()) for name in nodenames])
3306
    node_to_secondary = dict([(name, set()) for name in nodenames])
3307

    
3308
    inst_fields = frozenset(("pinst_cnt", "pinst_list",
3309
                             "sinst_cnt", "sinst_list"))
3310
    if inst_fields & frozenset(self.op.output_fields):
3311
      inst_data = self.cfg.GetAllInstancesInfo()
3312

    
3313
      for inst in inst_data.values():
3314
        if inst.primary_node in node_to_primary:
3315
          node_to_primary[inst.primary_node].add(inst.name)
3316
        for secnode in inst.secondary_nodes:
3317
          if secnode in node_to_secondary:
3318
            node_to_secondary[secnode].add(inst.name)
3319

    
3320
    master_node = self.cfg.GetMasterNode()
3321

    
3322
    # end data gathering
3323

    
3324
    output = []
3325
    for node in nodelist:
3326
      node_output = []
3327
      for field in self.op.output_fields:
3328
        if field in self._SIMPLE_FIELDS:
3329
          val = getattr(node, field)
3330
        elif field == "pinst_list":
3331
          val = list(node_to_primary[node.name])
3332
        elif field == "sinst_list":
3333
          val = list(node_to_secondary[node.name])
3334
        elif field == "pinst_cnt":
3335
          val = len(node_to_primary[node.name])
3336
        elif field == "sinst_cnt":
3337
          val = len(node_to_secondary[node.name])
3338
        elif field == "pip":
3339
          val = node.primary_ip
3340
        elif field == "sip":
3341
          val = node.secondary_ip
3342
        elif field == "tags":
3343
          val = list(node.GetTags())
3344
        elif field == "master":
3345
          val = node.name == master_node
3346
        elif self._FIELDS_DYNAMIC.Matches(field):
3347
          val = live_data[node.name].get(field, None)
3348
        elif field == "role":
3349
          if node.name == master_node:
3350
            val = "M"
3351
          elif node.master_candidate:
3352
            val = "C"
3353
          elif node.drained:
3354
            val = "D"
3355
          elif node.offline:
3356
            val = "O"
3357
          else:
3358
            val = "R"
3359
        else:
3360
          raise errors.ParameterError(field)
3361
        node_output.append(val)
3362
      output.append(node_output)
3363

    
3364
    return output
3365

    
3366

    
3367
class LUQueryNodeVolumes(NoHooksLU):
3368
  """Logical unit for getting volumes on node(s).
3369

3370
  """
3371
  _OP_REQP = [
3372
    ("nodes", _TListOf(_TNonEmptyString)),
3373
    ("output_fields", _TListOf(_TNonEmptyString)),
3374
    ]
3375
  REQ_BGL = False
3376
  _FIELDS_DYNAMIC = utils.FieldSet("phys", "vg", "name", "size", "instance")
3377
  _FIELDS_STATIC = utils.FieldSet("node")
3378

    
3379
  def CheckArguments(self):
3380
    _CheckOutputFields(static=self._FIELDS_STATIC,
3381
                       dynamic=self._FIELDS_DYNAMIC,
3382
                       selected=self.op.output_fields)
3383

    
3384
  def ExpandNames(self):
3385
    self.needed_locks = {}
3386
    self.share_locks[locking.LEVEL_NODE] = 1
3387
    if not self.op.nodes:
3388
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3389
    else:
3390
      self.needed_locks[locking.LEVEL_NODE] = \
3391
        _GetWantedNodes(self, self.op.nodes)
3392

    
3393
  def Exec(self, feedback_fn):
3394
    """Computes the list of nodes and their attributes.
3395

3396
    """
3397
    nodenames = self.acquired_locks[locking.LEVEL_NODE]
3398
    volumes = self.rpc.call_node_volumes(nodenames)
3399

    
3400
    ilist = [self.cfg.GetInstanceInfo(iname) for iname
3401
             in self.cfg.GetInstanceList()]
3402

    
3403
    lv_by_node = dict([(inst, inst.MapLVsByNode()) for inst in ilist])
3404

    
3405
    output = []
3406
    for node in nodenames:
3407
      nresult = volumes[node]
3408
      if nresult.offline:
3409
        continue
3410
      msg = nresult.fail_msg
3411
      if msg:
3412
        self.LogWarning("Can't compute volume data on node %s: %s", node, msg)
3413
        continue
3414

    
3415
      node_vols = nresult.payload[:]
3416
      node_vols.sort(key=lambda vol: vol['dev'])
3417

    
3418
      for vol in node_vols:
3419
        node_output = []
3420
        for field in self.op.output_fields:
3421
          if field == "node":
3422
            val = node
3423
          elif field == "phys":
3424
            val = vol['dev']
3425
          elif field == "vg":
3426
            val = vol['vg']
3427
          elif field == "name":
3428
            val = vol['name']
3429
          elif field == "size":
3430
            val = int(float(vol['size']))
3431
          elif field == "instance":
3432
            for inst in ilist:
3433
              if node not in lv_by_node[inst]:
3434
                continue
3435
              if vol['name'] in lv_by_node[inst][node]:
3436
                val = inst.name
3437
                break
3438
            else:
3439
              val = '-'
3440
          else:
3441
            raise errors.ParameterError(field)
3442
          node_output.append(str(val))
3443

    
3444
        output.append(node_output)
3445

    
3446
    return output
3447

    
3448

    
3449
class LUQueryNodeStorage(NoHooksLU):
3450
  """Logical unit for getting information on storage units on node(s).
3451

3452
  """
3453
  _FIELDS_STATIC = utils.FieldSet(constants.SF_NODE)
3454
  _OP_REQP = [
3455
    ("nodes", _TListOf(_TNonEmptyString)),
3456
    ("storage_type", _CheckStorageType),
3457
    ("output_fields", _TListOf(_TNonEmptyString)),
3458
    ]
3459
  _OP_DEFS = [("name", None)]
3460
  REQ_BGL = False
3461

    
3462
  def CheckArguments(self):
3463
    _CheckOutputFields(static=self._FIELDS_STATIC,
3464
                       dynamic=utils.FieldSet(*constants.VALID_STORAGE_FIELDS),
3465
                       selected=self.op.output_fields)
3466

    
3467
  def ExpandNames(self):
3468
    self.needed_locks = {}
3469
    self.share_locks[locking.LEVEL_NODE] = 1
3470

    
3471
    if self.op.nodes:
3472
      self.needed_locks[locking.LEVEL_NODE] = \
3473
        _GetWantedNodes(self, self.op.nodes)
3474
    else:
3475
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
3476

    
3477
  def Exec(self, feedback_fn):
3478
    """Computes the list of nodes and their attributes.
3479

3480
    """
3481
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
3482

    
3483
    # Always get name to sort by
3484
    if constants.SF_NAME in self.op.output_fields:
3485
      fields = self.op.output_fields[:]
3486
    else:
3487
      fields = [constants.SF_NAME] + self.op.output_fields
3488

    
3489
    # Never ask for node or type as it's only known to the LU
3490
    for extra in [constants.SF_NODE, constants.SF_TYPE]:
3491
      while extra in fields:
3492
        fields.remove(extra)
3493

    
3494
    field_idx = dict([(name, idx) for (idx, name) in enumerate(fields)])
3495
    name_idx = field_idx[constants.SF_NAME]
3496

    
3497
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3498
    data = self.rpc.call_storage_list(self.nodes,
3499
                                      self.op.storage_type, st_args,
3500
                                      self.op.name, fields)
3501

    
3502
    result = []
3503

    
3504
    for node in utils.NiceSort(self.nodes):
3505
      nresult = data[node]
3506
      if nresult.offline:
3507
        continue
3508

    
3509
      msg = nresult.fail_msg
3510
      if msg:
3511
        self.LogWarning("Can't get storage data from node %s: %s", node, msg)
3512
        continue
3513

    
3514
      rows = dict([(row[name_idx], row) for row in nresult.payload])
3515

    
3516
      for name in utils.NiceSort(rows.keys()):
3517
        row = rows[name]
3518

    
3519
        out = []
3520

    
3521
        for field in self.op.output_fields:
3522
          if field == constants.SF_NODE:
3523
            val = node
3524
          elif field == constants.SF_TYPE:
3525
            val = self.op.storage_type
3526
          elif field in field_idx:
3527
            val = row[field_idx[field]]
3528
          else:
3529
            raise errors.ParameterError(field)
3530

    
3531
          out.append(val)
3532

    
3533
        result.append(out)
3534

    
3535
    return result
3536

    
3537

    
3538
class LUModifyNodeStorage(NoHooksLU):
3539
  """Logical unit for modifying a storage volume on a node.
3540

3541
  """
3542
  _OP_REQP = [
3543
    ("node_name", _TNonEmptyString),
3544
    ("storage_type", _CheckStorageType),
3545
    ("name", _TNonEmptyString),
3546
    ("changes", _TDict),
3547
    ]
3548
  REQ_BGL = False
3549

    
3550
  def CheckArguments(self):
3551
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3552

    
3553
    storage_type = self.op.storage_type
3554

    
3555
    try:
3556
      modifiable = constants.MODIFIABLE_STORAGE_FIELDS[storage_type]
3557
    except KeyError:
3558
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
3559
                                 " modified" % storage_type,
3560
                                 errors.ECODE_INVAL)
3561

    
3562
    diff = set(self.op.changes.keys()) - modifiable
3563
    if diff:
3564
      raise errors.OpPrereqError("The following fields can not be modified for"
3565
                                 " storage units of type '%s': %r" %
3566
                                 (storage_type, list(diff)),
3567
                                 errors.ECODE_INVAL)
3568

    
3569
  def ExpandNames(self):
3570
    self.needed_locks = {
3571
      locking.LEVEL_NODE: self.op.node_name,
3572
      }
3573

    
3574
  def Exec(self, feedback_fn):
3575
    """Computes the list of nodes and their attributes.
3576

3577
    """
3578
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
3579
    result = self.rpc.call_storage_modify(self.op.node_name,
3580
                                          self.op.storage_type, st_args,
3581
                                          self.op.name, self.op.changes)
3582
    result.Raise("Failed to modify storage unit '%s' on %s" %
3583
                 (self.op.name, self.op.node_name))
3584

    
3585

    
3586
class LUAddNode(LogicalUnit):
3587
  """Logical unit for adding node to the cluster.
3588

3589
  """
3590
  HPATH = "node-add"
3591
  HTYPE = constants.HTYPE_NODE
3592
  _OP_REQP = [
3593
    ("node_name", _TNonEmptyString),
3594
    ]
3595
  _OP_DEFS = [("secondary_ip", None)]
3596

    
3597
  def CheckArguments(self):
3598
    # validate/normalize the node name
3599
    self.op.node_name = utils.HostInfo.NormalizeName(self.op.node_name)
3600

    
3601
  def BuildHooksEnv(self):
3602
    """Build hooks env.
3603

3604
    This will run on all nodes before, and on all nodes + the new node after.
3605

3606
    """
3607
    env = {
3608
      "OP_TARGET": self.op.node_name,
3609
      "NODE_NAME": self.op.node_name,
3610
      "NODE_PIP": self.op.primary_ip,
3611
      "NODE_SIP": self.op.secondary_ip,
3612
      }
3613
    nodes_0 = self.cfg.GetNodeList()
3614
    nodes_1 = nodes_0 + [self.op.node_name, ]
3615
    return env, nodes_0, nodes_1
3616

    
3617
  def CheckPrereq(self):
3618
    """Check prerequisites.
3619

3620
    This checks:
3621
     - the new node is not already in the config
3622
     - it is resolvable
3623
     - its parameters (single/dual homed) matches the cluster
3624

3625
    Any errors are signaled by raising errors.OpPrereqError.
3626

3627
    """
3628
    node_name = self.op.node_name
3629
    cfg = self.cfg
3630

    
3631
    dns_data = utils.GetHostInfo(node_name)
3632

    
3633
    node = dns_data.name
3634
    primary_ip = self.op.primary_ip = dns_data.ip
3635
    if self.op.secondary_ip is None:
3636
      self.op.secondary_ip = primary_ip
3637
    if not utils.IsValidIP4(self.op.secondary_ip):
3638
      raise errors.OpPrereqError("Invalid secondary IP given",
3639
                                 errors.ECODE_INVAL)
3640
    secondary_ip = self.op.secondary_ip
3641

    
3642
    node_list = cfg.GetNodeList()
3643
    if not self.op.readd and node in node_list:
3644
      raise errors.OpPrereqError("Node %s is already in the configuration" %
3645
                                 node, errors.ECODE_EXISTS)
3646
    elif self.op.readd and node not in node_list:
3647
      raise errors.OpPrereqError("Node %s is not in the configuration" % node,
3648
                                 errors.ECODE_NOENT)
3649

    
3650
    self.changed_primary_ip = False
3651

    
3652
    for existing_node_name in node_list:
3653
      existing_node = cfg.GetNodeInfo(existing_node_name)
3654

    
3655
      if self.op.readd and node == existing_node_name:
3656
        if existing_node.secondary_ip != secondary_ip:
3657
          raise errors.OpPrereqError("Readded node doesn't have the same IP"
3658
                                     " address configuration as before",
3659
                                     errors.ECODE_INVAL)
3660
        if existing_node.primary_ip != primary_ip:
3661
          self.changed_primary_ip = True
3662

    
3663
        continue
3664

    
3665
      if (existing_node.primary_ip == primary_ip or
3666
          existing_node.secondary_ip == primary_ip or
3667
          existing_node.primary_ip == secondary_ip or
3668
          existing_node.secondary_ip == secondary_ip):
3669
        raise errors.OpPrereqError("New node ip address(es) conflict with"
3670
                                   " existing node %s" % existing_node.name,
3671
                                   errors.ECODE_NOTUNIQUE)
3672

    
3673
    # check that the type of the node (single versus dual homed) is the
3674
    # same as for the master
3675
    myself = cfg.GetNodeInfo(self.cfg.GetMasterNode())
3676
    master_singlehomed = myself.secondary_ip == myself.primary_ip
3677
    newbie_singlehomed = secondary_ip == primary_ip
3678
    if master_singlehomed != newbie_singlehomed:
3679
      if master_singlehomed:
3680
        raise errors.OpPrereqError("The master has no private ip but the"
3681
                                   " new node has one",
3682
                                   errors.ECODE_INVAL)
3683
      else:
3684
        raise errors.OpPrereqError("The master has a private ip but the"
3685
                                   " new node doesn't have one",
3686
                                   errors.ECODE_INVAL)
3687

    
3688
    # checks reachability
3689
    if not utils.TcpPing(primary_ip, constants.DEFAULT_NODED_PORT):
3690
      raise errors.OpPrereqError("Node not reachable by ping",
3691
                                 errors.ECODE_ENVIRON)
3692

    
3693
    if not newbie_singlehomed:
3694
      # check reachability from my secondary ip to newbie's secondary ip
3695
      if not utils.TcpPing(secondary_ip, constants.DEFAULT_NODED_PORT,
3696
                           source=myself.secondary_ip):
3697
        raise errors.OpPrereqError("Node secondary ip not reachable by TCP"
3698
                                   " based ping to noded port",
3699
                                   errors.ECODE_ENVIRON)
3700

    
3701
    if self.op.readd:
3702
      exceptions = [node]
3703
    else:
3704
      exceptions = []
3705

    
3706
    self.master_candidate = _DecideSelfPromotion(self, exceptions=exceptions)
3707

    
3708
    if self.op.readd:
3709
      self.new_node = self.cfg.GetNodeInfo(node)
3710
      assert self.new_node is not None, "Can't retrieve locked node %s" % node
3711
    else:
3712
      self.new_node = objects.Node(name=node,
3713
                                   primary_ip=primary_ip,
3714
                                   secondary_ip=secondary_ip,
3715
                                   master_candidate=self.master_candidate,
3716
                                   offline=False, drained=False)
3717

    
3718
  def Exec(self, feedback_fn):
3719
    """Adds the new node to the cluster.
3720

3721
    """
3722
    new_node = self.new_node
3723
    node = new_node.name
3724

    
3725
    # for re-adds, reset the offline/drained/master-candidate flags;
3726
    # we need to reset here, otherwise offline would prevent RPC calls
3727
    # later in the procedure; this also means that if the re-add
3728
    # fails, we are left with a non-offlined, broken node
3729
    if self.op.readd:
3730
      new_node.drained = new_node.offline = False # pylint: disable-msg=W0201
3731
      self.LogInfo("Readding a node, the offline/drained flags were reset")
3732
      # if we demote the node, we do cleanup later in the procedure
3733
      new_node.master_candidate = self.master_candidate
3734
      if self.changed_primary_ip:
3735
        new_node.primary_ip = self.op.primary_ip
3736

    
3737
    # notify the user about any possible mc promotion
3738
    if new_node.master_candidate:
3739
      self.LogInfo("Node will be a master candidate")
3740

    
3741
    # check connectivity
3742
    result = self.rpc.call_version([node])[node]
3743
    result.Raise("Can't get version information from node %s" % node)
3744
    if constants.PROTOCOL_VERSION == result.payload:
3745
      logging.info("Communication to node %s fine, sw version %s match",
3746
                   node, result.payload)
3747
    else:
3748
      raise errors.OpExecError("Version mismatch master version %s,"
3749
                               " node version %s" %
3750
                               (constants.PROTOCOL_VERSION, result.payload))
3751

    
3752
    # setup ssh on node
3753
    if self.cfg.GetClusterInfo().modify_ssh_setup:
3754
      logging.info("Copy ssh key to node %s", node)
3755
      priv_key, pub_key, _ = ssh.GetUserFiles(constants.GANETI_RUNAS)
3756
      keyarray = []
3757
      keyfiles = [constants.SSH_HOST_DSA_PRIV, constants.SSH_HOST_DSA_PUB,
3758
                  constants.SSH_HOST_RSA_PRIV, constants.SSH_HOST_RSA_PUB,
3759
                  priv_key, pub_key]
3760

    
3761
      for i in keyfiles:
3762
        keyarray.append(utils.ReadFile(i))
3763

    
3764
      result = self.rpc.call_node_add(node, keyarray[0], keyarray[1],
3765
                                      keyarray[2], keyarray[3], keyarray[4],
3766
                                      keyarray[5])
3767
      result.Raise("Cannot transfer ssh keys to the new node")
3768

    
3769
    # Add node to our /etc/hosts, and add key to known_hosts
3770
    if self.cfg.GetClusterInfo().modify_etc_hosts:
3771
      # FIXME: this should be done via an rpc call to node daemon
3772
      utils.AddHostToEtcHosts(new_node.name)
3773

    
3774
    if new_node.secondary_ip != new_node.primary_ip:
3775
      result = self.rpc.call_node_has_ip_address(new_node.name,
3776
                                                 new_node.secondary_ip)
3777
      result.Raise("Failure checking secondary ip on node %s" % new_node.name,
3778
                   prereq=True, ecode=errors.ECODE_ENVIRON)
3779
      if not result.payload:
3780
        raise errors.OpExecError("Node claims it doesn't have the secondary ip"
3781
                                 " you gave (%s). Please fix and re-run this"
3782
                                 " command." % new_node.secondary_ip)
3783

    
3784
    node_verify_list = [self.cfg.GetMasterNode()]
3785
    node_verify_param = {
3786
      constants.NV_NODELIST: [node],
3787
      # TODO: do a node-net-test as well?
3788
    }
3789

    
3790
    result = self.rpc.call_node_verify(node_verify_list, node_verify_param,
3791
                                       self.cfg.GetClusterName())
3792
    for verifier in node_verify_list:
3793
      result[verifier].Raise("Cannot communicate with node %s" % verifier)
3794
      nl_payload = result[verifier].payload[constants.NV_NODELIST]
3795
      if nl_payload:
3796
        for failed in nl_payload:
3797
          feedback_fn("ssh/hostname verification failed"
3798
                      " (checking from %s): %s" %
3799
                      (verifier, nl_payload[failed]))
3800
        raise errors.OpExecError("ssh/hostname verification failed.")
3801

    
3802
    if self.op.readd:
3803
      _RedistributeAncillaryFiles(self)
3804
      self.context.ReaddNode(new_node)
3805
      # make sure we redistribute the config
3806
      self.cfg.Update(new_node, feedback_fn)
3807
      # and make sure the new node will not have old files around
3808
      if not new_node.master_candidate:
3809
        result = self.rpc.call_node_demote_from_mc(new_node.name)
3810
        msg = result.fail_msg
3811
        if msg:
3812
          self.LogWarning("Node failed to demote itself from master"
3813
                          " candidate status: %s" % msg)
3814
    else:
3815
      _RedistributeAncillaryFiles(self, additional_nodes=[node])
3816
      self.context.AddNode(new_node, self.proc.GetECId())
3817

    
3818

    
3819
class LUSetNodeParams(LogicalUnit):
3820
  """Modifies the parameters of a node.
3821

3822
  """
3823
  HPATH = "node-modify"
3824
  HTYPE = constants.HTYPE_NODE
3825
  _OP_REQP = [("node_name", _TNonEmptyString)]
3826
  REQ_BGL = False
3827

    
3828
  def CheckArguments(self):
3829
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3830
    _CheckBooleanOpField(self.op, 'master_candidate')
3831
    _CheckBooleanOpField(self.op, 'offline')
3832
    _CheckBooleanOpField(self.op, 'drained')
3833
    _CheckBooleanOpField(self.op, 'auto_promote')
3834
    all_mods = [self.op.offline, self.op.master_candidate, self.op.drained]
3835
    if all_mods.count(None) == 3:
3836
      raise errors.OpPrereqError("Please pass at least one modification",
3837
                                 errors.ECODE_INVAL)
3838
    if all_mods.count(True) > 1:
3839
      raise errors.OpPrereqError("Can't set the node into more than one"
3840
                                 " state at the same time",
3841
                                 errors.ECODE_INVAL)
3842

    
3843
    # Boolean value that tells us whether we're offlining or draining the node
3844
    self.offline_or_drain = (self.op.offline == True or
3845
                             self.op.drained == True)
3846
    self.deoffline_or_drain = (self.op.offline == False or
3847
                               self.op.drained == False)
3848
    self.might_demote = (self.op.master_candidate == False or
3849
                         self.offline_or_drain)
3850

    
3851
    self.lock_all = self.op.auto_promote and self.might_demote
3852

    
3853

    
3854
  def ExpandNames(self):
3855
    if self.lock_all:
3856
      self.needed_locks = {locking.LEVEL_NODE: locking.ALL_SET}
3857
    else:
3858
      self.needed_locks = {locking.LEVEL_NODE: self.op.node_name}
3859

    
3860
  def BuildHooksEnv(self):
3861
    """Build hooks env.
3862

3863
    This runs on the master node.
3864

3865
    """
3866
    env = {
3867
      "OP_TARGET": self.op.node_name,
3868
      "MASTER_CANDIDATE": str(self.op.master_candidate),
3869
      "OFFLINE": str(self.op.offline),
3870
      "DRAINED": str(self.op.drained),
3871
      }
3872
    nl = [self.cfg.GetMasterNode(),
3873
          self.op.node_name]
3874
    return env, nl, nl
3875

    
3876
  def CheckPrereq(self):
3877
    """Check prerequisites.
3878

3879
    This only checks the instance list against the existing names.
3880

3881
    """
3882
    node = self.node = self.cfg.GetNodeInfo(self.op.node_name)
3883

    
3884
    if (self.op.master_candidate is not None or
3885
        self.op.drained is not None or
3886
        self.op.offline is not None):
3887
      # we can't change the master's node flags
3888
      if self.op.node_name == self.cfg.GetMasterNode():
3889
        raise errors.OpPrereqError("The master role can be changed"
3890
                                   " only via masterfailover",
3891
                                   errors.ECODE_INVAL)
3892

    
3893

    
3894
    if node.master_candidate and self.might_demote and not self.lock_all:
3895
      assert not self.op.auto_promote, "auto-promote set but lock_all not"
3896
      # check if after removing the current node, we're missing master
3897
      # candidates
3898
      (mc_remaining, mc_should, _) = \
3899
          self.cfg.GetMasterCandidateStats(exceptions=[node.name])
3900
      if mc_remaining < mc_should:
3901
        raise errors.OpPrereqError("Not enough master candidates, please"
3902
                                   " pass auto_promote to allow promotion",
3903
                                   errors.ECODE_INVAL)
3904

    
3905
    if (self.op.master_candidate == True and
3906
        ((node.offline and not self.op.offline == False) or
3907
         (node.drained and not self.op.drained == False))):
3908
      raise errors.OpPrereqError("Node '%s' is offline or drained, can't set"
3909
                                 " to master_candidate" % node.name,
3910
                                 errors.ECODE_INVAL)
3911

    
3912
    # If we're being deofflined/drained, we'll MC ourself if needed
3913
    if (self.deoffline_or_drain and not self.offline_or_drain and not
3914
        self.op.master_candidate == True and not node.master_candidate):
3915
      self.op.master_candidate = _DecideSelfPromotion(self)
3916
      if self.op.master_candidate:
3917
        self.LogInfo("Autopromoting node to master candidate")
3918

    
3919
    return
3920

    
3921
  def Exec(self, feedback_fn):
3922
    """Modifies a node.
3923

3924
    """
3925
    node = self.node
3926

    
3927
    result = []
3928
    changed_mc = False
3929

    
3930
    if self.op.offline is not None:
3931
      node.offline = self.op.offline
3932
      result.append(("offline", str(self.op.offline)))
3933
      if self.op.offline == True:
3934
        if node.master_candidate:
3935
          node.master_candidate = False
3936
          changed_mc = True
3937
          result.append(("master_candidate", "auto-demotion due to offline"))
3938
        if node.drained:
3939
          node.drained = False
3940
          result.append(("drained", "clear drained status due to offline"))
3941

    
3942
    if self.op.master_candidate is not None:
3943
      node.master_candidate = self.op.master_candidate
3944
      changed_mc = True
3945
      result.append(("master_candidate", str(self.op.master_candidate)))
3946
      if self.op.master_candidate == False:
3947
        rrc = self.rpc.call_node_demote_from_mc(node.name)
3948
        msg = rrc.fail_msg
3949
        if msg:
3950
          self.LogWarning("Node failed to demote itself: %s" % msg)
3951

    
3952
    if self.op.drained is not None:
3953
      node.drained = self.op.drained
3954
      result.append(("drained", str(self.op.drained)))
3955
      if self.op.drained == True:
3956
        if node.master_candidate:
3957
          node.master_candidate = False
3958
          changed_mc = True
3959
          result.append(("master_candidate", "auto-demotion due to drain"))
3960
          rrc = self.rpc.call_node_demote_from_mc(node.name)
3961
          msg = rrc.fail_msg
3962
          if msg:
3963
            self.LogWarning("Node failed to demote itself: %s" % msg)
3964
        if node.offline:
3965
          node.offline = False
3966
          result.append(("offline", "clear offline status due to drain"))
3967

    
3968
    # we locked all nodes, we adjust the CP before updating this node
3969
    if self.lock_all:
3970
      _AdjustCandidatePool(self, [node.name])
3971

    
3972
    # this will trigger configuration file update, if needed
3973
    self.cfg.Update(node, feedback_fn)
3974

    
3975
    # this will trigger job queue propagation or cleanup
3976
    if changed_mc:
3977
      self.context.ReaddNode(node)
3978

    
3979
    return result
3980

    
3981

    
3982
class LUPowercycleNode(NoHooksLU):
3983
  """Powercycles a node.
3984

3985
  """
3986
  _OP_REQP = [
3987
    ("node_name", _TNonEmptyString),
3988
    ("force", _TBool),
3989
    ]
3990
  REQ_BGL = False
3991

    
3992
  def CheckArguments(self):
3993
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
3994
    if self.op.node_name == self.cfg.GetMasterNode() and not self.op.force:
3995
      raise errors.OpPrereqError("The node is the master and the force"
3996
                                 " parameter was not set",
3997
                                 errors.ECODE_INVAL)
3998

    
3999
  def ExpandNames(self):
4000
    """Locking for PowercycleNode.
4001

4002
    This is a last-resort option and shouldn't block on other
4003
    jobs. Therefore, we grab no locks.
4004

4005
    """
4006
    self.needed_locks = {}
4007

    
4008
  def Exec(self, feedback_fn):
4009
    """Reboots a node.
4010

4011
    """
4012
    result = self.rpc.call_node_powercycle(self.op.node_name,
4013
                                           self.cfg.GetHypervisorType())
4014
    result.Raise("Failed to schedule the reboot")
4015
    return result.payload
4016

    
4017

    
4018
class LUQueryClusterInfo(NoHooksLU):
4019
  """Query cluster configuration.
4020

4021
  """
4022
  _OP_REQP = []
4023
  REQ_BGL = False
4024

    
4025
  def ExpandNames(self):
4026
    self.needed_locks = {}
4027

    
4028
  def Exec(self, feedback_fn):
4029
    """Return cluster config.
4030

4031
    """
4032
    cluster = self.cfg.GetClusterInfo()
4033
    os_hvp = {}
4034

    
4035
    # Filter just for enabled hypervisors
4036
    for os_name, hv_dict in cluster.os_hvp.items():
4037
      os_hvp[os_name] = {}
4038
      for hv_name, hv_params in hv_dict.items():
4039
        if hv_name in cluster.enabled_hypervisors:
4040
          os_hvp[os_name][hv_name] = hv_params
4041

    
4042
    result = {
4043
      "software_version": constants.RELEASE_VERSION,
4044
      "protocol_version": constants.PROTOCOL_VERSION,
4045
      "config_version": constants.CONFIG_VERSION,
4046
      "os_api_version": max(constants.OS_API_VERSIONS),
4047
      "export_version": constants.EXPORT_VERSION,
4048
      "architecture": (platform.architecture()[0], platform.machine()),
4049
      "name": cluster.cluster_name,
4050
      "master": cluster.master_node,
4051
      "default_hypervisor": cluster.enabled_hypervisors[0],
4052
      "enabled_hypervisors": cluster.enabled_hypervisors,
4053
      "hvparams": dict([(hypervisor_name, cluster.hvparams[hypervisor_name])
4054
                        for hypervisor_name in cluster.enabled_hypervisors]),
4055
      "os_hvp": os_hvp,
4056
      "beparams": cluster.beparams,
4057
      "osparams": cluster.osparams,
4058
      "nicparams": cluster.nicparams,
4059
      "candidate_pool_size": cluster.candidate_pool_size,
4060
      "master_netdev": cluster.master_netdev,
4061
      "volume_group_name": cluster.volume_group_name,
4062
      "file_storage_dir": cluster.file_storage_dir,
4063
      "maintain_node_health": cluster.maintain_node_health,
4064
      "ctime": cluster.ctime,
4065
      "mtime": cluster.mtime,
4066
      "uuid": cluster.uuid,
4067
      "tags": list(cluster.GetTags()),
4068
      "uid_pool": cluster.uid_pool,
4069
      }
4070

    
4071
    return result
4072

    
4073

    
4074
class LUQueryConfigValues(NoHooksLU):
4075
  """Return configuration values.
4076

4077
  """
4078
  _OP_REQP = []
4079
  REQ_BGL = False
4080
  _FIELDS_DYNAMIC = utils.FieldSet()
4081
  _FIELDS_STATIC = utils.FieldSet("cluster_name", "master_node", "drain_flag",
4082
                                  "watcher_pause")
4083

    
4084
  def CheckArguments(self):
4085
    _CheckOutputFields(static=self._FIELDS_STATIC,
4086
                       dynamic=self._FIELDS_DYNAMIC,
4087
                       selected=self.op.output_fields)
4088

    
4089
  def ExpandNames(self):
4090
    self.needed_locks = {}
4091

    
4092
  def Exec(self, feedback_fn):
4093
    """Dump a representation of the cluster config to the standard output.
4094

4095
    """
4096
    values = []
4097
    for field in self.op.output_fields:
4098
      if field == "cluster_name":
4099
        entry = self.cfg.GetClusterName()
4100
      elif field == "master_node":
4101
        entry = self.cfg.GetMasterNode()
4102
      elif field == "drain_flag":
4103
        entry = os.path.exists(constants.JOB_QUEUE_DRAIN_FILE)
4104
      elif field == "watcher_pause":
4105
        entry = utils.ReadWatcherPauseFile(constants.WATCHER_PAUSEFILE)
4106
      else:
4107
        raise errors.ParameterError(field)
4108
      values.append(entry)
4109
    return values
4110

    
4111

    
4112
class LUActivateInstanceDisks(NoHooksLU):
4113
  """Bring up an instance's disks.
4114

4115
  """
4116
  _OP_REQP = [("instance_name", _TNonEmptyString)]
4117
  _OP_DEFS = [("ignore_size", False)]
4118
  REQ_BGL = False
4119

    
4120
  def ExpandNames(self):
4121
    self._ExpandAndLockInstance()
4122
    self.needed_locks[locking.LEVEL_NODE] = []
4123
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4124

    
4125
  def DeclareLocks(self, level):
4126
    if level == locking.LEVEL_NODE:
4127
      self._LockInstancesNodes()
4128

    
4129
  def CheckPrereq(self):
4130
    """Check prerequisites.
4131

4132
    This checks that the instance is in the cluster.
4133

4134
    """
4135
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4136
    assert self.instance is not None, \
4137
      "Cannot retrieve locked instance %s" % self.op.instance_name
4138
    _CheckNodeOnline(self, self.instance.primary_node)
4139

    
4140
  def Exec(self, feedback_fn):
4141
    """Activate the disks.
4142

4143
    """
4144
    disks_ok, disks_info = \
4145
              _AssembleInstanceDisks(self, self.instance,
4146
                                     ignore_size=self.op.ignore_size)
4147
    if not disks_ok:
4148
      raise errors.OpExecError("Cannot activate block devices")
4149

    
4150
    return disks_info
4151

    
4152

    
4153
def _AssembleInstanceDisks(lu, instance, disks=None, ignore_secondaries=False,
4154
                           ignore_size=False):
4155
  """Prepare the block devices for an instance.
4156

4157
  This sets up the block devices on all nodes.
4158

4159
  @type lu: L{LogicalUnit}
4160
  @param lu: the logical unit on whose behalf we execute
4161
  @type instance: L{objects.Instance}
4162
  @param instance: the instance for whose disks we assemble
4163
  @type disks: list of L{objects.Disk} or None
4164
  @param disks: which disks to assemble (or all, if None)
4165
  @type ignore_secondaries: boolean
4166
  @param ignore_secondaries: if true, errors on secondary nodes
4167
      won't result in an error return from the function
4168
  @type ignore_size: boolean
4169
  @param ignore_size: if true, the current known size of the disk
4170
      will not be used during the disk activation, useful for cases
4171
      when the size is wrong
4172
  @return: False if the operation failed, otherwise a list of
4173
      (host, instance_visible_name, node_visible_name)
4174
      with the mapping from node devices to instance devices
4175

4176
  """
4177
  device_info = []
4178
  disks_ok = True
4179
  iname = instance.name
4180
  disks = _ExpandCheckDisks(instance, disks)
4181

    
4182
  # With the two passes mechanism we try to reduce the window of
4183
  # opportunity for the race condition of switching DRBD to primary
4184
  # before handshaking occured, but we do not eliminate it
4185

    
4186
  # The proper fix would be to wait (with some limits) until the
4187
  # connection has been made and drbd transitions from WFConnection
4188
  # into any other network-connected state (Connected, SyncTarget,
4189
  # SyncSource, etc.)
4190

    
4191
  # 1st pass, assemble on all nodes in secondary mode
4192
  for inst_disk in disks:
4193
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4194
      if ignore_size:
4195
        node_disk = node_disk.Copy()
4196
        node_disk.UnsetSize()
4197
      lu.cfg.SetDiskID(node_disk, node)
4198
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, False)
4199
      msg = result.fail_msg
4200
      if msg:
4201
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4202
                           " (is_primary=False, pass=1): %s",
4203
                           inst_disk.iv_name, node, msg)
4204
        if not ignore_secondaries:
4205
          disks_ok = False
4206

    
4207
  # FIXME: race condition on drbd migration to primary
4208

    
4209
  # 2nd pass, do only the primary node
4210
  for inst_disk in disks:
4211
    dev_path = None
4212

    
4213
    for node, node_disk in inst_disk.ComputeNodeTree(instance.primary_node):
4214
      if node != instance.primary_node:
4215
        continue
4216
      if ignore_size:
4217
        node_disk = node_disk.Copy()
4218
        node_disk.UnsetSize()
4219
      lu.cfg.SetDiskID(node_disk, node)
4220
      result = lu.rpc.call_blockdev_assemble(node, node_disk, iname, True)
4221
      msg = result.fail_msg
4222
      if msg:
4223
        lu.proc.LogWarning("Could not prepare block device %s on node %s"
4224
                           " (is_primary=True, pass=2): %s",
4225
                           inst_disk.iv_name, node, msg)
4226
        disks_ok = False
4227
      else:
4228
        dev_path = result.payload
4229

    
4230
    device_info.append((instance.primary_node, inst_disk.iv_name, dev_path))
4231

    
4232
  # leave the disks configured for the primary node
4233
  # this is a workaround that would be fixed better by
4234
  # improving the logical/physical id handling
4235
  for disk in disks:
4236
    lu.cfg.SetDiskID(disk, instance.primary_node)
4237

    
4238
  return disks_ok, device_info
4239

    
4240

    
4241
def _StartInstanceDisks(lu, instance, force):
4242
  """Start the disks of an instance.
4243

4244
  """
4245
  disks_ok, _ = _AssembleInstanceDisks(lu, instance,
4246
                                           ignore_secondaries=force)
4247
  if not disks_ok:
4248
    _ShutdownInstanceDisks(lu, instance)
4249
    if force is not None and not force:
4250
      lu.proc.LogWarning("", hint="If the message above refers to a"
4251
                         " secondary node,"
4252
                         " you can retry the operation using '--force'.")
4253
    raise errors.OpExecError("Disk consistency error")
4254

    
4255

    
4256
class LUDeactivateInstanceDisks(NoHooksLU):
4257
  """Shutdown an instance's disks.
4258

4259
  """
4260
  _OP_REQP = [("instance_name", _TNonEmptyString)]
4261
  REQ_BGL = False
4262

    
4263
  def ExpandNames(self):
4264
    self._ExpandAndLockInstance()
4265
    self.needed_locks[locking.LEVEL_NODE] = []
4266
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4267

    
4268
  def DeclareLocks(self, level):
4269
    if level == locking.LEVEL_NODE:
4270
      self._LockInstancesNodes()
4271

    
4272
  def CheckPrereq(self):
4273
    """Check prerequisites.
4274

4275
    This checks that the instance is in the cluster.
4276

4277
    """
4278
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4279
    assert self.instance is not None, \
4280
      "Cannot retrieve locked instance %s" % self.op.instance_name
4281

    
4282
  def Exec(self, feedback_fn):
4283
    """Deactivate the disks
4284

4285
    """
4286
    instance = self.instance
4287
    _SafeShutdownInstanceDisks(self, instance)
4288

    
4289

    
4290
def _SafeShutdownInstanceDisks(lu, instance, disks=None):
4291
  """Shutdown block devices of an instance.
4292

4293
  This function checks if an instance is running, before calling
4294
  _ShutdownInstanceDisks.
4295

4296
  """
4297
  _CheckInstanceDown(lu, instance, "cannot shutdown disks")
4298
  _ShutdownInstanceDisks(lu, instance, disks=disks)
4299

    
4300

    
4301
def _ExpandCheckDisks(instance, disks):
4302
  """Return the instance disks selected by the disks list
4303

4304
  @type disks: list of L{objects.Disk} or None
4305
  @param disks: selected disks
4306
  @rtype: list of L{objects.Disk}
4307
  @return: selected instance disks to act on
4308

4309
  """
4310
  if disks is None:
4311
    return instance.disks
4312
  else:
4313
    if not set(disks).issubset(instance.disks):
4314
      raise errors.ProgrammerError("Can only act on disks belonging to the"
4315
                                   " target instance")
4316
    return disks
4317

    
4318

    
4319
def _ShutdownInstanceDisks(lu, instance, disks=None, ignore_primary=False):
4320
  """Shutdown block devices of an instance.
4321

4322
  This does the shutdown on all nodes of the instance.
4323

4324
  If the ignore_primary is false, errors on the primary node are
4325
  ignored.
4326

4327
  """
4328
  all_result = True
4329
  disks = _ExpandCheckDisks(instance, disks)
4330

    
4331
  for disk in disks:
4332
    for node, top_disk in disk.ComputeNodeTree(instance.primary_node):
4333
      lu.cfg.SetDiskID(top_disk, node)
4334
      result = lu.rpc.call_blockdev_shutdown(node, top_disk)
4335
      msg = result.fail_msg
4336
      if msg:
4337
        lu.LogWarning("Could not shutdown block device %s on node %s: %s",
4338
                      disk.iv_name, node, msg)
4339
        if not ignore_primary or node != instance.primary_node:
4340
          all_result = False
4341
  return all_result
4342

    
4343

    
4344
def _CheckNodeFreeMemory(lu, node, reason, requested, hypervisor_name):
4345
  """Checks if a node has enough free memory.
4346

4347
  This function check if a given node has the needed amount of free
4348
  memory. In case the node has less memory or we cannot get the
4349
  information from the node, this function raise an OpPrereqError
4350
  exception.
4351

4352
  @type lu: C{LogicalUnit}
4353
  @param lu: a logical unit from which we get configuration data
4354
  @type node: C{str}
4355
  @param node: the node to check
4356
  @type reason: C{str}
4357
  @param reason: string to use in the error message
4358
  @type requested: C{int}
4359
  @param requested: the amount of memory in MiB to check for
4360
  @type hypervisor_name: C{str}
4361
  @param hypervisor_name: the hypervisor to ask for memory stats
4362
  @raise errors.OpPrereqError: if the node doesn't have enough memory, or
4363
      we cannot check the node
4364

4365
  """
4366
  nodeinfo = lu.rpc.call_node_info([node], lu.cfg.GetVGName(), hypervisor_name)
4367
  nodeinfo[node].Raise("Can't get data from node %s" % node,
4368
                       prereq=True, ecode=errors.ECODE_ENVIRON)
4369
  free_mem = nodeinfo[node].payload.get('memory_free', None)
4370
  if not isinstance(free_mem, int):
4371
    raise errors.OpPrereqError("Can't compute free memory on node %s, result"
4372
                               " was '%s'" % (node, free_mem),
4373
                               errors.ECODE_ENVIRON)
4374
  if requested > free_mem:
4375
    raise errors.OpPrereqError("Not enough memory on node %s for %s:"
4376
                               " needed %s MiB, available %s MiB" %
4377
                               (node, reason, requested, free_mem),
4378
                               errors.ECODE_NORES)
4379

    
4380

    
4381
def _CheckNodesFreeDisk(lu, nodenames, requested):
4382
  """Checks if nodes have enough free disk space in the default VG.
4383

4384
  This function check if all given nodes have the needed amount of
4385
  free disk. In case any node has less disk or we cannot get the
4386
  information from the node, this function raise an OpPrereqError
4387
  exception.
4388

4389
  @type lu: C{LogicalUnit}
4390
  @param lu: a logical unit from which we get configuration data
4391
  @type nodenames: C{list}
4392
  @param nodenames: the list of node names to check
4393
  @type requested: C{int}
4394
  @param requested: the amount of disk in MiB to check for
4395
  @raise errors.OpPrereqError: if the node doesn't have enough disk, or
4396
      we cannot check the node
4397

4398
  """
4399
  nodeinfo = lu.rpc.call_node_info(nodenames, lu.cfg.GetVGName(),
4400
                                   lu.cfg.GetHypervisorType())
4401
  for node in nodenames:
4402
    info = nodeinfo[node]
4403
    info.Raise("Cannot get current information from node %s" % node,
4404
               prereq=True, ecode=errors.ECODE_ENVIRON)
4405
    vg_free = info.payload.get("vg_free", None)
4406
    if not isinstance(vg_free, int):
4407
      raise errors.OpPrereqError("Can't compute free disk space on node %s,"
4408
                                 " result was '%s'" % (node, vg_free),
4409
                                 errors.ECODE_ENVIRON)
4410
    if requested > vg_free:
4411
      raise errors.OpPrereqError("Not enough disk space on target node %s:"
4412
                                 " required %d MiB, available %d MiB" %
4413
                                 (node, requested, vg_free),
4414
                                 errors.ECODE_NORES)
4415

    
4416

    
4417
class LUStartupInstance(LogicalUnit):
4418
  """Starts an instance.
4419

4420
  """
4421
  HPATH = "instance-start"
4422
  HTYPE = constants.HTYPE_INSTANCE
4423
  _OP_REQP = [
4424
    ("instance_name", _TNonEmptyString),
4425
    ("force", _TBool),
4426
    ("beparams", _TDict),
4427
    ("hvparams", _TDict),
4428
    ]
4429
  _OP_DEFS = [
4430
    ("beparams", _EmptyDict),
4431
    ("hvparams", _EmptyDict),
4432
    ]
4433
  REQ_BGL = False
4434

    
4435
  def CheckArguments(self):
4436
    # extra beparams
4437
    if self.op.beparams:
4438
      # fill the beparams dict
4439
      utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
4440

    
4441
  def ExpandNames(self):
4442
    self._ExpandAndLockInstance()
4443

    
4444
  def BuildHooksEnv(self):
4445
    """Build hooks env.
4446

4447
    This runs on master, primary and secondary nodes of the instance.
4448

4449
    """
4450
    env = {
4451
      "FORCE": self.op.force,
4452
      }
4453
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4454
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4455
    return env, nl, nl
4456

    
4457
  def CheckPrereq(self):
4458
    """Check prerequisites.
4459

4460
    This checks that the instance is in the cluster.
4461

4462
    """
4463
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4464
    assert self.instance is not None, \
4465
      "Cannot retrieve locked instance %s" % self.op.instance_name
4466

    
4467
    # extra hvparams
4468
    if self.op.hvparams:
4469
      # check hypervisor parameter syntax (locally)
4470
      cluster = self.cfg.GetClusterInfo()
4471
      utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
4472
      filled_hvp = cluster.FillHV(instance)
4473
      filled_hvp.update(self.op.hvparams)
4474
      hv_type = hypervisor.GetHypervisor(instance.hypervisor)
4475
      hv_type.CheckParameterSyntax(filled_hvp)
4476
      _CheckHVParams(self, instance.all_nodes, instance.hypervisor, filled_hvp)
4477

    
4478
    _CheckNodeOnline(self, instance.primary_node)
4479

    
4480
    bep = self.cfg.GetClusterInfo().FillBE(instance)
4481
    # check bridges existence
4482
    _CheckInstanceBridgesExist(self, instance)
4483

    
4484
    remote_info = self.rpc.call_instance_info(instance.primary_node,
4485
                                              instance.name,
4486
                                              instance.hypervisor)
4487
    remote_info.Raise("Error checking node %s" % instance.primary_node,
4488
                      prereq=True, ecode=errors.ECODE_ENVIRON)
4489
    if not remote_info.payload: # not running already
4490
      _CheckNodeFreeMemory(self, instance.primary_node,
4491
                           "starting instance %s" % instance.name,
4492
                           bep[constants.BE_MEMORY], instance.hypervisor)
4493

    
4494
  def Exec(self, feedback_fn):
4495
    """Start the instance.
4496

4497
    """
4498
    instance = self.instance
4499
    force = self.op.force
4500

    
4501
    self.cfg.MarkInstanceUp(instance.name)
4502

    
4503
    node_current = instance.primary_node
4504

    
4505
    _StartInstanceDisks(self, instance, force)
4506

    
4507
    result = self.rpc.call_instance_start(node_current, instance,
4508
                                          self.op.hvparams, self.op.beparams)
4509
    msg = result.fail_msg
4510
    if msg:
4511
      _ShutdownInstanceDisks(self, instance)
4512
      raise errors.OpExecError("Could not start instance: %s" % msg)
4513

    
4514

    
4515
class LURebootInstance(LogicalUnit):
4516
  """Reboot an instance.
4517

4518
  """
4519
  HPATH = "instance-reboot"
4520
  HTYPE = constants.HTYPE_INSTANCE
4521
  _OP_REQP = [
4522
    ("instance_name", _TNonEmptyString),
4523
    ("ignore_secondaries", _TBool),
4524
    ("reboot_type", _TElemOf(constants.REBOOT_TYPES)),
4525
    ]
4526
  _OP_DEFS = [("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT)]
4527
  REQ_BGL = False
4528

    
4529
  def ExpandNames(self):
4530
    self._ExpandAndLockInstance()
4531

    
4532
  def BuildHooksEnv(self):
4533
    """Build hooks env.
4534

4535
    This runs on master, primary and secondary nodes of the instance.
4536

4537
    """
4538
    env = {
4539
      "IGNORE_SECONDARIES": self.op.ignore_secondaries,
4540
      "REBOOT_TYPE": self.op.reboot_type,
4541
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
4542
      }
4543
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
4544
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4545
    return env, nl, nl
4546

    
4547
  def CheckPrereq(self):
4548
    """Check prerequisites.
4549

4550
    This checks that the instance is in the cluster.
4551

4552
    """
4553
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4554
    assert self.instance is not None, \
4555
      "Cannot retrieve locked instance %s" % self.op.instance_name
4556

    
4557
    _CheckNodeOnline(self, instance.primary_node)
4558

    
4559
    # check bridges existence
4560
    _CheckInstanceBridgesExist(self, instance)
4561

    
4562
  def Exec(self, feedback_fn):
4563
    """Reboot the instance.
4564

4565
    """
4566
    instance = self.instance
4567
    ignore_secondaries = self.op.ignore_secondaries
4568
    reboot_type = self.op.reboot_type
4569

    
4570
    node_current = instance.primary_node
4571

    
4572
    if reboot_type in [constants.INSTANCE_REBOOT_SOFT,
4573
                       constants.INSTANCE_REBOOT_HARD]:
4574
      for disk in instance.disks:
4575
        self.cfg.SetDiskID(disk, node_current)
4576
      result = self.rpc.call_instance_reboot(node_current, instance,
4577
                                             reboot_type,
4578
                                             self.op.shutdown_timeout)
4579
      result.Raise("Could not reboot instance")
4580
    else:
4581
      result = self.rpc.call_instance_shutdown(node_current, instance,
4582
                                               self.op.shutdown_timeout)
4583
      result.Raise("Could not shutdown instance for full reboot")
4584
      _ShutdownInstanceDisks(self, instance)
4585
      _StartInstanceDisks(self, instance, ignore_secondaries)
4586
      result = self.rpc.call_instance_start(node_current, instance, None, None)
4587
      msg = result.fail_msg
4588
      if msg:
4589
        _ShutdownInstanceDisks(self, instance)
4590
        raise errors.OpExecError("Could not start instance for"
4591
                                 " full reboot: %s" % msg)
4592

    
4593
    self.cfg.MarkInstanceUp(instance.name)
4594

    
4595

    
4596
class LUShutdownInstance(LogicalUnit):
4597
  """Shutdown an instance.
4598

4599
  """
4600
  HPATH = "instance-stop"
4601
  HTYPE = constants.HTYPE_INSTANCE
4602
  _OP_REQP = [("instance_name", _TNonEmptyString)]
4603
  _OP_DEFS = [("timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT)]
4604
  REQ_BGL = False
4605

    
4606
  def ExpandNames(self):
4607
    self._ExpandAndLockInstance()
4608

    
4609
  def BuildHooksEnv(self):
4610
    """Build hooks env.
4611

4612
    This runs on master, primary and secondary nodes of the instance.
4613

4614
    """
4615
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4616
    env["TIMEOUT"] = self.op.timeout
4617
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4618
    return env, nl, nl
4619

    
4620
  def CheckPrereq(self):
4621
    """Check prerequisites.
4622

4623
    This checks that the instance is in the cluster.
4624

4625
    """
4626
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4627
    assert self.instance is not None, \
4628
      "Cannot retrieve locked instance %s" % self.op.instance_name
4629
    _CheckNodeOnline(self, self.instance.primary_node)
4630

    
4631
  def Exec(self, feedback_fn):
4632
    """Shutdown the instance.
4633

4634
    """
4635
    instance = self.instance
4636
    node_current = instance.primary_node
4637
    timeout = self.op.timeout
4638
    self.cfg.MarkInstanceDown(instance.name)
4639
    result = self.rpc.call_instance_shutdown(node_current, instance, timeout)
4640
    msg = result.fail_msg
4641
    if msg:
4642
      self.proc.LogWarning("Could not shutdown instance: %s" % msg)
4643

    
4644
    _ShutdownInstanceDisks(self, instance)
4645

    
4646

    
4647
class LUReinstallInstance(LogicalUnit):
4648
  """Reinstall an instance.
4649

4650
  """
4651
  HPATH = "instance-reinstall"
4652
  HTYPE = constants.HTYPE_INSTANCE
4653
  _OP_REQP = [("instance_name", _TNonEmptyString)]
4654
  _OP_DEFS = [
4655
    ("os_type", None),
4656
    ("force_variant", False),
4657
    ]
4658
  REQ_BGL = False
4659

    
4660
  def ExpandNames(self):
4661
    self._ExpandAndLockInstance()
4662

    
4663
  def BuildHooksEnv(self):
4664
    """Build hooks env.
4665

4666
    This runs on master, primary and secondary nodes of the instance.
4667

4668
    """
4669
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4670
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4671
    return env, nl, nl
4672

    
4673
  def CheckPrereq(self):
4674
    """Check prerequisites.
4675

4676
    This checks that the instance is in the cluster and is not running.
4677

4678
    """
4679
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4680
    assert instance is not None, \
4681
      "Cannot retrieve locked instance %s" % self.op.instance_name
4682
    _CheckNodeOnline(self, instance.primary_node)
4683

    
4684
    if instance.disk_template == constants.DT_DISKLESS:
4685
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4686
                                 self.op.instance_name,
4687
                                 errors.ECODE_INVAL)
4688
    _CheckInstanceDown(self, instance, "cannot reinstall")
4689

    
4690
    if self.op.os_type is not None:
4691
      # OS verification
4692
      pnode = _ExpandNodeName(self.cfg, instance.primary_node)
4693
      _CheckNodeHasOS(self, pnode, self.op.os_type, self.op.force_variant)
4694

    
4695
    self.instance = instance
4696

    
4697
  def Exec(self, feedback_fn):
4698
    """Reinstall the instance.
4699

4700
    """
4701
    inst = self.instance
4702

    
4703
    if self.op.os_type is not None:
4704
      feedback_fn("Changing OS to '%s'..." % self.op.os_type)
4705
      inst.os = self.op.os_type
4706
      self.cfg.Update(inst, feedback_fn)
4707

    
4708
    _StartInstanceDisks(self, inst, None)
4709
    try:
4710
      feedback_fn("Running the instance OS create scripts...")
4711
      # FIXME: pass debug option from opcode to backend
4712
      result = self.rpc.call_instance_os_add(inst.primary_node, inst, True,
4713
                                             self.op.debug_level)
4714
      result.Raise("Could not install OS for instance %s on node %s" %
4715
                   (inst.name, inst.primary_node))
4716
    finally:
4717
      _ShutdownInstanceDisks(self, inst)
4718

    
4719

    
4720
class LURecreateInstanceDisks(LogicalUnit):
4721
  """Recreate an instance's missing disks.
4722

4723
  """
4724
  HPATH = "instance-recreate-disks"
4725
  HTYPE = constants.HTYPE_INSTANCE
4726
  _OP_REQP = [
4727
    ("instance_name", _TNonEmptyString),
4728
    ("disks", _TListOf(_TPositiveInt)),
4729
    ]
4730
  REQ_BGL = False
4731

    
4732
  def ExpandNames(self):
4733
    self._ExpandAndLockInstance()
4734

    
4735
  def BuildHooksEnv(self):
4736
    """Build hooks env.
4737

4738
    This runs on master, primary and secondary nodes of the instance.
4739

4740
    """
4741
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4742
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4743
    return env, nl, nl
4744

    
4745
  def CheckPrereq(self):
4746
    """Check prerequisites.
4747

4748
    This checks that the instance is in the cluster and is not running.
4749

4750
    """
4751
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4752
    assert instance is not None, \
4753
      "Cannot retrieve locked instance %s" % self.op.instance_name
4754
    _CheckNodeOnline(self, instance.primary_node)
4755

    
4756
    if instance.disk_template == constants.DT_DISKLESS:
4757
      raise errors.OpPrereqError("Instance '%s' has no disks" %
4758
                                 self.op.instance_name, errors.ECODE_INVAL)
4759
    _CheckInstanceDown(self, instance, "cannot recreate disks")
4760

    
4761
    if not self.op.disks:
4762
      self.op.disks = range(len(instance.disks))
4763
    else:
4764
      for idx in self.op.disks:
4765
        if idx >= len(instance.disks):
4766
          raise errors.OpPrereqError("Invalid disk index passed '%s'" % idx,
4767
                                     errors.ECODE_INVAL)
4768

    
4769
    self.instance = instance
4770

    
4771
  def Exec(self, feedback_fn):
4772
    """Recreate the disks.
4773

4774
    """
4775
    to_skip = []
4776
    for idx, _ in enumerate(self.instance.disks):
4777
      if idx not in self.op.disks: # disk idx has not been passed in
4778
        to_skip.append(idx)
4779
        continue
4780

    
4781
    _CreateDisks(self, self.instance, to_skip=to_skip)
4782

    
4783

    
4784
class LURenameInstance(LogicalUnit):
4785
  """Rename an instance.
4786

4787
  """
4788
  HPATH = "instance-rename"
4789
  HTYPE = constants.HTYPE_INSTANCE
4790
  _OP_REQP = [
4791
    ("instance_name", _TNonEmptyString),
4792
    ("new_name", _TNonEmptyString),
4793
    ("ignore_ip", _TBool),
4794
    ("check_name", _TBool),
4795
    ]
4796
  _OP_DEFS = [("ignore_ip", False), ("check_name", True)]
4797

    
4798
  def BuildHooksEnv(self):
4799
    """Build hooks env.
4800

4801
    This runs on master, primary and secondary nodes of the instance.
4802

4803
    """
4804
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4805
    env["INSTANCE_NEW_NAME"] = self.op.new_name
4806
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
4807
    return env, nl, nl
4808

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

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

4814
    """
4815
    self.op.instance_name = _ExpandInstanceName(self.cfg,
4816
                                                self.op.instance_name)
4817
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4818
    assert instance is not None
4819
    _CheckNodeOnline(self, instance.primary_node)
4820
    _CheckInstanceDown(self, instance, "cannot rename")
4821
    self.instance = instance
4822

    
4823
    # new name verification
4824
    if self.op.check_name:
4825
      name_info = utils.GetHostInfo(self.op.new_name)
4826
      self.op.new_name = name_info.name
4827

    
4828
    new_name = self.op.new_name
4829

    
4830
    instance_list = self.cfg.GetInstanceList()
4831
    if new_name in instance_list:
4832
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
4833
                                 new_name, errors.ECODE_EXISTS)
4834

    
4835
    if not self.op.ignore_ip:
4836
      if utils.TcpPing(name_info.ip, constants.DEFAULT_NODED_PORT):
4837
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
4838
                                   (name_info.ip, new_name),
4839
                                   errors.ECODE_NOTUNIQUE)
4840

    
4841
  def Exec(self, feedback_fn):
4842
    """Reinstall the instance.
4843

4844
    """
4845
    inst = self.instance
4846
    old_name = inst.name
4847

    
4848
    if inst.disk_template == constants.DT_FILE:
4849
      old_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4850

    
4851
    self.cfg.RenameInstance(inst.name, self.op.new_name)
4852
    # Change the instance lock. This is definitely safe while we hold the BGL
4853
    self.context.glm.remove(locking.LEVEL_INSTANCE, old_name)
4854
    self.context.glm.add(locking.LEVEL_INSTANCE, self.op.new_name)
4855

    
4856
    # re-read the instance from the configuration after rename
4857
    inst = self.cfg.GetInstanceInfo(self.op.new_name)
4858

    
4859
    if inst.disk_template == constants.DT_FILE:
4860
      new_file_storage_dir = os.path.dirname(inst.disks[0].logical_id[1])
4861
      result = self.rpc.call_file_storage_dir_rename(inst.primary_node,
4862
                                                     old_file_storage_dir,
4863
                                                     new_file_storage_dir)
4864
      result.Raise("Could not rename on node %s directory '%s' to '%s'"
4865
                   " (but the instance has been renamed in Ganeti)" %
4866
                   (inst.primary_node, old_file_storage_dir,
4867
                    new_file_storage_dir))
4868

    
4869
    _StartInstanceDisks(self, inst, None)
4870
    try:
4871
      result = self.rpc.call_instance_run_rename(inst.primary_node, inst,
4872
                                                 old_name, self.op.debug_level)
4873
      msg = result.fail_msg
4874
      if msg:
4875
        msg = ("Could not run OS rename script for instance %s on node %s"
4876
               " (but the instance has been renamed in Ganeti): %s" %
4877
               (inst.name, inst.primary_node, msg))
4878
        self.proc.LogWarning(msg)
4879
    finally:
4880
      _ShutdownInstanceDisks(self, inst)
4881

    
4882

    
4883
class LURemoveInstance(LogicalUnit):
4884
  """Remove an instance.
4885

4886
  """
4887
  HPATH = "instance-remove"
4888
  HTYPE = constants.HTYPE_INSTANCE
4889
  _OP_REQP = [
4890
    ("instance_name", _TNonEmptyString),
4891
    ("ignore_failures", _TBool),
4892
    ]
4893
  _OP_DEFS = [("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT)]
4894
  REQ_BGL = False
4895

    
4896
  def ExpandNames(self):
4897
    self._ExpandAndLockInstance()
4898
    self.needed_locks[locking.LEVEL_NODE] = []
4899
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
4900

    
4901
  def DeclareLocks(self, level):
4902
    if level == locking.LEVEL_NODE:
4903
      self._LockInstancesNodes()
4904

    
4905
  def BuildHooksEnv(self):
4906
    """Build hooks env.
4907

4908
    This runs on master, primary and secondary nodes of the instance.
4909

4910
    """
4911
    env = _BuildInstanceHookEnvByObject(self, self.instance)
4912
    env["SHUTDOWN_TIMEOUT"] = self.op.shutdown_timeout
4913
    nl = [self.cfg.GetMasterNode()]
4914
    nl_post = list(self.instance.all_nodes) + nl
4915
    return env, nl, nl_post
4916

    
4917
  def CheckPrereq(self):
4918
    """Check prerequisites.
4919

4920
    This checks that the instance is in the cluster.
4921

4922
    """
4923
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
4924
    assert self.instance is not None, \
4925
      "Cannot retrieve locked instance %s" % self.op.instance_name
4926

    
4927
  def Exec(self, feedback_fn):
4928
    """Remove the instance.
4929

4930
    """
4931
    instance = self.instance
4932
    logging.info("Shutting down instance %s on node %s",
4933
                 instance.name, instance.primary_node)
4934

    
4935
    result = self.rpc.call_instance_shutdown(instance.primary_node, instance,
4936
                                             self.op.shutdown_timeout)
4937
    msg = result.fail_msg
4938
    if msg:
4939
      if self.op.ignore_failures:
4940
        feedback_fn("Warning: can't shutdown instance: %s" % msg)
4941
      else:
4942
        raise errors.OpExecError("Could not shutdown instance %s on"
4943
                                 " node %s: %s" %
4944
                                 (instance.name, instance.primary_node, msg))
4945

    
4946
    _RemoveInstance(self, feedback_fn, instance, self.op.ignore_failures)
4947

    
4948

    
4949
def _RemoveInstance(lu, feedback_fn, instance, ignore_failures):
4950
  """Utility function to remove an instance.
4951

4952
  """
4953
  logging.info("Removing block devices for instance %s", instance.name)
4954

    
4955
  if not _RemoveDisks(lu, instance):
4956
    if not ignore_failures:
4957
      raise errors.OpExecError("Can't remove instance's disks")
4958
    feedback_fn("Warning: can't remove instance's disks")
4959

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

    
4962
  lu.cfg.RemoveInstance(instance.name)
4963

    
4964
  assert not lu.remove_locks.get(locking.LEVEL_INSTANCE), \
4965
    "Instance lock removal conflict"
4966

    
4967
  # Remove lock for the instance
4968
  lu.remove_locks[locking.LEVEL_INSTANCE] = instance.name
4969

    
4970

    
4971
class LUQueryInstances(NoHooksLU):
4972
  """Logical unit for querying instances.
4973

4974
  """
4975
  # pylint: disable-msg=W0142
4976
  _OP_REQP = [
4977
    ("output_fields", _TListOf(_TNonEmptyString)),
4978
    ("names", _TListOf(_TNonEmptyString)),
4979
    ("use_locking", _TBool),
4980
    ]
4981
  REQ_BGL = False
4982
  _SIMPLE_FIELDS = ["name", "os", "network_port", "hypervisor",
4983
                    "serial_no", "ctime", "mtime", "uuid"]
4984
  _FIELDS_STATIC = utils.FieldSet(*["name", "os", "pnode", "snodes",
4985
                                    "admin_state",
4986
                                    "disk_template", "ip", "mac", "bridge",
4987
                                    "nic_mode", "nic_link",
4988
                                    "sda_size", "sdb_size", "vcpus", "tags",
4989
                                    "network_port", "beparams",
4990
                                    r"(disk)\.(size)/([0-9]+)",
4991
                                    r"(disk)\.(sizes)", "disk_usage",
4992
                                    r"(nic)\.(mac|ip|mode|link)/([0-9]+)",
4993
                                    r"(nic)\.(bridge)/([0-9]+)",
4994
                                    r"(nic)\.(macs|ips|modes|links|bridges)",
4995
                                    r"(disk|nic)\.(count)",
4996
                                    "hvparams",
4997
                                    ] + _SIMPLE_FIELDS +
4998
                                  ["hv/%s" % name
4999
                                   for name in constants.HVS_PARAMETERS
5000
                                   if name not in constants.HVC_GLOBALS] +
5001
                                  ["be/%s" % name
5002
                                   for name in constants.BES_PARAMETERS])
5003
  _FIELDS_DYNAMIC = utils.FieldSet("oper_state", "oper_ram", "status")
5004

    
5005

    
5006
  def CheckArguments(self):
5007
    _CheckOutputFields(static=self._FIELDS_STATIC,
5008
                       dynamic=self._FIELDS_DYNAMIC,
5009
                       selected=self.op.output_fields)
5010

    
5011
  def ExpandNames(self):
5012
    self.needed_locks = {}
5013
    self.share_locks[locking.LEVEL_INSTANCE] = 1
5014
    self.share_locks[locking.LEVEL_NODE] = 1
5015

    
5016
    if self.op.names:
5017
      self.wanted = _GetWantedInstances(self, self.op.names)
5018
    else:
5019
      self.wanted = locking.ALL_SET
5020

    
5021
    self.do_node_query = self._FIELDS_STATIC.NonMatching(self.op.output_fields)
5022
    self.do_locking = self.do_node_query and self.op.use_locking
5023
    if self.do_locking:
5024
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted
5025
      self.needed_locks[locking.LEVEL_NODE] = []
5026
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5027

    
5028
  def DeclareLocks(self, level):
5029
    if level == locking.LEVEL_NODE and self.do_locking:
5030
      self._LockInstancesNodes()
5031

    
5032
  def Exec(self, feedback_fn):
5033
    """Computes the list of nodes and their attributes.
5034

5035
    """
5036
    # pylint: disable-msg=R0912
5037
    # way too many branches here
5038
    all_info = self.cfg.GetAllInstancesInfo()
5039
    if self.wanted == locking.ALL_SET:
5040
      # caller didn't specify instance names, so ordering is not important
5041
      if self.do_locking:
5042
        instance_names = self.acquired_locks[locking.LEVEL_INSTANCE]
5043
      else:
5044
        instance_names = all_info.keys()
5045
      instance_names = utils.NiceSort(instance_names)
5046
    else:
5047
      # caller did specify names, so we must keep the ordering
5048
      if self.do_locking:
5049
        tgt_set = self.acquired_locks[locking.LEVEL_INSTANCE]
5050
      else:
5051
        tgt_set = all_info.keys()
5052
      missing = set(self.wanted).difference(tgt_set)
5053
      if missing:
5054
        raise errors.OpExecError("Some instances were removed before"
5055
                                 " retrieving their data: %s" % missing)
5056
      instance_names = self.wanted
5057

    
5058
    instance_list = [all_info[iname] for iname in instance_names]
5059

    
5060
    # begin data gathering
5061

    
5062
    nodes = frozenset([inst.primary_node for inst in instance_list])
5063
    hv_list = list(set([inst.hypervisor for inst in instance_list]))
5064

    
5065
    bad_nodes = []
5066
    off_nodes = []
5067
    if self.do_node_query:
5068
      live_data = {}
5069
      node_data = self.rpc.call_all_instances_info(nodes, hv_list)
5070
      for name in nodes:
5071
        result = node_data[name]
5072
        if result.offline:
5073
          # offline nodes will be in both lists
5074
          off_nodes.append(name)
5075
        if result.fail_msg:
5076
          bad_nodes.append(name)
5077
        else:
5078
          if result.payload:
5079
            live_data.update(result.payload)
5080
          # else no instance is alive
5081
    else:
5082
      live_data = dict([(name, {}) for name in instance_names])
5083

    
5084
    # end data gathering
5085

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

    
5249
    return output
5250

    
5251

    
5252
class LUFailoverInstance(LogicalUnit):
5253
  """Failover an instance.
5254

5255
  """
5256
  HPATH = "instance-failover"
5257
  HTYPE = constants.HTYPE_INSTANCE
5258
  _OP_REQP = [
5259
    ("instance_name", _TNonEmptyString),
5260
    ("ignore_consistency", _TBool),
5261
    ]
5262
  _OP_DEFS = [("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT)]
5263
  REQ_BGL = False
5264

    
5265
  def ExpandNames(self):
5266
    self._ExpandAndLockInstance()
5267
    self.needed_locks[locking.LEVEL_NODE] = []
5268
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5269

    
5270
  def DeclareLocks(self, level):
5271
    if level == locking.LEVEL_NODE:
5272
      self._LockInstancesNodes()
5273

    
5274
  def BuildHooksEnv(self):
5275
    """Build hooks env.
5276

5277
    This runs on master, primary and secondary nodes of the instance.
5278

5279
    """
5280
    instance = self.instance
5281
    source_node = instance.primary_node
5282
    target_node = instance.secondary_nodes[0]
5283
    env = {
5284
      "IGNORE_CONSISTENCY": self.op.ignore_consistency,
5285
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5286
      "OLD_PRIMARY": source_node,
5287
      "OLD_SECONDARY": target_node,
5288
      "NEW_PRIMARY": target_node,
5289
      "NEW_SECONDARY": source_node,
5290
      }
5291
    env.update(_BuildInstanceHookEnvByObject(self, instance))
5292
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5293
    nl_post = list(nl)
5294
    nl_post.append(source_node)
5295
    return env, nl, nl_post
5296

    
5297
  def CheckPrereq(self):
5298
    """Check prerequisites.
5299

5300
    This checks that the instance is in the cluster.
5301

5302
    """
5303
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5304
    assert self.instance is not None, \
5305
      "Cannot retrieve locked instance %s" % self.op.instance_name
5306

    
5307
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5308
    if instance.disk_template not in constants.DTS_NET_MIRROR:
5309
      raise errors.OpPrereqError("Instance's disk layout is not"
5310
                                 " network mirrored, cannot failover.",
5311
                                 errors.ECODE_STATE)
5312

    
5313
    secondary_nodes = instance.secondary_nodes
5314
    if not secondary_nodes:
5315
      raise errors.ProgrammerError("no secondary node but using "
5316
                                   "a mirrored disk template")
5317

    
5318
    target_node = secondary_nodes[0]
5319
    _CheckNodeOnline(self, target_node)
5320
    _CheckNodeNotDrained(self, target_node)
5321
    if instance.admin_up:
5322
      # check memory requirements on the secondary node
5323
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5324
                           instance.name, bep[constants.BE_MEMORY],
5325
                           instance.hypervisor)
5326
    else:
5327
      self.LogInfo("Not checking memory on the secondary node as"
5328
                   " instance will not be started")
5329

    
5330
    # check bridge existance
5331
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5332

    
5333
  def Exec(self, feedback_fn):
5334
    """Failover an instance.
5335

5336
    The failover is done by shutting it down on its present node and
5337
    starting it on the secondary.
5338

5339
    """
5340
    instance = self.instance
5341

    
5342
    source_node = instance.primary_node
5343
    target_node = instance.secondary_nodes[0]
5344

    
5345
    if instance.admin_up:
5346
      feedback_fn("* checking disk consistency between source and target")
5347
      for dev in instance.disks:
5348
        # for drbd, these are drbd over lvm
5349
        if not _CheckDiskConsistency(self, dev, target_node, False):
5350
          if not self.op.ignore_consistency:
5351
            raise errors.OpExecError("Disk %s is degraded on target node,"
5352
                                     " aborting failover." % dev.iv_name)
5353
    else:
5354
      feedback_fn("* not checking disk consistency as instance is not running")
5355

    
5356
    feedback_fn("* shutting down instance on source node")
5357
    logging.info("Shutting down instance %s on node %s",
5358
                 instance.name, source_node)
5359

    
5360
    result = self.rpc.call_instance_shutdown(source_node, instance,
5361
                                             self.op.shutdown_timeout)
5362
    msg = result.fail_msg
5363
    if msg:
5364
      if self.op.ignore_consistency:
5365
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5366
                             " Proceeding anyway. Please make sure node"
5367
                             " %s is down. Error details: %s",
5368
                             instance.name, source_node, source_node, msg)
5369
      else:
5370
        raise errors.OpExecError("Could not shutdown instance %s on"
5371
                                 " node %s: %s" %
5372
                                 (instance.name, source_node, msg))
5373

    
5374
    feedback_fn("* deactivating the instance's disks on source node")
5375
    if not _ShutdownInstanceDisks(self, instance, ignore_primary=True):
5376
      raise errors.OpExecError("Can't shut down the instance's disks.")
5377

    
5378
    instance.primary_node = target_node
5379
    # distribute new instance config to the other nodes
5380
    self.cfg.Update(instance, feedback_fn)
5381

    
5382
    # Only start the instance if it's marked as up
5383
    if instance.admin_up:
5384
      feedback_fn("* activating the instance's disks on target node")
5385
      logging.info("Starting instance %s on node %s",
5386
                   instance.name, target_node)
5387

    
5388
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5389
                                           ignore_secondaries=True)
5390
      if not disks_ok:
5391
        _ShutdownInstanceDisks(self, instance)
5392
        raise errors.OpExecError("Can't activate the instance's disks")
5393

    
5394
      feedback_fn("* starting the instance on the target node")
5395
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5396
      msg = result.fail_msg
5397
      if msg:
5398
        _ShutdownInstanceDisks(self, instance)
5399
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5400
                                 (instance.name, target_node, msg))
5401

    
5402

    
5403
class LUMigrateInstance(LogicalUnit):
5404
  """Migrate an instance.
5405

5406
  This is migration without shutting down, compared to the failover,
5407
  which is done with shutdown.
5408

5409
  """
5410
  HPATH = "instance-migrate"
5411
  HTYPE = constants.HTYPE_INSTANCE
5412
  _OP_REQP = [
5413
    ("instance_name", _TNonEmptyString),
5414
    ("live", _TBool),
5415
    ("cleanup", _TBool),
5416
    ]
5417

    
5418
  REQ_BGL = False
5419

    
5420
  def ExpandNames(self):
5421
    self._ExpandAndLockInstance()
5422

    
5423
    self.needed_locks[locking.LEVEL_NODE] = []
5424
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
5425

    
5426
    self._migrater = TLMigrateInstance(self, self.op.instance_name,
5427
                                       self.op.live, self.op.cleanup)
5428
    self.tasklets = [self._migrater]
5429

    
5430
  def DeclareLocks(self, level):
5431
    if level == locking.LEVEL_NODE:
5432
      self._LockInstancesNodes()
5433

    
5434
  def BuildHooksEnv(self):
5435
    """Build hooks env.
5436

5437
    This runs on master, primary and secondary nodes of the instance.
5438

5439
    """
5440
    instance = self._migrater.instance
5441
    source_node = instance.primary_node
5442
    target_node = instance.secondary_nodes[0]
5443
    env = _BuildInstanceHookEnvByObject(self, instance)
5444
    env["MIGRATE_LIVE"] = self.op.live
5445
    env["MIGRATE_CLEANUP"] = self.op.cleanup
5446
    env.update({
5447
        "OLD_PRIMARY": source_node,
5448
        "OLD_SECONDARY": target_node,
5449
        "NEW_PRIMARY": target_node,
5450
        "NEW_SECONDARY": source_node,
5451
        })
5452
    nl = [self.cfg.GetMasterNode()] + list(instance.secondary_nodes)
5453
    nl_post = list(nl)
5454
    nl_post.append(source_node)
5455
    return env, nl, nl_post
5456

    
5457

    
5458
class LUMoveInstance(LogicalUnit):
5459
  """Move an instance by data-copying.
5460

5461
  """
5462
  HPATH = "instance-move"
5463
  HTYPE = constants.HTYPE_INSTANCE
5464
  _OP_REQP = [
5465
    ("instance_name", _TNonEmptyString),
5466
    ("target_node", _TNonEmptyString),
5467
    ]
5468
  _OP_DEFS = [("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT)]
5469
  REQ_BGL = False
5470

    
5471
  def ExpandNames(self):
5472
    self._ExpandAndLockInstance()
5473
    target_node = _ExpandNodeName(self.cfg, self.op.target_node)
5474
    self.op.target_node = target_node
5475
    self.needed_locks[locking.LEVEL_NODE] = [target_node]
5476
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5477

    
5478
  def DeclareLocks(self, level):
5479
    if level == locking.LEVEL_NODE:
5480
      self._LockInstancesNodes(primary_only=True)
5481

    
5482
  def BuildHooksEnv(self):
5483
    """Build hooks env.
5484

5485
    This runs on master, primary and secondary nodes of the instance.
5486

5487
    """
5488
    env = {
5489
      "TARGET_NODE": self.op.target_node,
5490
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
5491
      }
5492
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
5493
    nl = [self.cfg.GetMasterNode()] + [self.instance.primary_node,
5494
                                       self.op.target_node]
5495
    return env, nl, nl
5496

    
5497
  def CheckPrereq(self):
5498
    """Check prerequisites.
5499

5500
    This checks that the instance is in the cluster.
5501

5502
    """
5503
    self.instance = instance = self.cfg.GetInstanceInfo(self.op.instance_name)
5504
    assert self.instance is not None, \
5505
      "Cannot retrieve locked instance %s" % self.op.instance_name
5506

    
5507
    node = self.cfg.GetNodeInfo(self.op.target_node)
5508
    assert node is not None, \
5509
      "Cannot retrieve locked node %s" % self.op.target_node
5510

    
5511
    self.target_node = target_node = node.name
5512

    
5513
    if target_node == instance.primary_node:
5514
      raise errors.OpPrereqError("Instance %s is already on the node %s" %
5515
                                 (instance.name, target_node),
5516
                                 errors.ECODE_STATE)
5517

    
5518
    bep = self.cfg.GetClusterInfo().FillBE(instance)
5519

    
5520
    for idx, dsk in enumerate(instance.disks):
5521
      if dsk.dev_type not in (constants.LD_LV, constants.LD_FILE):
5522
        raise errors.OpPrereqError("Instance disk %d has a complex layout,"
5523
                                   " cannot copy" % idx, errors.ECODE_STATE)
5524

    
5525
    _CheckNodeOnline(self, target_node)
5526
    _CheckNodeNotDrained(self, target_node)
5527

    
5528
    if instance.admin_up:
5529
      # check memory requirements on the secondary node
5530
      _CheckNodeFreeMemory(self, target_node, "failing over instance %s" %
5531
                           instance.name, bep[constants.BE_MEMORY],
5532
                           instance.hypervisor)
5533
    else:
5534
      self.LogInfo("Not checking memory on the secondary node as"
5535
                   " instance will not be started")
5536

    
5537
    # check bridge existance
5538
    _CheckInstanceBridgesExist(self, instance, node=target_node)
5539

    
5540
  def Exec(self, feedback_fn):
5541
    """Move an instance.
5542

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

5546
    """
5547
    instance = self.instance
5548

    
5549
    source_node = instance.primary_node
5550
    target_node = self.target_node
5551

    
5552
    self.LogInfo("Shutting down instance %s on source node %s",
5553
                 instance.name, source_node)
5554

    
5555
    result = self.rpc.call_instance_shutdown(source_node, instance,
5556
                                             self.op.shutdown_timeout)
5557
    msg = result.fail_msg
5558
    if msg:
5559
      if self.op.ignore_consistency:
5560
        self.proc.LogWarning("Could not shutdown instance %s on node %s."
5561
                             " Proceeding anyway. Please make sure node"
5562
                             " %s is down. Error details: %s",
5563
                             instance.name, source_node, source_node, msg)
5564
      else:
5565
        raise errors.OpExecError("Could not shutdown instance %s on"
5566
                                 " node %s: %s" %
5567
                                 (instance.name, source_node, msg))
5568

    
5569
    # create the target disks
5570
    try:
5571
      _CreateDisks(self, instance, target_node=target_node)
5572
    except errors.OpExecError:
5573
      self.LogWarning("Device creation failed, reverting...")
5574
      try:
5575
        _RemoveDisks(self, instance, target_node=target_node)
5576
      finally:
5577
        self.cfg.ReleaseDRBDMinors(instance.name)
5578
        raise
5579

    
5580
    cluster_name = self.cfg.GetClusterInfo().cluster_name
5581

    
5582
    errs = []
5583
    # activate, get path, copy the data over
5584
    for idx, disk in enumerate(instance.disks):
5585
      self.LogInfo("Copying data for disk %d", idx)
5586
      result = self.rpc.call_blockdev_assemble(target_node, disk,
5587
                                               instance.name, True)
5588
      if result.fail_msg:
5589
        self.LogWarning("Can't assemble newly created disk %d: %s",
5590
                        idx, result.fail_msg)
5591
        errs.append(result.fail_msg)
5592
        break
5593
      dev_path = result.payload
5594
      result = self.rpc.call_blockdev_export(source_node, disk,
5595
                                             target_node, dev_path,
5596
                                             cluster_name)
5597
      if result.fail_msg:
5598
        self.LogWarning("Can't copy data over for disk %d: %s",
5599
                        idx, result.fail_msg)
5600
        errs.append(result.fail_msg)
5601
        break
5602

    
5603
    if errs:
5604
      self.LogWarning("Some disks failed to copy, aborting")
5605
      try:
5606
        _RemoveDisks(self, instance, target_node=target_node)
5607
      finally:
5608
        self.cfg.ReleaseDRBDMinors(instance.name)
5609
        raise errors.OpExecError("Errors during disk copy: %s" %
5610
                                 (",".join(errs),))
5611

    
5612
    instance.primary_node = target_node
5613
    self.cfg.Update(instance, feedback_fn)
5614

    
5615
    self.LogInfo("Removing the disks on the original node")
5616
    _RemoveDisks(self, instance, target_node=source_node)
5617

    
5618
    # Only start the instance if it's marked as up
5619
    if instance.admin_up:
5620
      self.LogInfo("Starting instance %s on node %s",
5621
                   instance.name, target_node)
5622

    
5623
      disks_ok, _ = _AssembleInstanceDisks(self, instance,
5624
                                           ignore_secondaries=True)
5625
      if not disks_ok:
5626
        _ShutdownInstanceDisks(self, instance)
5627
        raise errors.OpExecError("Can't activate the instance's disks")
5628

    
5629
      result = self.rpc.call_instance_start(target_node, instance, None, None)
5630
      msg = result.fail_msg
5631
      if msg:
5632
        _ShutdownInstanceDisks(self, instance)
5633
        raise errors.OpExecError("Could not start instance %s on node %s: %s" %
5634
                                 (instance.name, target_node, msg))
5635

    
5636

    
5637
class LUMigrateNode(LogicalUnit):
5638
  """Migrate all instances from a node.
5639

5640
  """
5641
  HPATH = "node-migrate"
5642
  HTYPE = constants.HTYPE_NODE
5643
  _OP_REQP = [
5644
    ("node_name", _TNonEmptyString),
5645
    ("live", _TBool),
5646
    ]
5647
  REQ_BGL = False
5648

    
5649
  def ExpandNames(self):
5650
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
5651

    
5652
    self.needed_locks = {
5653
      locking.LEVEL_NODE: [self.op.node_name],
5654
      }
5655

    
5656
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
5657

    
5658
    # Create tasklets for migrating instances for all instances on this node
5659
    names = []
5660
    tasklets = []
5661

    
5662
    for inst in _GetNodePrimaryInstances(self.cfg, self.op.node_name):
5663
      logging.debug("Migrating instance %s", inst.name)
5664
      names.append(inst.name)
5665

    
5666
      tasklets.append(TLMigrateInstance(self, inst.name, self.op.live, False))
5667

    
5668
    self.tasklets = tasklets
5669

    
5670
    # Declare instance locks
5671
    self.needed_locks[locking.LEVEL_INSTANCE] = names
5672

    
5673
  def DeclareLocks(self, level):
5674
    if level == locking.LEVEL_NODE:
5675
      self._LockInstancesNodes()
5676

    
5677
  def BuildHooksEnv(self):
5678
    """Build hooks env.
5679

5680
    This runs on the master, the primary and all the secondaries.
5681

5682
    """
5683
    env = {
5684
      "NODE_NAME": self.op.node_name,
5685
      }
5686

    
5687
    nl = [self.cfg.GetMasterNode()]
5688

    
5689
    return (env, nl, nl)
5690

    
5691

    
5692
class TLMigrateInstance(Tasklet):
5693
  def __init__(self, lu, instance_name, live, cleanup):
5694
    """Initializes this class.
5695

5696
    """
5697
    Tasklet.__init__(self, lu)
5698

    
5699
    # Parameters
5700
    self.instance_name = instance_name
5701
    self.live = live
5702
    self.cleanup = cleanup
5703

    
5704
  def CheckPrereq(self):
5705
    """Check prerequisites.
5706

5707
    This checks that the instance is in the cluster.
5708

5709
    """
5710
    instance_name = _ExpandInstanceName(self.lu.cfg, self.instance_name)
5711
    instance = self.cfg.GetInstanceInfo(instance_name)
5712
    assert instance is not None
5713

    
5714
    if instance.disk_template != constants.DT_DRBD8:
5715
      raise errors.OpPrereqError("Instance's disk layout is not"
5716
                                 " drbd8, cannot migrate.", errors.ECODE_STATE)
5717

    
5718
    secondary_nodes = instance.secondary_nodes
5719
    if not secondary_nodes:
5720
      raise errors.ConfigurationError("No secondary node but using"
5721
                                      " drbd8 disk template")
5722

    
5723
    i_be = self.cfg.GetClusterInfo().FillBE(instance)
5724

    
5725
    target_node = secondary_nodes[0]
5726
    # check memory requirements on the secondary node
5727
    _CheckNodeFreeMemory(self.lu, target_node, "migrating instance %s" %
5728
                         instance.name, i_be[constants.BE_MEMORY],
5729
                         instance.hypervisor)
5730

    
5731
    # check bridge existance
5732
    _CheckInstanceBridgesExist(self.lu, instance, node=target_node)
5733

    
5734
    if not self.cleanup:
5735
      _CheckNodeNotDrained(self.lu, target_node)
5736
      result = self.rpc.call_instance_migratable(instance.primary_node,
5737
                                                 instance)
5738
      result.Raise("Can't migrate, please use failover",
5739
                   prereq=True, ecode=errors.ECODE_STATE)
5740

    
5741
    self.instance = instance
5742

    
5743
  def _WaitUntilSync(self):
5744
    """Poll with custom rpc for disk sync.
5745

5746
    This uses our own step-based rpc call.
5747

5748
    """
5749
    self.feedback_fn("* wait until resync is done")
5750
    all_done = False
5751
    while not all_done:
5752
      all_done = True
5753
      result = self.rpc.call_drbd_wait_sync(self.all_nodes,
5754
                                            self.nodes_ip,
5755
                                            self.instance.disks)
5756
      min_percent = 100
5757
      for node, nres in result.items():
5758
        nres.Raise("Cannot resync disks on node %s" % node)
5759
        node_done, node_percent = nres.payload
5760
        all_done = all_done and node_done
5761
        if node_percent is not None:
5762
          min_percent = min(min_percent, node_percent)
5763
      if not all_done:
5764
        if min_percent < 100:
5765
          self.feedback_fn("   - progress: %.1f%%" % min_percent)
5766
        time.sleep(2)
5767

    
5768
  def _EnsureSecondary(self, node):
5769
    """Demote a node to secondary.
5770

5771
    """
5772
    self.feedback_fn("* switching node %s to secondary mode" % node)
5773

    
5774
    for dev in self.instance.disks:
5775
      self.cfg.SetDiskID(dev, node)
5776

    
5777
    result = self.rpc.call_blockdev_close(node, self.instance.name,
5778
                                          self.instance.disks)
5779
    result.Raise("Cannot change disk to secondary on node %s" % node)
5780

    
5781
  def _GoStandalone(self):
5782
    """Disconnect from the network.
5783

5784
    """
5785
    self.feedback_fn("* changing into standalone mode")
5786
    result = self.rpc.call_drbd_disconnect_net(self.all_nodes, self.nodes_ip,
5787
                                               self.instance.disks)
5788
    for node, nres in result.items():
5789
      nres.Raise("Cannot disconnect disks node %s" % node)
5790

    
5791
  def _GoReconnect(self, multimaster):
5792
    """Reconnect to the network.
5793

5794
    """
5795
    if multimaster:
5796
      msg = "dual-master"
5797
    else:
5798
      msg = "single-master"
5799
    self.feedback_fn("* changing disks into %s mode" % msg)
5800
    result = self.rpc.call_drbd_attach_net(self.all_nodes, self.nodes_ip,
5801
                                           self.instance.disks,
5802
                                           self.instance.name, multimaster)
5803
    for node, nres in result.items():
5804
      nres.Raise("Cannot change disks config on node %s" % node)
5805

    
5806
  def _ExecCleanup(self):
5807
    """Try to cleanup after a failed migration.
5808

5809
    The cleanup is done by:
5810
      - check that the instance is running only on one node
5811
        (and update the config if needed)
5812
      - change disks on its secondary node to secondary
5813
      - wait until disks are fully synchronized
5814
      - disconnect from the network
5815
      - change disks into single-master mode
5816
      - wait again until disks are fully synchronized
5817

5818
    """
5819
    instance = self.instance
5820
    target_node = self.target_node
5821
    source_node = self.source_node
5822

    
5823
    # check running on only one node
5824
    self.feedback_fn("* checking where the instance actually runs"
5825
                     " (if this hangs, the hypervisor might be in"
5826
                     " a bad state)")
5827
    ins_l = self.rpc.call_instance_list(self.all_nodes, [instance.hypervisor])
5828
    for node, result in ins_l.items():
5829
      result.Raise("Can't contact node %s" % node)
5830

    
5831
    runningon_source = instance.name in ins_l[source_node].payload
5832
    runningon_target = instance.name in ins_l[target_node].payload
5833

    
5834
    if runningon_source and runningon_target:
5835
      raise errors.OpExecError("Instance seems to be running on two nodes,"
5836
                               " or the hypervisor is confused. You will have"
5837
                               " to ensure manually that it runs only on one"
5838
                               " and restart this operation.")
5839

    
5840
    if not (runningon_source or runningon_target):
5841
      raise errors.OpExecError("Instance does not seem to be running at all."
5842
                               " In this case, it's safer to repair by"
5843
                               " running 'gnt-instance stop' to ensure disk"
5844
                               " shutdown, and then restarting it.")
5845

    
5846
    if runningon_target:
5847
      # the migration has actually succeeded, we need to update the config
5848
      self.feedback_fn("* instance running on secondary node (%s),"
5849
                       " updating config" % target_node)
5850
      instance.primary_node = target_node
5851
      self.cfg.Update(instance, self.feedback_fn)
5852
      demoted_node = source_node
5853
    else:
5854
      self.feedback_fn("* instance confirmed to be running on its"
5855
                       " primary node (%s)" % source_node)
5856
      demoted_node = target_node
5857

    
5858
    self._EnsureSecondary(demoted_node)
5859
    try:
5860
      self._WaitUntilSync()
5861
    except errors.OpExecError:
5862
      # we ignore here errors, since if the device is standalone, it
5863
      # won't be able to sync
5864
      pass
5865
    self._GoStandalone()
5866
    self._GoReconnect(False)
5867
    self._WaitUntilSync()
5868

    
5869
    self.feedback_fn("* done")
5870

    
5871
  def _RevertDiskStatus(self):
5872
    """Try to revert the disk status after a failed migration.
5873

5874
    """
5875
    target_node = self.target_node
5876
    try:
5877
      self._EnsureSecondary(target_node)
5878
      self._GoStandalone()
5879
      self._GoReconnect(False)
5880
      self._WaitUntilSync()
5881
    except errors.OpExecError, err:
5882
      self.lu.LogWarning("Migration failed and I can't reconnect the"
5883
                         " drives: error '%s'\n"
5884
                         "Please look and recover the instance status" %
5885
                         str(err))
5886

    
5887
  def _AbortMigration(self):
5888
    """Call the hypervisor code to abort a started migration.
5889

5890
    """
5891
    instance = self.instance
5892
    target_node = self.target_node
5893
    migration_info = self.migration_info
5894

    
5895
    abort_result = self.rpc.call_finalize_migration(target_node,
5896
                                                    instance,
5897
                                                    migration_info,
5898
                                                    False)
5899
    abort_msg = abort_result.fail_msg
5900
    if abort_msg:
5901
      logging.error("Aborting migration failed on target node %s: %s",
5902
                    target_node, abort_msg)
5903
      # Don't raise an exception here, as we stil have to try to revert the
5904
      # disk status, even if this step failed.
5905

    
5906
  def _ExecMigration(self):
5907
    """Migrate an instance.
5908

5909
    The migrate is done by:
5910
      - change the disks into dual-master mode
5911
      - wait until disks are fully synchronized again
5912
      - migrate the instance
5913
      - change disks on the new secondary node (the old primary) to secondary
5914
      - wait until disks are fully synchronized
5915
      - change disks into single-master mode
5916

5917
    """
5918
    instance = self.instance
5919
    target_node = self.target_node
5920
    source_node = self.source_node
5921

    
5922
    self.feedback_fn("* checking disk consistency between source and target")
5923
    for dev in instance.disks:
5924
      if not _CheckDiskConsistency(self.lu, dev, target_node, False):
5925
        raise errors.OpExecError("Disk %s is degraded or not fully"
5926
                                 " synchronized on target node,"
5927
                                 " aborting migrate." % dev.iv_name)
5928

    
5929
    # First get the migration information from the remote node
5930
    result = self.rpc.call_migration_info(source_node, instance)
5931
    msg = result.fail_msg
5932
    if msg:
5933
      log_err = ("Failed fetching source migration information from %s: %s" %
5934
                 (source_node, msg))
5935
      logging.error(log_err)
5936
      raise errors.OpExecError(log_err)
5937

    
5938
    self.migration_info = migration_info = result.payload
5939

    
5940
    # Then switch the disks to master/master mode
5941
    self._EnsureSecondary(target_node)
5942
    self._GoStandalone()
5943
    self._GoReconnect(True)
5944
    self._WaitUntilSync()
5945

    
5946
    self.feedback_fn("* preparing %s to accept the instance" % target_node)
5947
    result = self.rpc.call_accept_instance(target_node,
5948
                                           instance,
5949
                                           migration_info,
5950
                                           self.nodes_ip[target_node])
5951

    
5952
    msg = result.fail_msg
5953
    if msg:
5954
      logging.error("Instance pre-migration failed, trying to revert"
5955
                    " disk status: %s", msg)
5956
      self.feedback_fn("Pre-migration failed, aborting")
5957
      self._AbortMigration()
5958
      self._RevertDiskStatus()
5959
      raise errors.OpExecError("Could not pre-migrate instance %s: %s" %
5960
                               (instance.name, msg))
5961

    
5962
    self.feedback_fn("* migrating instance to %s" % target_node)
5963
    time.sleep(10)
5964
    result = self.rpc.call_instance_migrate(source_node, instance,
5965
                                            self.nodes_ip[target_node],
5966
                                            self.live)
5967
    msg = result.fail_msg
5968
    if msg:
5969
      logging.error("Instance migration failed, trying to revert"
5970
                    " disk status: %s", msg)
5971
      self.feedback_fn("Migration failed, aborting")
5972
      self._AbortMigration()
5973
      self._RevertDiskStatus()
5974
      raise errors.OpExecError("Could not migrate instance %s: %s" %
5975
                               (instance.name, msg))
5976
    time.sleep(10)
5977

    
5978
    instance.primary_node = target_node
5979
    # distribute new instance config to the other nodes
5980
    self.cfg.Update(instance, self.feedback_fn)
5981

    
5982
    result = self.rpc.call_finalize_migration(target_node,
5983
                                              instance,
5984
                                              migration_info,
5985
                                              True)
5986
    msg = result.fail_msg
5987
    if msg:
5988
      logging.error("Instance migration succeeded, but finalization failed:"
5989
                    " %s", msg)
5990
      raise errors.OpExecError("Could not finalize instance migration: %s" %
5991
                               msg)
5992

    
5993
    self._EnsureSecondary(source_node)
5994
    self._WaitUntilSync()
5995
    self._GoStandalone()
5996
    self._GoReconnect(False)
5997
    self._WaitUntilSync()
5998

    
5999
    self.feedback_fn("* done")
6000

    
6001
  def Exec(self, feedback_fn):
6002
    """Perform the migration.
6003

6004
    """
6005
    feedback_fn("Migrating instance %s" % self.instance.name)
6006

    
6007
    self.feedback_fn = feedback_fn
6008

    
6009
    self.source_node = self.instance.primary_node
6010
    self.target_node = self.instance.secondary_nodes[0]
6011
    self.all_nodes = [self.source_node, self.target_node]
6012
    self.nodes_ip = {
6013
      self.source_node: self.cfg.GetNodeInfo(self.source_node).secondary_ip,
6014
      self.target_node: self.cfg.GetNodeInfo(self.target_node).secondary_ip,
6015
      }
6016

    
6017
    if self.cleanup:
6018
      return self._ExecCleanup()
6019
    else:
6020
      return self._ExecMigration()
6021

    
6022

    
6023
def _CreateBlockDev(lu, node, instance, device, force_create,
6024
                    info, force_open):
6025
  """Create a tree of block devices on a given node.
6026

6027
  If this device type has to be created on secondaries, create it and
6028
  all its children.
6029

6030
  If not, just recurse to children keeping the same 'force' value.
6031

6032
  @param lu: the lu on whose behalf we execute
6033
  @param node: the node on which to create the device
6034
  @type instance: L{objects.Instance}
6035
  @param instance: the instance which owns the device
6036
  @type device: L{objects.Disk}
6037
  @param device: the device to create
6038
  @type force_create: boolean
6039
  @param force_create: whether to force creation of this device; this
6040
      will be change to True whenever we find a device which has
6041
      CreateOnSecondary() attribute
6042
  @param info: the extra 'metadata' we should attach to the device
6043
      (this will be represented as a LVM tag)
6044
  @type force_open: boolean
6045
  @param force_open: this parameter will be passes to the
6046
      L{backend.BlockdevCreate} function where it specifies
6047
      whether we run on primary or not, and it affects both
6048
      the child assembly and the device own Open() execution
6049

6050
  """
6051
  if device.CreateOnSecondary():
6052
    force_create = True
6053

    
6054
  if device.children:
6055
    for child in device.children:
6056
      _CreateBlockDev(lu, node, instance, child, force_create,
6057
                      info, force_open)
6058

    
6059
  if not force_create:
6060
    return
6061

    
6062
  _CreateSingleBlockDev(lu, node, instance, device, info, force_open)
6063

    
6064

    
6065
def _CreateSingleBlockDev(lu, node, instance, device, info, force_open):
6066
  """Create a single block device on a given node.
6067

6068
  This will not recurse over children of the device, so they must be
6069
  created in advance.
6070

6071
  @param lu: the lu on whose behalf we execute
6072
  @param node: the node on which to create the device
6073
  @type instance: L{objects.Instance}
6074
  @param instance: the instance which owns the device
6075
  @type device: L{objects.Disk}
6076
  @param device: the device to create
6077
  @param info: the extra 'metadata' we should attach to the device
6078
      (this will be represented as a LVM tag)
6079
  @type force_open: boolean
6080
  @param force_open: this parameter will be passes to the
6081
      L{backend.BlockdevCreate} function where it specifies
6082
      whether we run on primary or not, and it affects both
6083
      the child assembly and the device own Open() execution
6084

6085
  """
6086
  lu.cfg.SetDiskID(device, node)
6087
  result = lu.rpc.call_blockdev_create(node, device, device.size,
6088
                                       instance.name, force_open, info)
6089
  result.Raise("Can't create block device %s on"
6090
               " node %s for instance %s" % (device, node, instance.name))
6091
  if device.physical_id is None:
6092
    device.physical_id = result.payload
6093

    
6094

    
6095
def _GenerateUniqueNames(lu, exts):
6096
  """Generate a suitable LV name.
6097

6098
  This will generate a logical volume name for the given instance.
6099

6100
  """
6101
  results = []
6102
  for val in exts:
6103
    new_id = lu.cfg.GenerateUniqueID(lu.proc.GetECId())
6104
    results.append("%s%s" % (new_id, val))
6105
  return results
6106

    
6107

    
6108
def _GenerateDRBD8Branch(lu, primary, secondary, size, names, iv_name,
6109
                         p_minor, s_minor):
6110
  """Generate a drbd8 device complete with its children.
6111

6112
  """
6113
  port = lu.cfg.AllocatePort()
6114
  vgname = lu.cfg.GetVGName()
6115
  shared_secret = lu.cfg.GenerateDRBDSecret(lu.proc.GetECId())
6116
  dev_data = objects.Disk(dev_type=constants.LD_LV, size=size,
6117
                          logical_id=(vgname, names[0]))
6118
  dev_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
6119
                          logical_id=(vgname, names[1]))
6120
  drbd_dev = objects.Disk(dev_type=constants.LD_DRBD8, size=size,
6121
                          logical_id=(primary, secondary, port,
6122
                                      p_minor, s_minor,
6123
                                      shared_secret),
6124
                          children=[dev_data, dev_meta],
6125
                          iv_name=iv_name)
6126
  return drbd_dev
6127

    
6128

    
6129
def _GenerateDiskTemplate(lu, template_name,
6130
                          instance_name, primary_node,
6131
                          secondary_nodes, disk_info,
6132
                          file_storage_dir, file_driver,
6133
                          base_index):
6134
  """Generate the entire disk layout for a given template type.
6135

6136
  """
6137
  #TODO: compute space requirements
6138

    
6139
  vgname = lu.cfg.GetVGName()
6140
  disk_count = len(disk_info)
6141
  disks = []
6142
  if template_name == constants.DT_DISKLESS:
6143
    pass
6144
  elif template_name == constants.DT_PLAIN:
6145
    if len(secondary_nodes) != 0:
6146
      raise errors.ProgrammerError("Wrong template configuration")
6147

    
6148
    names = _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6149
                                      for i in range(disk_count)])
6150
    for idx, disk in enumerate(disk_info):
6151
      disk_index = idx + base_index
6152
      disk_dev = objects.Disk(dev_type=constants.LD_LV, size=disk["size"],
6153
                              logical_id=(vgname, names[idx]),
6154
                              iv_name="disk/%d" % disk_index,
6155
                              mode=disk["mode"])
6156
      disks.append(disk_dev)
6157
  elif template_name == constants.DT_DRBD8:
6158
    if len(secondary_nodes) != 1:
6159
      raise errors.ProgrammerError("Wrong template configuration")
6160
    remote_node = secondary_nodes[0]
6161
    minors = lu.cfg.AllocateDRBDMinor(
6162
      [primary_node, remote_node] * len(disk_info), instance_name)
6163

    
6164
    names = []
6165
    for lv_prefix in _GenerateUniqueNames(lu, [".disk%d" % (base_index + i)
6166
                                               for i in range(disk_count)]):
6167
      names.append(lv_prefix + "_data")
6168
      names.append(lv_prefix + "_meta")
6169
    for idx, disk in enumerate(disk_info):
6170
      disk_index = idx + base_index
6171
      disk_dev = _GenerateDRBD8Branch(lu, primary_node, remote_node,
6172
                                      disk["size"], names[idx*2:idx*2+2],
6173
                                      "disk/%d" % disk_index,
6174
                                      minors[idx*2], minors[idx*2+1])
6175
      disk_dev.mode = disk["mode"]
6176
      disks.append(disk_dev)
6177
  elif template_name == constants.DT_FILE:
6178
    if len(secondary_nodes) != 0:
6179
      raise errors.ProgrammerError("Wrong template configuration")
6180

    
6181
    _RequireFileStorage()
6182

    
6183
    for idx, disk in enumerate(disk_info):
6184
      disk_index = idx + base_index
6185
      disk_dev = objects.Disk(dev_type=constants.LD_FILE, size=disk["size"],
6186
                              iv_name="disk/%d" % disk_index,
6187
                              logical_id=(file_driver,
6188
                                          "%s/disk%d" % (file_storage_dir,
6189
                                                         disk_index)),
6190
                              mode=disk["mode"])
6191
      disks.append(disk_dev)
6192
  else:
6193
    raise errors.ProgrammerError("Invalid disk template '%s'" % template_name)
6194
  return disks
6195

    
6196

    
6197
def _GetInstanceInfoText(instance):
6198
  """Compute that text that should be added to the disk's metadata.
6199

6200
  """
6201
  return "originstname+%s" % instance.name
6202

    
6203

    
6204
def _CreateDisks(lu, instance, to_skip=None, target_node=None):
6205
  """Create all disks for an instance.
6206

6207
  This abstracts away some work from AddInstance.
6208

6209
  @type lu: L{LogicalUnit}
6210
  @param lu: the logical unit on whose behalf we execute
6211
  @type instance: L{objects.Instance}
6212
  @param instance: the instance whose disks we should create
6213
  @type to_skip: list
6214
  @param to_skip: list of indices to skip
6215
  @type target_node: string
6216
  @param target_node: if passed, overrides the target node for creation
6217
  @rtype: boolean
6218
  @return: the success of the creation
6219

6220
  """
6221
  info = _GetInstanceInfoText(instance)
6222
  if target_node is None:
6223
    pnode = instance.primary_node
6224
    all_nodes = instance.all_nodes
6225
  else:
6226
    pnode = target_node
6227
    all_nodes = [pnode]
6228

    
6229
  if instance.disk_template == constants.DT_FILE:
6230
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6231
    result = lu.rpc.call_file_storage_dir_create(pnode, file_storage_dir)
6232

    
6233
    result.Raise("Failed to create directory '%s' on"
6234
                 " node %s" % (file_storage_dir, pnode))
6235

    
6236
  # Note: this needs to be kept in sync with adding of disks in
6237
  # LUSetInstanceParams
6238
  for idx, device in enumerate(instance.disks):
6239
    if to_skip and idx in to_skip:
6240
      continue
6241
    logging.info("Creating volume %s for instance %s",
6242
                 device.iv_name, instance.name)
6243
    #HARDCODE
6244
    for node in all_nodes:
6245
      f_create = node == pnode
6246
      _CreateBlockDev(lu, node, instance, device, f_create, info, f_create)
6247

    
6248

    
6249
def _RemoveDisks(lu, instance, target_node=None):
6250
  """Remove all disks for an instance.
6251

6252
  This abstracts away some work from `AddInstance()` and
6253
  `RemoveInstance()`. Note that in case some of the devices couldn't
6254
  be removed, the removal will continue with the other ones (compare
6255
  with `_CreateDisks()`).
6256

6257
  @type lu: L{LogicalUnit}
6258
  @param lu: the logical unit on whose behalf we execute
6259
  @type instance: L{objects.Instance}
6260
  @param instance: the instance whose disks we should remove
6261
  @type target_node: string
6262
  @param target_node: used to override the node on which to remove the disks
6263
  @rtype: boolean
6264
  @return: the success of the removal
6265

6266
  """
6267
  logging.info("Removing block devices for instance %s", instance.name)
6268

    
6269
  all_result = True
6270
  for device in instance.disks:
6271
    if target_node:
6272
      edata = [(target_node, device)]
6273
    else:
6274
      edata = device.ComputeNodeTree(instance.primary_node)
6275
    for node, disk in edata:
6276
      lu.cfg.SetDiskID(disk, node)
6277
      msg = lu.rpc.call_blockdev_remove(node, disk).fail_msg
6278
      if msg:
6279
        lu.LogWarning("Could not remove block device %s on node %s,"
6280
                      " continuing anyway: %s", device.iv_name, node, msg)
6281
        all_result = False
6282

    
6283
  if instance.disk_template == constants.DT_FILE:
6284
    file_storage_dir = os.path.dirname(instance.disks[0].logical_id[1])
6285
    if target_node:
6286
      tgt = target_node
6287
    else:
6288
      tgt = instance.primary_node
6289
    result = lu.rpc.call_file_storage_dir_remove(tgt, file_storage_dir)
6290
    if result.fail_msg:
6291
      lu.LogWarning("Could not remove directory '%s' on node %s: %s",
6292
                    file_storage_dir, instance.primary_node, result.fail_msg)
6293
      all_result = False
6294

    
6295
  return all_result
6296

    
6297

    
6298
def _ComputeDiskSize(disk_template, disks):
6299
  """Compute disk size requirements in the volume group
6300

6301
  """
6302
  # Required free disk space as a function of disk and swap space
6303
  req_size_dict = {
6304
    constants.DT_DISKLESS: None,
6305
    constants.DT_PLAIN: sum(d["size"] for d in disks),
6306
    # 128 MB are added for drbd metadata for each disk
6307
    constants.DT_DRBD8: sum(d["size"] + 128 for d in disks),
6308
    constants.DT_FILE: None,
6309
  }
6310

    
6311
  if disk_template not in req_size_dict:
6312
    raise errors.ProgrammerError("Disk template '%s' size requirement"
6313
                                 " is unknown" %  disk_template)
6314

    
6315
  return req_size_dict[disk_template]
6316

    
6317

    
6318
def _CheckHVParams(lu, nodenames, hvname, hvparams):
6319
  """Hypervisor parameter validation.
6320

6321
  This function abstract the hypervisor parameter validation to be
6322
  used in both instance create and instance modify.
6323

6324
  @type lu: L{LogicalUnit}
6325
  @param lu: the logical unit for which we check
6326
  @type nodenames: list
6327
  @param nodenames: the list of nodes on which we should check
6328
  @type hvname: string
6329
  @param hvname: the name of the hypervisor we should use
6330
  @type hvparams: dict
6331
  @param hvparams: the parameters which we need to check
6332
  @raise errors.OpPrereqError: if the parameters are not valid
6333

6334
  """
6335
  hvinfo = lu.rpc.call_hypervisor_validate_params(nodenames,
6336
                                                  hvname,
6337
                                                  hvparams)
6338
  for node in nodenames:
6339
    info = hvinfo[node]
6340
    if info.offline:
6341
      continue
6342
    info.Raise("Hypervisor parameter validation failed on node %s" % node)
6343

    
6344

    
6345
def _CheckOSParams(lu, required, nodenames, osname, osparams):
6346
  """OS parameters validation.
6347

6348
  @type lu: L{LogicalUnit}
6349
  @param lu: the logical unit for which we check
6350
  @type required: boolean
6351
  @param required: whether the validation should fail if the OS is not
6352
      found
6353
  @type nodenames: list
6354
  @param nodenames: the list of nodes on which we should check
6355
  @type osname: string
6356
  @param osname: the name of the hypervisor we should use
6357
  @type osparams: dict
6358
  @param osparams: the parameters which we need to check
6359
  @raise errors.OpPrereqError: if the parameters are not valid
6360

6361
  """
6362
  result = lu.rpc.call_os_validate(required, nodenames, osname,
6363
                                   [constants.OS_VALIDATE_PARAMETERS],
6364
                                   osparams)
6365
  for node, nres in result.items():
6366
    # we don't check for offline cases since this should be run only
6367
    # against the master node and/or an instance's nodes
6368
    nres.Raise("OS Parameters validation failed on node %s" % node)
6369
    if not nres.payload:
6370
      lu.LogInfo("OS %s not found on node %s, validation skipped",
6371
                 osname, node)
6372

    
6373

    
6374
class LUCreateInstance(LogicalUnit):
6375
  """Create an instance.
6376

6377
  """
6378
  HPATH = "instance-add"
6379
  HTYPE = constants.HTYPE_INSTANCE
6380
  _OP_REQP = [
6381
    ("instance_name", _TNonEmptyString),
6382
    ("mode", _TElemOf(constants.INSTANCE_CREATE_MODES)),
6383
    ("start", _TBool),
6384
    ("wait_for_sync", _TBool),
6385
    ("ip_check", _TBool),
6386
    ("disks", _TListOf(_TDict)),
6387
    ("nics", _TListOf(_TDict)),
6388
    ("hvparams", _TDict),
6389
    ("beparams", _TDict),
6390
    ("osparams", _TDict),
6391
    ]
6392
  _OP_DEFS = [
6393
    ("name_check", True),
6394
    ("no_install", False),
6395
    ("os_type", None),
6396
    ("force_variant", False),
6397
    ("source_handshake", None),
6398
    ("source_x509_ca", None),
6399
    ("source_instance_name", None),
6400
    ("src_node", None),
6401
    ("src_path", None),
6402
    ("pnode", None),
6403
    ("snode", None),
6404
    ("iallocator", None),
6405
    ("hypervisor", None),
6406
    ("disk_template", None),
6407
    ("identify_defaults", None),
6408
    ]
6409
  REQ_BGL = False
6410

    
6411
  def CheckArguments(self):
6412
    """Check arguments.
6413

6414
    """
6415
    # do not require name_check to ease forward/backward compatibility
6416
    # for tools
6417
    if self.op.no_install and self.op.start:
6418
      self.LogInfo("No-installation mode selected, disabling startup")
6419
      self.op.start = False
6420
    # validate/normalize the instance name
6421
    self.op.instance_name = utils.HostInfo.NormalizeName(self.op.instance_name)
6422
    if self.op.ip_check and not self.op.name_check:
6423
      # TODO: make the ip check more flexible and not depend on the name check
6424
      raise errors.OpPrereqError("Cannot do ip checks without a name check",
6425
                                 errors.ECODE_INVAL)
6426

    
6427
    # check nics' parameter names
6428
    for nic in self.op.nics:
6429
      utils.ForceDictType(nic, constants.INIC_PARAMS_TYPES)
6430

    
6431
    # check disks. parameter names and consistent adopt/no-adopt strategy
6432
    has_adopt = has_no_adopt = False
6433
    for disk in self.op.disks:
6434
      utils.ForceDictType(disk, constants.IDISK_PARAMS_TYPES)
6435
      if "adopt" in disk:
6436
        has_adopt = True
6437
      else:
6438
        has_no_adopt = True
6439
    if has_adopt and has_no_adopt:
6440
      raise errors.OpPrereqError("Either all disks are adopted or none is",
6441
                                 errors.ECODE_INVAL)
6442
    if has_adopt:
6443
      if self.op.disk_template not in constants.DTS_MAY_ADOPT:
6444
        raise errors.OpPrereqError("Disk adoption is not supported for the"
6445
                                   " '%s' disk template" %
6446
                                   self.op.disk_template,
6447
                                   errors.ECODE_INVAL)
6448
      if self.op.iallocator is not None:
6449
        raise errors.OpPrereqError("Disk adoption not allowed with an"
6450
                                   " iallocator script", errors.ECODE_INVAL)
6451
      if self.op.mode == constants.INSTANCE_IMPORT:
6452
        raise errors.OpPrereqError("Disk adoption not allowed for"
6453
                                   " instance import", errors.ECODE_INVAL)
6454

    
6455
    self.adopt_disks = has_adopt
6456

    
6457
    # instance name verification
6458
    if self.op.name_check:
6459
      self.hostname1 = utils.GetHostInfo(self.op.instance_name)
6460
      self.op.instance_name = self.hostname1.name
6461
      # used in CheckPrereq for ip ping check
6462
      self.check_ip = self.hostname1.ip
6463
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6464
      raise errors.OpPrereqError("Remote imports require names to be checked" %
6465
                                 errors.ECODE_INVAL)
6466
    else:
6467
      self.check_ip = None
6468

    
6469
    # file storage checks
6470
    if (self.op.file_driver and
6471
        not self.op.file_driver in constants.FILE_DRIVER):
6472
      raise errors.OpPrereqError("Invalid file driver name '%s'" %
6473
                                 self.op.file_driver, errors.ECODE_INVAL)
6474

    
6475
    if self.op.file_storage_dir and os.path.isabs(self.op.file_storage_dir):
6476
      raise errors.OpPrereqError("File storage directory path not absolute",
6477
                                 errors.ECODE_INVAL)
6478

    
6479
    ### Node/iallocator related checks
6480
    if [self.op.iallocator, self.op.pnode].count(None) != 1:
6481
      raise errors.OpPrereqError("One and only one of iallocator and primary"
6482
                                 " node must be given",
6483
                                 errors.ECODE_INVAL)
6484

    
6485
    self._cds = _GetClusterDomainSecret()
6486

    
6487
    if self.op.mode == constants.INSTANCE_IMPORT:
6488
      # On import force_variant must be True, because if we forced it at
6489
      # initial install, our only chance when importing it back is that it
6490
      # works again!
6491
      self.op.force_variant = True
6492

    
6493
      if self.op.no_install:
6494
        self.LogInfo("No-installation mode has no effect during import")
6495

    
6496
    elif self.op.mode == constants.INSTANCE_CREATE:
6497
      if self.op.os_type is None:
6498
        raise errors.OpPrereqError("No guest OS specified",
6499
                                   errors.ECODE_INVAL)
6500
      if self.op.disk_template is None:
6501
        raise errors.OpPrereqError("No disk template specified",
6502
                                   errors.ECODE_INVAL)
6503

    
6504
    elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
6505
      # Check handshake to ensure both clusters have the same domain secret
6506
      src_handshake = self.op.source_handshake
6507
      if not src_handshake:
6508
        raise errors.OpPrereqError("Missing source handshake",
6509
                                   errors.ECODE_INVAL)
6510

    
6511
      errmsg = masterd.instance.CheckRemoteExportHandshake(self._cds,
6512
                                                           src_handshake)
6513
      if errmsg:
6514
        raise errors.OpPrereqError("Invalid handshake: %s" % errmsg,
6515
                                   errors.ECODE_INVAL)
6516

    
6517
      # Load and check source CA
6518
      self.source_x509_ca_pem = self.op.source_x509_ca
6519
      if not self.source_x509_ca_pem:
6520
        raise errors.OpPrereqError("Missing source X509 CA",
6521
                                   errors.ECODE_INVAL)
6522

    
6523
      try:
6524
        (cert, _) = utils.LoadSignedX509Certificate(self.source_x509_ca_pem,
6525
                                                    self._cds)
6526
      except OpenSSL.crypto.Error, err:
6527
        raise errors.OpPrereqError("Unable to load source X509 CA (%s)" %
6528
                                   (err, ), errors.ECODE_INVAL)
6529

    
6530
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
6531
      if errcode is not None:
6532
        raise errors.OpPrereqError("Invalid source X509 CA (%s)" % (msg, ),
6533
                                   errors.ECODE_INVAL)
6534

    
6535
      self.source_x509_ca = cert
6536

    
6537
      src_instance_name = self.op.source_instance_name
6538
      if not src_instance_name:
6539
        raise errors.OpPrereqError("Missing source instance name",
6540
                                   errors.ECODE_INVAL)
6541

    
6542
      self.source_instance_name = \
6543
        utils.GetHostInfo(utils.HostInfo.NormalizeName(src_instance_name)).name
6544

    
6545
    else:
6546
      raise errors.OpPrereqError("Invalid instance creation mode %r" %
6547
                                 self.op.mode, errors.ECODE_INVAL)
6548

    
6549
  def ExpandNames(self):
6550
    """ExpandNames for CreateInstance.
6551

6552
    Figure out the right locks for instance creation.
6553

6554
    """
6555
    self.needed_locks = {}
6556

    
6557
    instance_name = self.op.instance_name
6558
    # this is just a preventive check, but someone might still add this
6559
    # instance in the meantime, and creation will fail at lock-add time
6560
    if instance_name in self.cfg.GetInstanceList():
6561
      raise errors.OpPrereqError("Instance '%s' is already in the cluster" %
6562
                                 instance_name, errors.ECODE_EXISTS)
6563

    
6564
    self.add_locks[locking.LEVEL_INSTANCE] = instance_name
6565

    
6566
    if self.op.iallocator:
6567
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6568
    else:
6569
      self.op.pnode = _ExpandNodeName(self.cfg, self.op.pnode)
6570
      nodelist = [self.op.pnode]
6571
      if self.op.snode is not None:
6572
        self.op.snode = _ExpandNodeName(self.cfg, self.op.snode)
6573
        nodelist.append(self.op.snode)
6574
      self.needed_locks[locking.LEVEL_NODE] = nodelist
6575

    
6576
    # in case of import lock the source node too
6577
    if self.op.mode == constants.INSTANCE_IMPORT:
6578
      src_node = self.op.src_node
6579
      src_path = self.op.src_path
6580

    
6581
      if src_path is None:
6582
        self.op.src_path = src_path = self.op.instance_name
6583

    
6584
      if src_node is None:
6585
        self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
6586
        self.op.src_node = None
6587
        if os.path.isabs(src_path):
6588
          raise errors.OpPrereqError("Importing an instance from an absolute"
6589
                                     " path requires a source node option.",
6590
                                     errors.ECODE_INVAL)
6591
      else:
6592
        self.op.src_node = src_node = _ExpandNodeName(self.cfg, src_node)
6593
        if self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET:
6594
          self.needed_locks[locking.LEVEL_NODE].append(src_node)
6595
        if not os.path.isabs(src_path):
6596
          self.op.src_path = src_path = \
6597
            utils.PathJoin(constants.EXPORT_DIR, src_path)
6598

    
6599
  def _RunAllocator(self):
6600
    """Run the allocator based on input opcode.
6601

6602
    """
6603
    nics = [n.ToDict() for n in self.nics]
6604
    ial = IAllocator(self.cfg, self.rpc,
6605
                     mode=constants.IALLOCATOR_MODE_ALLOC,
6606
                     name=self.op.instance_name,
6607
                     disk_template=self.op.disk_template,
6608
                     tags=[],
6609
                     os=self.op.os_type,
6610
                     vcpus=self.be_full[constants.BE_VCPUS],
6611
                     mem_size=self.be_full[constants.BE_MEMORY],
6612
                     disks=self.disks,
6613
                     nics=nics,
6614
                     hypervisor=self.op.hypervisor,
6615
                     )
6616

    
6617
    ial.Run(self.op.iallocator)
6618

    
6619
    if not ial.success:
6620
      raise errors.OpPrereqError("Can't compute nodes using"
6621
                                 " iallocator '%s': %s" %
6622
                                 (self.op.iallocator, ial.info),
6623
                                 errors.ECODE_NORES)
6624
    if len(ial.result) != ial.required_nodes:
6625
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
6626
                                 " of nodes (%s), required %s" %
6627
                                 (self.op.iallocator, len(ial.result),
6628
                                  ial.required_nodes), errors.ECODE_FAULT)
6629
    self.op.pnode = ial.result[0]
6630
    self.LogInfo("Selected nodes for instance %s via iallocator %s: %s",
6631
                 self.op.instance_name, self.op.iallocator,
6632
                 utils.CommaJoin(ial.result))
6633
    if ial.required_nodes == 2:
6634
      self.op.snode = ial.result[1]
6635

    
6636
  def BuildHooksEnv(self):
6637
    """Build hooks env.
6638

6639
    This runs on master, primary and secondary nodes of the instance.
6640

6641
    """
6642
    env = {
6643
      "ADD_MODE": self.op.mode,
6644
      }
6645
    if self.op.mode == constants.INSTANCE_IMPORT:
6646
      env["SRC_NODE"] = self.op.src_node
6647
      env["SRC_PATH"] = self.op.src_path
6648
      env["SRC_IMAGES"] = self.src_images
6649

    
6650
    env.update(_BuildInstanceHookEnv(
6651
      name=self.op.instance_name,
6652
      primary_node=self.op.pnode,
6653
      secondary_nodes=self.secondaries,
6654
      status=self.op.start,
6655
      os_type=self.op.os_type,
6656
      memory=self.be_full[constants.BE_MEMORY],
6657
      vcpus=self.be_full[constants.BE_VCPUS],
6658
      nics=_NICListToTuple(self, self.nics),
6659
      disk_template=self.op.disk_template,
6660
      disks=[(d["size"], d["mode"]) for d in self.disks],
6661
      bep=self.be_full,
6662
      hvp=self.hv_full,
6663
      hypervisor_name=self.op.hypervisor,
6664
    ))
6665

    
6666
    nl = ([self.cfg.GetMasterNode(), self.op.pnode] +
6667
          self.secondaries)
6668
    return env, nl, nl
6669

    
6670
  def _ReadExportInfo(self):
6671
    """Reads the export information from disk.
6672

6673
    It will override the opcode source node and path with the actual
6674
    information, if these two were not specified before.
6675

6676
    @return: the export information
6677

6678
    """
6679
    assert self.op.mode == constants.INSTANCE_IMPORT
6680

    
6681
    src_node = self.op.src_node
6682
    src_path = self.op.src_path
6683

    
6684
    if src_node is None:
6685
      locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
6686
      exp_list = self.rpc.call_export_list(locked_nodes)
6687
      found = False
6688
      for node in exp_list:
6689
        if exp_list[node].fail_msg:
6690
          continue
6691
        if src_path in exp_list[node].payload:
6692
          found = True
6693
          self.op.src_node = src_node = node
6694
          self.op.src_path = src_path = utils.PathJoin(constants.EXPORT_DIR,
6695
                                                       src_path)
6696
          break
6697
      if not found:
6698
        raise errors.OpPrereqError("No export found for relative path %s" %
6699
                                    src_path, errors.ECODE_INVAL)
6700

    
6701
    _CheckNodeOnline(self, src_node)
6702
    result = self.rpc.call_export_info(src_node, src_path)
6703
    result.Raise("No export or invalid export found in dir %s" % src_path)
6704

    
6705
    export_info = objects.SerializableConfigParser.Loads(str(result.payload))
6706
    if not export_info.has_section(constants.INISECT_EXP):
6707
      raise errors.ProgrammerError("Corrupted export config",
6708
                                   errors.ECODE_ENVIRON)
6709

    
6710
    ei_version = export_info.get(constants.INISECT_EXP, "version")
6711
    if (int(ei_version) != constants.EXPORT_VERSION):
6712
      raise errors.OpPrereqError("Wrong export version %s (wanted %d)" %
6713
                                 (ei_version, constants.EXPORT_VERSION),
6714
                                 errors.ECODE_ENVIRON)
6715
    return export_info
6716

    
6717
  def _ReadExportParams(self, einfo):
6718
    """Use export parameters as defaults.
6719

6720
    In case the opcode doesn't specify (as in override) some instance
6721
    parameters, then try to use them from the export information, if
6722
    that declares them.
6723

6724
    """
6725
    self.op.os_type = einfo.get(constants.INISECT_EXP, "os")
6726

    
6727
    if self.op.disk_template is None:
6728
      if einfo.has_option(constants.INISECT_INS, "disk_template"):
6729
        self.op.disk_template = einfo.get(constants.INISECT_INS,
6730
                                          "disk_template")
6731
      else:
6732
        raise errors.OpPrereqError("No disk template specified and the export"
6733
                                   " is missing the disk_template information",
6734
                                   errors.ECODE_INVAL)
6735

    
6736
    if not self.op.disks:
6737
      if einfo.has_option(constants.INISECT_INS, "disk_count"):
6738
        disks = []
6739
        # TODO: import the disk iv_name too
6740
        for idx in range(einfo.getint(constants.INISECT_INS, "disk_count")):
6741
          disk_sz = einfo.getint(constants.INISECT_INS, "disk%d_size" % idx)
6742
          disks.append({"size": disk_sz})
6743
        self.op.disks = disks
6744
      else:
6745
        raise errors.OpPrereqError("No disk info specified and the export"
6746
                                   " is missing the disk information",
6747
                                   errors.ECODE_INVAL)
6748

    
6749
    if (not self.op.nics and
6750
        einfo.has_option(constants.INISECT_INS, "nic_count")):
6751
      nics = []
6752
      for idx in range(einfo.getint(constants.INISECT_INS, "nic_count")):
6753
        ndict = {}
6754
        for name in list(constants.NICS_PARAMETERS) + ["ip", "mac"]:
6755
          v = einfo.get(constants.INISECT_INS, "nic%d_%s" % (idx, name))
6756
          ndict[name] = v
6757
        nics.append(ndict)
6758
      self.op.nics = nics
6759

    
6760
    if (self.op.hypervisor is None and
6761
        einfo.has_option(constants.INISECT_INS, "hypervisor")):
6762
      self.op.hypervisor = einfo.get(constants.INISECT_INS, "hypervisor")
6763
    if einfo.has_section(constants.INISECT_HYP):
6764
      # use the export parameters but do not override the ones
6765
      # specified by the user
6766
      for name, value in einfo.items(constants.INISECT_HYP):
6767
        if name not in self.op.hvparams:
6768
          self.op.hvparams[name] = value
6769

    
6770
    if einfo.has_section(constants.INISECT_BEP):
6771
      # use the parameters, without overriding
6772
      for name, value in einfo.items(constants.INISECT_BEP):
6773
        if name not in self.op.beparams:
6774
          self.op.beparams[name] = value
6775
    else:
6776
      # try to read the parameters old style, from the main section
6777
      for name in constants.BES_PARAMETERS:
6778
        if (name not in self.op.beparams and
6779
            einfo.has_option(constants.INISECT_INS, name)):
6780
          self.op.beparams[name] = einfo.get(constants.INISECT_INS, name)
6781

    
6782
    if einfo.has_section(constants.INISECT_OSP):
6783
      # use the parameters, without overriding
6784
      for name, value in einfo.items(constants.INISECT_OSP):
6785
        if name not in self.op.osparams:
6786
          self.op.osparams[name] = value
6787

    
6788
  def _RevertToDefaults(self, cluster):
6789
    """Revert the instance parameters to the default values.
6790

6791
    """
6792
    # hvparams
6793
    hv_defs = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type, {})
6794
    for name in self.op.hvparams.keys():
6795
      if name in hv_defs and hv_defs[name] == self.op.hvparams[name]:
6796
        del self.op.hvparams[name]
6797
    # beparams
6798
    be_defs = cluster.SimpleFillBE({})
6799
    for name in self.op.beparams.keys():
6800
      if name in be_defs and be_defs[name] == self.op.beparams[name]:
6801
        del self.op.beparams[name]
6802
    # nic params
6803
    nic_defs = cluster.SimpleFillNIC({})
6804
    for nic in self.op.nics:
6805
      for name in constants.NICS_PARAMETERS:
6806
        if name in nic and name in nic_defs and nic[name] == nic_defs[name]:
6807
          del nic[name]
6808
    # osparams
6809
    os_defs = cluster.SimpleFillOS(self.op.os_type, {})
6810
    for name in self.op.osparams.keys():
6811
      if name in os_defs and os_defs[name] == self.op.osparams[name]:
6812
        del self.op.osparams[name]
6813

    
6814
  def CheckPrereq(self):
6815
    """Check prerequisites.
6816

6817
    """
6818
    if self.op.mode == constants.INSTANCE_IMPORT:
6819
      export_info = self._ReadExportInfo()
6820
      self._ReadExportParams(export_info)
6821

    
6822
    _CheckDiskTemplate(self.op.disk_template)
6823

    
6824
    if (not self.cfg.GetVGName() and
6825
        self.op.disk_template not in constants.DTS_NOT_LVM):
6826
      raise errors.OpPrereqError("Cluster does not support lvm-based"
6827
                                 " instances", errors.ECODE_STATE)
6828

    
6829
    if self.op.hypervisor is None:
6830
      self.op.hypervisor = self.cfg.GetHypervisorType()
6831

    
6832
    cluster = self.cfg.GetClusterInfo()
6833
    enabled_hvs = cluster.enabled_hypervisors
6834
    if self.op.hypervisor not in enabled_hvs:
6835
      raise errors.OpPrereqError("Selected hypervisor (%s) not enabled in the"
6836
                                 " cluster (%s)" % (self.op.hypervisor,
6837
                                  ",".join(enabled_hvs)),
6838
                                 errors.ECODE_STATE)
6839

    
6840
    # check hypervisor parameter syntax (locally)
6841
    utils.ForceDictType(self.op.hvparams, constants.HVS_PARAMETER_TYPES)
6842
    filled_hvp = cluster.SimpleFillHV(self.op.hypervisor, self.op.os_type,
6843
                                      self.op.hvparams)
6844
    hv_type = hypervisor.GetHypervisor(self.op.hypervisor)
6845
    hv_type.CheckParameterSyntax(filled_hvp)
6846
    self.hv_full = filled_hvp
6847
    # check that we don't specify global parameters on an instance
6848
    _CheckGlobalHvParams(self.op.hvparams)
6849

    
6850
    # fill and remember the beparams dict
6851
    utils.ForceDictType(self.op.beparams, constants.BES_PARAMETER_TYPES)
6852
    self.be_full = cluster.SimpleFillBE(self.op.beparams)
6853

    
6854
    # build os parameters
6855
    self.os_full = cluster.SimpleFillOS(self.op.os_type, self.op.osparams)
6856

    
6857
    # now that hvp/bep are in final format, let's reset to defaults,
6858
    # if told to do so
6859
    if self.op.identify_defaults:
6860
      self._RevertToDefaults(cluster)
6861

    
6862
    # NIC buildup
6863
    self.nics = []
6864
    for idx, nic in enumerate(self.op.nics):
6865
      nic_mode_req = nic.get("mode", None)
6866
      nic_mode = nic_mode_req
6867
      if nic_mode is None:
6868
        nic_mode = cluster.nicparams[constants.PP_DEFAULT][constants.NIC_MODE]
6869

    
6870
      # in routed mode, for the first nic, the default ip is 'auto'
6871
      if nic_mode == constants.NIC_MODE_ROUTED and idx == 0:
6872
        default_ip_mode = constants.VALUE_AUTO
6873
      else:
6874
        default_ip_mode = constants.VALUE_NONE
6875

    
6876
      # ip validity checks
6877
      ip = nic.get("ip", default_ip_mode)
6878
      if ip is None or ip.lower() == constants.VALUE_NONE:
6879
        nic_ip = None
6880
      elif ip.lower() == constants.VALUE_AUTO:
6881
        if not self.op.name_check:
6882
          raise errors.OpPrereqError("IP address set to auto but name checks"
6883
                                     " have been skipped. Aborting.",
6884
                                     errors.ECODE_INVAL)
6885
        nic_ip = self.hostname1.ip
6886
      else:
6887
        if not utils.IsValidIP4(ip):
6888
          raise errors.OpPrereqError("Given IP address '%s' doesn't look"
6889
                                     " like a valid IP" % ip,
6890
                                     errors.ECODE_INVAL)
6891
        nic_ip = ip
6892

    
6893
      # TODO: check the ip address for uniqueness
6894
      if nic_mode == constants.NIC_MODE_ROUTED and not nic_ip:
6895
        raise errors.OpPrereqError("Routed nic mode requires an ip address",
6896
                                   errors.ECODE_INVAL)
6897

    
6898
      # MAC address verification
6899
      mac = nic.get("mac", constants.VALUE_AUTO)
6900
      if mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
6901
        mac = utils.NormalizeAndValidateMac(mac)
6902

    
6903
        try:
6904
          self.cfg.ReserveMAC(mac, self.proc.GetECId())
6905
        except errors.ReservationError:
6906
          raise errors.OpPrereqError("MAC address %s already in use"
6907
                                     " in cluster" % mac,
6908
                                     errors.ECODE_NOTUNIQUE)
6909

    
6910
      # bridge verification
6911
      bridge = nic.get("bridge", None)
6912
      link = nic.get("link", None)
6913
      if bridge and link:
6914
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
6915
                                   " at the same time", errors.ECODE_INVAL)
6916
      elif bridge and nic_mode == constants.NIC_MODE_ROUTED:
6917
        raise errors.OpPrereqError("Cannot pass 'bridge' on a routed nic",
6918
                                   errors.ECODE_INVAL)
6919
      elif bridge:
6920
        link = bridge
6921

    
6922
      nicparams = {}
6923
      if nic_mode_req:
6924
        nicparams[constants.NIC_MODE] = nic_mode_req
6925
      if link:
6926
        nicparams[constants.NIC_LINK] = link
6927

    
6928
      check_params = cluster.SimpleFillNIC(nicparams)
6929
      objects.NIC.CheckParameterSyntax(check_params)
6930
      self.nics.append(objects.NIC(mac=mac, ip=nic_ip, nicparams=nicparams))
6931

    
6932
    # disk checks/pre-build
6933
    self.disks = []
6934
    for disk in self.op.disks:
6935
      mode = disk.get("mode", constants.DISK_RDWR)
6936
      if mode not in constants.DISK_ACCESS_SET:
6937
        raise errors.OpPrereqError("Invalid disk access mode '%s'" %
6938
                                   mode, errors.ECODE_INVAL)
6939
      size = disk.get("size", None)
6940
      if size is None:
6941
        raise errors.OpPrereqError("Missing disk size", errors.ECODE_INVAL)
6942
      try:
6943
        size = int(size)
6944
      except (TypeError, ValueError):
6945
        raise errors.OpPrereqError("Invalid disk size '%s'" % size,
6946
                                   errors.ECODE_INVAL)
6947
      new_disk = {"size": size, "mode": mode}
6948
      if "adopt" in disk:
6949
        new_disk["adopt"] = disk["adopt"]
6950
      self.disks.append(new_disk)
6951

    
6952
    if self.op.mode == constants.INSTANCE_IMPORT:
6953

    
6954
      # Check that the new instance doesn't have less disks than the export
6955
      instance_disks = len(self.disks)
6956
      export_disks = export_info.getint(constants.INISECT_INS, 'disk_count')
6957
      if instance_disks < export_disks:
6958
        raise errors.OpPrereqError("Not enough disks to import."
6959
                                   " (instance: %d, export: %d)" %
6960
                                   (instance_disks, export_disks),
6961
                                   errors.ECODE_INVAL)
6962

    
6963
      disk_images = []
6964
      for idx in range(export_disks):
6965
        option = 'disk%d_dump' % idx
6966
        if export_info.has_option(constants.INISECT_INS, option):
6967
          # FIXME: are the old os-es, disk sizes, etc. useful?
6968
          export_name = export_info.get(constants.INISECT_INS, option)
6969
          image = utils.PathJoin(self.op.src_path, export_name)
6970
          disk_images.append(image)
6971
        else:
6972
          disk_images.append(False)
6973

    
6974
      self.src_images = disk_images
6975

    
6976
      old_name = export_info.get(constants.INISECT_INS, 'name')
6977
      try:
6978
        exp_nic_count = export_info.getint(constants.INISECT_INS, 'nic_count')
6979
      except (TypeError, ValueError), err:
6980
        raise errors.OpPrereqError("Invalid export file, nic_count is not"
6981
                                   " an integer: %s" % str(err),
6982
                                   errors.ECODE_STATE)
6983
      if self.op.instance_name == old_name:
6984
        for idx, nic in enumerate(self.nics):
6985
          if nic.mac == constants.VALUE_AUTO and exp_nic_count >= idx:
6986
            nic_mac_ini = 'nic%d_mac' % idx
6987
            nic.mac = export_info.get(constants.INISECT_INS, nic_mac_ini)
6988

    
6989
    # ENDIF: self.op.mode == constants.INSTANCE_IMPORT
6990

    
6991
    # ip ping checks (we use the same ip that was resolved in ExpandNames)
6992
    if self.op.ip_check:
6993
      if utils.TcpPing(self.check_ip, constants.DEFAULT_NODED_PORT):
6994
        raise errors.OpPrereqError("IP %s of instance %s already in use" %
6995
                                   (self.check_ip, self.op.instance_name),
6996
                                   errors.ECODE_NOTUNIQUE)
6997

    
6998
    #### mac address generation
6999
    # By generating here the mac address both the allocator and the hooks get
7000
    # the real final mac address rather than the 'auto' or 'generate' value.
7001
    # There is a race condition between the generation and the instance object
7002
    # creation, which means that we know the mac is valid now, but we're not
7003
    # sure it will be when we actually add the instance. If things go bad
7004
    # adding the instance will abort because of a duplicate mac, and the
7005
    # creation job will fail.
7006
    for nic in self.nics:
7007
      if nic.mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
7008
        nic.mac = self.cfg.GenerateMAC(self.proc.GetECId())
7009

    
7010
    #### allocator run
7011

    
7012
    if self.op.iallocator is not None:
7013
      self._RunAllocator()
7014

    
7015
    #### node related checks
7016

    
7017
    # check primary node
7018
    self.pnode = pnode = self.cfg.GetNodeInfo(self.op.pnode)
7019
    assert self.pnode is not None, \
7020
      "Cannot retrieve locked node %s" % self.op.pnode
7021
    if pnode.offline:
7022
      raise errors.OpPrereqError("Cannot use offline primary node '%s'" %
7023
                                 pnode.name, errors.ECODE_STATE)
7024
    if pnode.drained:
7025
      raise errors.OpPrereqError("Cannot use drained primary node '%s'" %
7026
                                 pnode.name, errors.ECODE_STATE)
7027

    
7028
    self.secondaries = []
7029

    
7030
    # mirror node verification
7031
    if self.op.disk_template in constants.DTS_NET_MIRROR:
7032
      if self.op.snode is None:
7033
        raise errors.OpPrereqError("The networked disk templates need"
7034
                                   " a mirror node", errors.ECODE_INVAL)
7035
      if self.op.snode == pnode.name:
7036
        raise errors.OpPrereqError("The secondary node cannot be the"
7037
                                   " primary node.", errors.ECODE_INVAL)
7038
      _CheckNodeOnline(self, self.op.snode)
7039
      _CheckNodeNotDrained(self, self.op.snode)
7040
      self.secondaries.append(self.op.snode)
7041

    
7042
    nodenames = [pnode.name] + self.secondaries
7043

    
7044
    req_size = _ComputeDiskSize(self.op.disk_template,
7045
                                self.disks)
7046

    
7047
    # Check lv size requirements, if not adopting
7048
    if req_size is not None and not self.adopt_disks:
7049
      _CheckNodesFreeDisk(self, nodenames, req_size)
7050

    
7051
    if self.adopt_disks: # instead, we must check the adoption data
7052
      all_lvs = set([i["adopt"] for i in self.disks])
7053
      if len(all_lvs) != len(self.disks):
7054
        raise errors.OpPrereqError("Duplicate volume names given for adoption",
7055
                                   errors.ECODE_INVAL)
7056
      for lv_name in all_lvs:
7057
        try:
7058
          self.cfg.ReserveLV(lv_name, self.proc.GetECId())
7059
        except errors.ReservationError:
7060
          raise errors.OpPrereqError("LV named %s used by another instance" %
7061
                                     lv_name, errors.ECODE_NOTUNIQUE)
7062

    
7063
      node_lvs = self.rpc.call_lv_list([pnode.name],
7064
                                       self.cfg.GetVGName())[pnode.name]
7065
      node_lvs.Raise("Cannot get LV information from node %s" % pnode.name)
7066
      node_lvs = node_lvs.payload
7067
      delta = all_lvs.difference(node_lvs.keys())
7068
      if delta:
7069
        raise errors.OpPrereqError("Missing logical volume(s): %s" %
7070
                                   utils.CommaJoin(delta),
7071
                                   errors.ECODE_INVAL)
7072
      online_lvs = [lv for lv in all_lvs if node_lvs[lv][2]]
7073
      if online_lvs:
7074
        raise errors.OpPrereqError("Online logical volumes found, cannot"
7075
                                   " adopt: %s" % utils.CommaJoin(online_lvs),
7076
                                   errors.ECODE_STATE)
7077
      # update the size of disk based on what is found
7078
      for dsk in self.disks:
7079
        dsk["size"] = int(float(node_lvs[dsk["adopt"]][0]))
7080

    
7081
    _CheckHVParams(self, nodenames, self.op.hypervisor, self.op.hvparams)
7082

    
7083
    _CheckNodeHasOS(self, pnode.name, self.op.os_type, self.op.force_variant)
7084
    # check OS parameters (remotely)
7085
    _CheckOSParams(self, True, nodenames, self.op.os_type, self.os_full)
7086

    
7087
    _CheckNicsBridgesExist(self, self.nics, self.pnode.name)
7088

    
7089
    # memory check on primary node
7090
    if self.op.start:
7091
      _CheckNodeFreeMemory(self, self.pnode.name,
7092
                           "creating instance %s" % self.op.instance_name,
7093
                           self.be_full[constants.BE_MEMORY],
7094
                           self.op.hypervisor)
7095

    
7096
    self.dry_run_result = list(nodenames)
7097

    
7098
  def Exec(self, feedback_fn):
7099
    """Create and add the instance to the cluster.
7100

7101
    """
7102
    instance = self.op.instance_name
7103
    pnode_name = self.pnode.name
7104

    
7105
    ht_kind = self.op.hypervisor
7106
    if ht_kind in constants.HTS_REQ_PORT:
7107
      network_port = self.cfg.AllocatePort()
7108
    else:
7109
      network_port = None
7110

    
7111
    if constants.ENABLE_FILE_STORAGE:
7112
      # this is needed because os.path.join does not accept None arguments
7113
      if self.op.file_storage_dir is None:
7114
        string_file_storage_dir = ""
7115
      else:
7116
        string_file_storage_dir = self.op.file_storage_dir
7117

    
7118
      # build the full file storage dir path
7119
      file_storage_dir = utils.PathJoin(self.cfg.GetFileStorageDir(),
7120
                                        string_file_storage_dir, instance)
7121
    else:
7122
      file_storage_dir = ""
7123

    
7124
    disks = _GenerateDiskTemplate(self,
7125
                                  self.op.disk_template,
7126
                                  instance, pnode_name,
7127
                                  self.secondaries,
7128
                                  self.disks,
7129
                                  file_storage_dir,
7130
                                  self.op.file_driver,
7131
                                  0)
7132

    
7133
    iobj = objects.Instance(name=instance, os=self.op.os_type,
7134
                            primary_node=pnode_name,
7135
                            nics=self.nics, disks=disks,
7136
                            disk_template=self.op.disk_template,
7137
                            admin_up=False,
7138
                            network_port=network_port,
7139
                            beparams=self.op.beparams,
7140
                            hvparams=self.op.hvparams,
7141
                            hypervisor=self.op.hypervisor,
7142
                            osparams=self.op.osparams,
7143
                            )
7144

    
7145
    if self.adopt_disks:
7146
      # rename LVs to the newly-generated names; we need to construct
7147
      # 'fake' LV disks with the old data, plus the new unique_id
7148
      tmp_disks = [objects.Disk.FromDict(v.ToDict()) for v in disks]
7149
      rename_to = []
7150
      for t_dsk, a_dsk in zip (tmp_disks, self.disks):
7151
        rename_to.append(t_dsk.logical_id)
7152
        t_dsk.logical_id = (t_dsk.logical_id[0], a_dsk["adopt"])
7153
        self.cfg.SetDiskID(t_dsk, pnode_name)
7154
      result = self.rpc.call_blockdev_rename(pnode_name,
7155
                                             zip(tmp_disks, rename_to))
7156
      result.Raise("Failed to rename adoped LVs")
7157
    else:
7158
      feedback_fn("* creating instance disks...")
7159
      try:
7160
        _CreateDisks(self, iobj)
7161
      except errors.OpExecError:
7162
        self.LogWarning("Device creation failed, reverting...")
7163
        try:
7164
          _RemoveDisks(self, iobj)
7165
        finally:
7166
          self.cfg.ReleaseDRBDMinors(instance)
7167
          raise
7168

    
7169
    feedback_fn("adding instance %s to cluster config" % instance)
7170

    
7171
    self.cfg.AddInstance(iobj, self.proc.GetECId())
7172

    
7173
    # Declare that we don't want to remove the instance lock anymore, as we've
7174
    # added the instance to the config
7175
    del self.remove_locks[locking.LEVEL_INSTANCE]
7176
    # Unlock all the nodes
7177
    if self.op.mode == constants.INSTANCE_IMPORT:
7178
      nodes_keep = [self.op.src_node]
7179
      nodes_release = [node for node in self.acquired_locks[locking.LEVEL_NODE]
7180
                       if node != self.op.src_node]
7181
      self.context.glm.release(locking.LEVEL_NODE, nodes_release)
7182
      self.acquired_locks[locking.LEVEL_NODE] = nodes_keep
7183
    else:
7184
      self.context.glm.release(locking.LEVEL_NODE)
7185
      del self.acquired_locks[locking.LEVEL_NODE]
7186

    
7187
    if self.op.wait_for_sync:
7188
      disk_abort = not _WaitForSync(self, iobj)
7189
    elif iobj.disk_template in constants.DTS_NET_MIRROR:
7190
      # make sure the disks are not degraded (still sync-ing is ok)
7191
      time.sleep(15)
7192
      feedback_fn("* checking mirrors status")
7193
      disk_abort = not _WaitForSync(self, iobj, oneshot=True)
7194
    else:
7195
      disk_abort = False
7196

    
7197
    if disk_abort:
7198
      _RemoveDisks(self, iobj)
7199
      self.cfg.RemoveInstance(iobj.name)
7200
      # Make sure the instance lock gets removed
7201
      self.remove_locks[locking.LEVEL_INSTANCE] = iobj.name
7202
      raise errors.OpExecError("There are some degraded disks for"
7203
                               " this instance")
7204

    
7205
    if iobj.disk_template != constants.DT_DISKLESS and not self.adopt_disks:
7206
      if self.op.mode == constants.INSTANCE_CREATE:
7207
        if not self.op.no_install:
7208
          feedback_fn("* running the instance OS create scripts...")
7209
          # FIXME: pass debug option from opcode to backend
7210
          result = self.rpc.call_instance_os_add(pnode_name, iobj, False,
7211
                                                 self.op.debug_level)
7212
          result.Raise("Could not add os for instance %s"
7213
                       " on node %s" % (instance, pnode_name))
7214

    
7215
      elif self.op.mode == constants.INSTANCE_IMPORT:
7216
        feedback_fn("* running the instance OS import scripts...")
7217

    
7218
        transfers = []
7219

    
7220
        for idx, image in enumerate(self.src_images):
7221
          if not image:
7222
            continue
7223

    
7224
          # FIXME: pass debug option from opcode to backend
7225
          dt = masterd.instance.DiskTransfer("disk/%s" % idx,
7226
                                             constants.IEIO_FILE, (image, ),
7227
                                             constants.IEIO_SCRIPT,
7228
                                             (iobj.disks[idx], idx),
7229
                                             None)
7230
          transfers.append(dt)
7231

    
7232
        import_result = \
7233
          masterd.instance.TransferInstanceData(self, feedback_fn,
7234
                                                self.op.src_node, pnode_name,
7235
                                                self.pnode.secondary_ip,
7236
                                                iobj, transfers)
7237
        if not compat.all(import_result):
7238
          self.LogWarning("Some disks for instance %s on node %s were not"
7239
                          " imported successfully" % (instance, pnode_name))
7240

    
7241
      elif self.op.mode == constants.INSTANCE_REMOTE_IMPORT:
7242
        feedback_fn("* preparing remote import...")
7243
        connect_timeout = constants.RIE_CONNECT_TIMEOUT
7244
        timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
7245

    
7246
        disk_results = masterd.instance.RemoteImport(self, feedback_fn, iobj,
7247
                                                     self.source_x509_ca,
7248
                                                     self._cds, timeouts)
7249
        if not compat.all(disk_results):
7250
          # TODO: Should the instance still be started, even if some disks
7251
          # failed to import (valid for local imports, too)?
7252
          self.LogWarning("Some disks for instance %s on node %s were not"
7253
                          " imported successfully" % (instance, pnode_name))
7254

    
7255
        # Run rename script on newly imported instance
7256
        assert iobj.name == instance
7257
        feedback_fn("Running rename script for %s" % instance)
7258
        result = self.rpc.call_instance_run_rename(pnode_name, iobj,
7259
                                                   self.source_instance_name,
7260
                                                   self.op.debug_level)
7261
        if result.fail_msg:
7262
          self.LogWarning("Failed to run rename script for %s on node"
7263
                          " %s: %s" % (instance, pnode_name, result.fail_msg))
7264

    
7265
      else:
7266
        # also checked in the prereq part
7267
        raise errors.ProgrammerError("Unknown OS initialization mode '%s'"
7268
                                     % self.op.mode)
7269

    
7270
    if self.op.start:
7271
      iobj.admin_up = True
7272
      self.cfg.Update(iobj, feedback_fn)
7273
      logging.info("Starting instance %s on node %s", instance, pnode_name)
7274
      feedback_fn("* starting instance...")
7275
      result = self.rpc.call_instance_start(pnode_name, iobj, None, None)
7276
      result.Raise("Could not start instance")
7277

    
7278
    return list(iobj.all_nodes)
7279

    
7280

    
7281
class LUConnectConsole(NoHooksLU):
7282
  """Connect to an instance's console.
7283

7284
  This is somewhat special in that it returns the command line that
7285
  you need to run on the master node in order to connect to the
7286
  console.
7287

7288
  """
7289
  _OP_REQP = [("instance_name", _TNonEmptyString)]
7290
  REQ_BGL = False
7291

    
7292
  def ExpandNames(self):
7293
    self._ExpandAndLockInstance()
7294

    
7295
  def CheckPrereq(self):
7296
    """Check prerequisites.
7297

7298
    This checks that the instance is in the cluster.
7299

7300
    """
7301
    self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
7302
    assert self.instance is not None, \
7303
      "Cannot retrieve locked instance %s" % self.op.instance_name
7304
    _CheckNodeOnline(self, self.instance.primary_node)
7305

    
7306
  def Exec(self, feedback_fn):
7307
    """Connect to the console of an instance
7308

7309
    """
7310
    instance = self.instance
7311
    node = instance.primary_node
7312

    
7313
    node_insts = self.rpc.call_instance_list([node],
7314
                                             [instance.hypervisor])[node]
7315
    node_insts.Raise("Can't get node information from %s" % node)
7316

    
7317
    if instance.name not in node_insts.payload:
7318
      raise errors.OpExecError("Instance %s is not running." % instance.name)
7319

    
7320
    logging.debug("Connecting to console of %s on %s", instance.name, node)
7321

    
7322
    hyper = hypervisor.GetHypervisor(instance.hypervisor)
7323
    cluster = self.cfg.GetClusterInfo()
7324
    # beparams and hvparams are passed separately, to avoid editing the
7325
    # instance and then saving the defaults in the instance itself.
7326
    hvparams = cluster.FillHV(instance)
7327
    beparams = cluster.FillBE(instance)
7328
    console_cmd = hyper.GetShellCommandForConsole(instance, hvparams, beparams)
7329

    
7330
    # build ssh cmdline
7331
    return self.ssh.BuildCmd(node, "root", console_cmd, batch=True, tty=True)
7332

    
7333

    
7334
class LUReplaceDisks(LogicalUnit):
7335
  """Replace the disks of an instance.
7336

7337
  """
7338
  HPATH = "mirrors-replace"
7339
  HTYPE = constants.HTYPE_INSTANCE
7340
  _OP_REQP = [
7341
    ("instance_name", _TNonEmptyString),
7342
    ("mode", _TElemOf(constants.REPLACE_MODES)),
7343
    ("disks", _TListOf(_TPositiveInt)),
7344
    ]
7345
  _OP_DEFS = [
7346
    ("remote_node", None),
7347
    ("iallocator", None),
7348
    ("early_release", None),
7349
    ]
7350
  REQ_BGL = False
7351

    
7352
  def CheckArguments(self):
7353
    TLReplaceDisks.CheckArguments(self.op.mode, self.op.remote_node,
7354
                                  self.op.iallocator)
7355

    
7356
  def ExpandNames(self):
7357
    self._ExpandAndLockInstance()
7358

    
7359
    if self.op.iallocator is not None:
7360
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
7361

    
7362
    elif self.op.remote_node is not None:
7363
      remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
7364
      self.op.remote_node = remote_node
7365

    
7366
      # Warning: do not remove the locking of the new secondary here
7367
      # unless DRBD8.AddChildren is changed to work in parallel;
7368
      # currently it doesn't since parallel invocations of
7369
      # FindUnusedMinor will conflict
7370
      self.needed_locks[locking.LEVEL_NODE] = [remote_node]
7371
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_APPEND
7372

    
7373
    else:
7374
      self.needed_locks[locking.LEVEL_NODE] = []
7375
      self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
7376

    
7377
    self.replacer = TLReplaceDisks(self, self.op.instance_name, self.op.mode,
7378
                                   self.op.iallocator, self.op.remote_node,
7379
                                   self.op.disks, False, self.op.early_release)
7380

    
7381
    self.tasklets = [self.replacer]
7382

    
7383
  def DeclareLocks(self, level):
7384
    # If we're not already locking all nodes in the set we have to declare the
7385
    # instance's primary/secondary nodes.
7386
    if (level == locking.LEVEL_NODE and
7387
        self.needed_locks[locking.LEVEL_NODE] is not locking.ALL_SET):
7388
      self._LockInstancesNodes()
7389

    
7390
  def BuildHooksEnv(self):
7391
    """Build hooks env.
7392

7393
    This runs on the master, the primary and all the secondaries.
7394

7395
    """
7396
    instance = self.replacer.instance
7397
    env = {
7398
      "MODE": self.op.mode,
7399
      "NEW_SECONDARY": self.op.remote_node,
7400
      "OLD_SECONDARY": instance.secondary_nodes[0],
7401
      }
7402
    env.update(_BuildInstanceHookEnvByObject(self, instance))
7403
    nl = [
7404
      self.cfg.GetMasterNode(),
7405
      instance.primary_node,
7406
      ]
7407
    if self.op.remote_node is not None:
7408
      nl.append(self.op.remote_node)
7409
    return env, nl, nl
7410

    
7411

    
7412
class TLReplaceDisks(Tasklet):
7413
  """Replaces disks for an instance.
7414

7415
  Note: Locking is not within the scope of this class.
7416

7417
  """
7418
  def __init__(self, lu, instance_name, mode, iallocator_name, remote_node,
7419
               disks, delay_iallocator, early_release):
7420
    """Initializes this class.
7421

7422
    """
7423
    Tasklet.__init__(self, lu)
7424

    
7425
    # Parameters
7426
    self.instance_name = instance_name
7427
    self.mode = mode
7428
    self.iallocator_name = iallocator_name
7429
    self.remote_node = remote_node
7430
    self.disks = disks
7431
    self.delay_iallocator = delay_iallocator
7432
    self.early_release = early_release
7433

    
7434
    # Runtime data
7435
    self.instance = None
7436
    self.new_node = None
7437
    self.target_node = None
7438
    self.other_node = None
7439
    self.remote_node_info = None
7440
    self.node_secondary_ip = None
7441

    
7442
  @staticmethod
7443
  def CheckArguments(mode, remote_node, iallocator):
7444
    """Helper function for users of this class.
7445

7446
    """
7447
    # check for valid parameter combination
7448
    if mode == constants.REPLACE_DISK_CHG:
7449
      if remote_node is None and iallocator is None:
7450
        raise errors.OpPrereqError("When changing the secondary either an"
7451
                                   " iallocator script must be used or the"
7452
                                   " new node given", errors.ECODE_INVAL)
7453

    
7454
      if remote_node is not None and iallocator is not None:
7455
        raise errors.OpPrereqError("Give either the iallocator or the new"
7456
                                   " secondary, not both", errors.ECODE_INVAL)
7457

    
7458
    elif remote_node is not None or iallocator is not None:
7459
      # Not replacing the secondary
7460
      raise errors.OpPrereqError("The iallocator and new node options can"
7461
                                 " only be used when changing the"
7462
                                 " secondary node", errors.ECODE_INVAL)
7463

    
7464
  @staticmethod
7465
  def _RunAllocator(lu, iallocator_name, instance_name, relocate_from):
7466
    """Compute a new secondary node using an IAllocator.
7467

7468
    """
7469
    ial = IAllocator(lu.cfg, lu.rpc,
7470
                     mode=constants.IALLOCATOR_MODE_RELOC,
7471
                     name=instance_name,
7472
                     relocate_from=relocate_from)
7473

    
7474
    ial.Run(iallocator_name)
7475

    
7476
    if not ial.success:
7477
      raise errors.OpPrereqError("Can't compute nodes using iallocator '%s':"
7478
                                 " %s" % (iallocator_name, ial.info),
7479
                                 errors.ECODE_NORES)
7480

    
7481
    if len(ial.result) != ial.required_nodes:
7482
      raise errors.OpPrereqError("iallocator '%s' returned invalid number"
7483
                                 " of nodes (%s), required %s" %
7484
                                 (iallocator_name,
7485
                                  len(ial.result), ial.required_nodes),
7486
                                 errors.ECODE_FAULT)
7487

    
7488
    remote_node_name = ial.result[0]
7489

    
7490
    lu.LogInfo("Selected new secondary for instance '%s': %s",
7491
               instance_name, remote_node_name)
7492

    
7493
    return remote_node_name
7494

    
7495
  def _FindFaultyDisks(self, node_name):
7496
    return _FindFaultyInstanceDisks(self.cfg, self.rpc, self.instance,
7497
                                    node_name, True)
7498

    
7499
  def CheckPrereq(self):
7500
    """Check prerequisites.
7501

7502
    This checks that the instance is in the cluster.
7503

7504
    """
7505
    self.instance = instance = self.cfg.GetInstanceInfo(self.instance_name)
7506
    assert instance is not None, \
7507
      "Cannot retrieve locked instance %s" % self.instance_name
7508

    
7509
    if instance.disk_template != constants.DT_DRBD8:
7510
      raise errors.OpPrereqError("Can only run replace disks for DRBD8-based"
7511
                                 " instances", errors.ECODE_INVAL)
7512

    
7513
    if len(instance.secondary_nodes) != 1:
7514
      raise errors.OpPrereqError("The instance has a strange layout,"
7515
                                 " expected one secondary but found %d" %
7516
                                 len(instance.secondary_nodes),
7517
                                 errors.ECODE_FAULT)
7518

    
7519
    if not self.delay_iallocator:
7520
      self._CheckPrereq2()
7521

    
7522
  def _CheckPrereq2(self):
7523
    """Check prerequisites, second part.
7524

7525
    This function should always be part of CheckPrereq. It was separated and is
7526
    now called from Exec because during node evacuation iallocator was only
7527
    called with an unmodified cluster model, not taking planned changes into
7528
    account.
7529

7530
    """
7531
    instance = self.instance
7532
    secondary_node = instance.secondary_nodes[0]
7533

    
7534
    if self.iallocator_name is None:
7535
      remote_node = self.remote_node
7536
    else:
7537
      remote_node = self._RunAllocator(self.lu, self.iallocator_name,
7538
                                       instance.name, instance.secondary_nodes)
7539

    
7540
    if remote_node is not None:
7541
      self.remote_node_info = self.cfg.GetNodeInfo(remote_node)
7542
      assert self.remote_node_info is not None, \
7543
        "Cannot retrieve locked node %s" % remote_node
7544
    else:
7545
      self.remote_node_info = None
7546

    
7547
    if remote_node == self.instance.primary_node:
7548
      raise errors.OpPrereqError("The specified node is the primary node of"
7549
                                 " the instance.", errors.ECODE_INVAL)
7550

    
7551
    if remote_node == secondary_node:
7552
      raise errors.OpPrereqError("The specified node is already the"
7553
                                 " secondary node of the instance.",
7554
                                 errors.ECODE_INVAL)
7555

    
7556
    if self.disks and self.mode in (constants.REPLACE_DISK_AUTO,
7557
                                    constants.REPLACE_DISK_CHG):
7558
      raise errors.OpPrereqError("Cannot specify disks to be replaced",
7559
                                 errors.ECODE_INVAL)
7560

    
7561
    if self.mode == constants.REPLACE_DISK_AUTO:
7562
      faulty_primary = self._FindFaultyDisks(instance.primary_node)
7563
      faulty_secondary = self._FindFaultyDisks(secondary_node)
7564

    
7565
      if faulty_primary and faulty_secondary:
7566
        raise errors.OpPrereqError("Instance %s has faulty disks on more than"
7567
                                   " one node and can not be repaired"
7568
                                   " automatically" % self.instance_name,
7569
                                   errors.ECODE_STATE)
7570

    
7571
      if faulty_primary:
7572
        self.disks = faulty_primary
7573
        self.target_node = instance.primary_node
7574
        self.other_node = secondary_node
7575
        check_nodes = [self.target_node, self.other_node]
7576
      elif faulty_secondary:
7577
        self.disks = faulty_secondary
7578
        self.target_node = secondary_node
7579
        self.other_node = instance.primary_node
7580
        check_nodes = [self.target_node, self.other_node]
7581
      else:
7582
        self.disks = []
7583
        check_nodes = []
7584

    
7585
    else:
7586
      # Non-automatic modes
7587
      if self.mode == constants.REPLACE_DISK_PRI:
7588
        self.target_node = instance.primary_node
7589
        self.other_node = secondary_node
7590
        check_nodes = [self.target_node, self.other_node]
7591

    
7592
      elif self.mode == constants.REPLACE_DISK_SEC:
7593
        self.target_node = secondary_node
7594
        self.other_node = instance.primary_node
7595
        check_nodes = [self.target_node, self.other_node]
7596

    
7597
      elif self.mode == constants.REPLACE_DISK_CHG:
7598
        self.new_node = remote_node
7599
        self.other_node = instance.primary_node
7600
        self.target_node = secondary_node
7601
        check_nodes = [self.new_node, self.other_node]
7602

    
7603
        _CheckNodeNotDrained(self.lu, remote_node)
7604

    
7605
        old_node_info = self.cfg.GetNodeInfo(secondary_node)
7606
        assert old_node_info is not None
7607
        if old_node_info.offline and not self.early_release:
7608
          # doesn't make sense to delay the release
7609
          self.early_release = True
7610
          self.lu.LogInfo("Old secondary %s is offline, automatically enabling"
7611
                          " early-release mode", secondary_node)
7612

    
7613
      else:
7614
        raise errors.ProgrammerError("Unhandled disk replace mode (%s)" %
7615
                                     self.mode)
7616

    
7617
      # If not specified all disks should be replaced
7618
      if not self.disks:
7619
        self.disks = range(len(self.instance.disks))
7620

    
7621
    for node in check_nodes:
7622
      _CheckNodeOnline(self.lu, node)
7623

    
7624
    # Check whether disks are valid
7625
    for disk_idx in self.disks:
7626
      instance.FindDisk(disk_idx)
7627

    
7628
    # Get secondary node IP addresses
7629
    node_2nd_ip = {}
7630

    
7631
    for node_name in [self.target_node, self.other_node, self.new_node]:
7632
      if node_name is not None:
7633
        node_2nd_ip[node_name] = self.cfg.GetNodeInfo(node_name).secondary_ip
7634

    
7635
    self.node_secondary_ip = node_2nd_ip
7636

    
7637
  def Exec(self, feedback_fn):
7638
    """Execute disk replacement.
7639

7640
    This dispatches the disk replacement to the appropriate handler.
7641

7642
    """
7643
    if self.delay_iallocator:
7644
      self._CheckPrereq2()
7645

    
7646
    if not self.disks:
7647
      feedback_fn("No disks need replacement")
7648
      return
7649

    
7650
    feedback_fn("Replacing disk(s) %s for %s" %
7651
                (utils.CommaJoin(self.disks), self.instance.name))
7652

    
7653
    activate_disks = (not self.instance.admin_up)
7654

    
7655
    # Activate the instance disks if we're replacing them on a down instance
7656
    if activate_disks:
7657
      _StartInstanceDisks(self.lu, self.instance, True)
7658

    
7659
    try:
7660
      # Should we replace the secondary node?
7661
      if self.new_node is not None:
7662
        fn = self._ExecDrbd8Secondary
7663
      else:
7664
        fn = self._ExecDrbd8DiskOnly
7665

    
7666
      return fn(feedback_fn)
7667

    
7668
    finally:
7669
      # Deactivate the instance disks if we're replacing them on a
7670
      # down instance
7671
      if activate_disks:
7672
        _SafeShutdownInstanceDisks(self.lu, self.instance)
7673

    
7674
  def _CheckVolumeGroup(self, nodes):
7675
    self.lu.LogInfo("Checking volume groups")
7676

    
7677
    vgname = self.cfg.GetVGName()
7678

    
7679
    # Make sure volume group exists on all involved nodes
7680
    results = self.rpc.call_vg_list(nodes)
7681
    if not results:
7682
      raise errors.OpExecError("Can't list volume groups on the nodes")
7683

    
7684
    for node in nodes:
7685
      res = results[node]
7686
      res.Raise("Error checking node %s" % node)
7687
      if vgname not in res.payload:
7688
        raise errors.OpExecError("Volume group '%s' not found on node %s" %
7689
                                 (vgname, node))
7690

    
7691
  def _CheckDisksExistence(self, nodes):
7692
    # Check disk existence
7693
    for idx, dev in enumerate(self.instance.disks):
7694
      if idx not in self.disks:
7695
        continue
7696

    
7697
      for node in nodes:
7698
        self.lu.LogInfo("Checking disk/%d on %s" % (idx, node))
7699
        self.cfg.SetDiskID(dev, node)
7700

    
7701
        result = self.rpc.call_blockdev_find(node, dev)
7702

    
7703
        msg = result.fail_msg
7704
        if msg or not result.payload:
7705
          if not msg:
7706
            msg = "disk not found"
7707
          raise errors.OpExecError("Can't find disk/%d on node %s: %s" %
7708
                                   (idx, node, msg))
7709

    
7710
  def _CheckDisksConsistency(self, node_name, on_primary, ldisk):
7711
    for idx, dev in enumerate(self.instance.disks):
7712
      if idx not in self.disks:
7713
        continue
7714

    
7715
      self.lu.LogInfo("Checking disk/%d consistency on node %s" %
7716
                      (idx, node_name))
7717

    
7718
      if not _CheckDiskConsistency(self.lu, dev, node_name, on_primary,
7719
                                   ldisk=ldisk):
7720
        raise errors.OpExecError("Node %s has degraded storage, unsafe to"
7721
                                 " replace disks for instance %s" %
7722
                                 (node_name, self.instance.name))
7723

    
7724
  def _CreateNewStorage(self, node_name):
7725
    vgname = self.cfg.GetVGName()
7726
    iv_names = {}
7727

    
7728
    for idx, dev in enumerate(self.instance.disks):
7729
      if idx not in self.disks:
7730
        continue
7731

    
7732
      self.lu.LogInfo("Adding storage on %s for disk/%d" % (node_name, idx))
7733

    
7734
      self.cfg.SetDiskID(dev, node_name)
7735

    
7736
      lv_names = [".disk%d_%s" % (idx, suffix) for suffix in ["data", "meta"]]
7737
      names = _GenerateUniqueNames(self.lu, lv_names)
7738

    
7739
      lv_data = objects.Disk(dev_type=constants.LD_LV, size=dev.size,
7740
                             logical_id=(vgname, names[0]))
7741
      lv_meta = objects.Disk(dev_type=constants.LD_LV, size=128,
7742
                             logical_id=(vgname, names[1]))
7743

    
7744
      new_lvs = [lv_data, lv_meta]
7745
      old_lvs = dev.children
7746
      iv_names[dev.iv_name] = (dev, old_lvs, new_lvs)
7747

    
7748
      # we pass force_create=True to force the LVM creation
7749
      for new_lv in new_lvs:
7750
        _CreateBlockDev(self.lu, node_name, self.instance, new_lv, True,
7751
                        _GetInstanceInfoText(self.instance), False)
7752

    
7753
    return iv_names
7754

    
7755
  def _CheckDevices(self, node_name, iv_names):
7756
    for name, (dev, _, _) in iv_names.iteritems():
7757
      self.cfg.SetDiskID(dev, node_name)
7758

    
7759
      result = self.rpc.call_blockdev_find(node_name, dev)
7760

    
7761
      msg = result.fail_msg
7762
      if msg or not result.payload:
7763
        if not msg:
7764
          msg = "disk not found"
7765
        raise errors.OpExecError("Can't find DRBD device %s: %s" %
7766
                                 (name, msg))
7767

    
7768
      if result.payload.is_degraded:
7769
        raise errors.OpExecError("DRBD device %s is degraded!" % name)
7770

    
7771
  def _RemoveOldStorage(self, node_name, iv_names):
7772
    for name, (_, old_lvs, _) in iv_names.iteritems():
7773
      self.lu.LogInfo("Remove logical volumes for %s" % name)
7774

    
7775
      for lv in old_lvs:
7776
        self.cfg.SetDiskID(lv, node_name)
7777

    
7778
        msg = self.rpc.call_blockdev_remove(node_name, lv).fail_msg
7779
        if msg:
7780
          self.lu.LogWarning("Can't remove old LV: %s" % msg,
7781
                             hint="remove unused LVs manually")
7782

    
7783
  def _ReleaseNodeLock(self, node_name):
7784
    """Releases the lock for a given node."""
7785
    self.lu.context.glm.release(locking.LEVEL_NODE, node_name)
7786

    
7787
  def _ExecDrbd8DiskOnly(self, feedback_fn):
7788
    """Replace a disk on the primary or secondary for DRBD 8.
7789

7790
    The algorithm for replace is quite complicated:
7791

7792
      1. for each disk to be replaced:
7793

7794
        1. create new LVs on the target node with unique names
7795
        1. detach old LVs from the drbd device
7796
        1. rename old LVs to name_replaced.<time_t>
7797
        1. rename new LVs to old LVs
7798
        1. attach the new LVs (with the old names now) to the drbd device
7799

7800
      1. wait for sync across all devices
7801

7802
      1. for each modified disk:
7803

7804
        1. remove old LVs (which have the name name_replaces.<time_t>)
7805

7806
    Failures are not very well handled.
7807

7808
    """
7809
    steps_total = 6
7810

    
7811
    # Step: check device activation
7812
    self.lu.LogStep(1, steps_total, "Check device existence")
7813
    self._CheckDisksExistence([self.other_node, self.target_node])
7814
    self._CheckVolumeGroup([self.target_node, self.other_node])
7815

    
7816
    # Step: check other node consistency
7817
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7818
    self._CheckDisksConsistency(self.other_node,
7819
                                self.other_node == self.instance.primary_node,
7820
                                False)
7821

    
7822
    # Step: create new storage
7823
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7824
    iv_names = self._CreateNewStorage(self.target_node)
7825

    
7826
    # Step: for each lv, detach+rename*2+attach
7827
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7828
    for dev, old_lvs, new_lvs in iv_names.itervalues():
7829
      self.lu.LogInfo("Detaching %s drbd from local storage" % dev.iv_name)
7830

    
7831
      result = self.rpc.call_blockdev_removechildren(self.target_node, dev,
7832
                                                     old_lvs)
7833
      result.Raise("Can't detach drbd from local storage on node"
7834
                   " %s for device %s" % (self.target_node, dev.iv_name))
7835
      #dev.children = []
7836
      #cfg.Update(instance)
7837

    
7838
      # ok, we created the new LVs, so now we know we have the needed
7839
      # storage; as such, we proceed on the target node to rename
7840
      # old_lv to _old, and new_lv to old_lv; note that we rename LVs
7841
      # using the assumption that logical_id == physical_id (which in
7842
      # turn is the unique_id on that node)
7843

    
7844
      # FIXME(iustin): use a better name for the replaced LVs
7845
      temp_suffix = int(time.time())
7846
      ren_fn = lambda d, suff: (d.physical_id[0],
7847
                                d.physical_id[1] + "_replaced-%s" % suff)
7848

    
7849
      # Build the rename list based on what LVs exist on the node
7850
      rename_old_to_new = []
7851
      for to_ren in old_lvs:
7852
        result = self.rpc.call_blockdev_find(self.target_node, to_ren)
7853
        if not result.fail_msg and result.payload:
7854
          # device exists
7855
          rename_old_to_new.append((to_ren, ren_fn(to_ren, temp_suffix)))
7856

    
7857
      self.lu.LogInfo("Renaming the old LVs on the target node")
7858
      result = self.rpc.call_blockdev_rename(self.target_node,
7859
                                             rename_old_to_new)
7860
      result.Raise("Can't rename old LVs on node %s" % self.target_node)
7861

    
7862
      # Now we rename the new LVs to the old LVs
7863
      self.lu.LogInfo("Renaming the new LVs on the target node")
7864
      rename_new_to_old = [(new, old.physical_id)
7865
                           for old, new in zip(old_lvs, new_lvs)]
7866
      result = self.rpc.call_blockdev_rename(self.target_node,
7867
                                             rename_new_to_old)
7868
      result.Raise("Can't rename new LVs on node %s" % self.target_node)
7869

    
7870
      for old, new in zip(old_lvs, new_lvs):
7871
        new.logical_id = old.logical_id
7872
        self.cfg.SetDiskID(new, self.target_node)
7873

    
7874
      for disk in old_lvs:
7875
        disk.logical_id = ren_fn(disk, temp_suffix)
7876
        self.cfg.SetDiskID(disk, self.target_node)
7877

    
7878
      # Now that the new lvs have the old name, we can add them to the device
7879
      self.lu.LogInfo("Adding new mirror component on %s" % self.target_node)
7880
      result = self.rpc.call_blockdev_addchildren(self.target_node, dev,
7881
                                                  new_lvs)
7882
      msg = result.fail_msg
7883
      if msg:
7884
        for new_lv in new_lvs:
7885
          msg2 = self.rpc.call_blockdev_remove(self.target_node,
7886
                                               new_lv).fail_msg
7887
          if msg2:
7888
            self.lu.LogWarning("Can't rollback device %s: %s", dev, msg2,
7889
                               hint=("cleanup manually the unused logical"
7890
                                     "volumes"))
7891
        raise errors.OpExecError("Can't add local storage to drbd: %s" % msg)
7892

    
7893
      dev.children = new_lvs
7894

    
7895
      self.cfg.Update(self.instance, feedback_fn)
7896

    
7897
    cstep = 5
7898
    if self.early_release:
7899
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7900
      cstep += 1
7901
      self._RemoveOldStorage(self.target_node, iv_names)
7902
      # WARNING: we release both node locks here, do not do other RPCs
7903
      # than WaitForSync to the primary node
7904
      self._ReleaseNodeLock([self.target_node, self.other_node])
7905

    
7906
    # Wait for sync
7907
    # This can fail as the old devices are degraded and _WaitForSync
7908
    # does a combined result over all disks, so we don't check its return value
7909
    self.lu.LogStep(cstep, steps_total, "Sync devices")
7910
    cstep += 1
7911
    _WaitForSync(self.lu, self.instance)
7912

    
7913
    # Check all devices manually
7914
    self._CheckDevices(self.instance.primary_node, iv_names)
7915

    
7916
    # Step: remove old storage
7917
    if not self.early_release:
7918
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
7919
      cstep += 1
7920
      self._RemoveOldStorage(self.target_node, iv_names)
7921

    
7922
  def _ExecDrbd8Secondary(self, feedback_fn):
7923
    """Replace the secondary node for DRBD 8.
7924

7925
    The algorithm for replace is quite complicated:
7926
      - for all disks of the instance:
7927
        - create new LVs on the new node with same names
7928
        - shutdown the drbd device on the old secondary
7929
        - disconnect the drbd network on the primary
7930
        - create the drbd device on the new secondary
7931
        - network attach the drbd on the primary, using an artifice:
7932
          the drbd code for Attach() will connect to the network if it
7933
          finds a device which is connected to the good local disks but
7934
          not network enabled
7935
      - wait for sync across all devices
7936
      - remove all disks from the old secondary
7937

7938
    Failures are not very well handled.
7939

7940
    """
7941
    steps_total = 6
7942

    
7943
    # Step: check device activation
7944
    self.lu.LogStep(1, steps_total, "Check device existence")
7945
    self._CheckDisksExistence([self.instance.primary_node])
7946
    self._CheckVolumeGroup([self.instance.primary_node])
7947

    
7948
    # Step: check other node consistency
7949
    self.lu.LogStep(2, steps_total, "Check peer consistency")
7950
    self._CheckDisksConsistency(self.instance.primary_node, True, True)
7951

    
7952
    # Step: create new storage
7953
    self.lu.LogStep(3, steps_total, "Allocate new storage")
7954
    for idx, dev in enumerate(self.instance.disks):
7955
      self.lu.LogInfo("Adding new local storage on %s for disk/%d" %
7956
                      (self.new_node, idx))
7957
      # we pass force_create=True to force LVM creation
7958
      for new_lv in dev.children:
7959
        _CreateBlockDev(self.lu, self.new_node, self.instance, new_lv, True,
7960
                        _GetInstanceInfoText(self.instance), False)
7961

    
7962
    # Step 4: dbrd minors and drbd setups changes
7963
    # after this, we must manually remove the drbd minors on both the
7964
    # error and the success paths
7965
    self.lu.LogStep(4, steps_total, "Changing drbd configuration")
7966
    minors = self.cfg.AllocateDRBDMinor([self.new_node
7967
                                         for dev in self.instance.disks],
7968
                                        self.instance.name)
7969
    logging.debug("Allocated minors %r", minors)
7970

    
7971
    iv_names = {}
7972
    for idx, (dev, new_minor) in enumerate(zip(self.instance.disks, minors)):
7973
      self.lu.LogInfo("activating a new drbd on %s for disk/%d" %
7974
                      (self.new_node, idx))
7975
      # create new devices on new_node; note that we create two IDs:
7976
      # one without port, so the drbd will be activated without
7977
      # networking information on the new node at this stage, and one
7978
      # with network, for the latter activation in step 4
7979
      (o_node1, o_node2, o_port, o_minor1, o_minor2, o_secret) = dev.logical_id
7980
      if self.instance.primary_node == o_node1:
7981
        p_minor = o_minor1
7982
      else:
7983
        assert self.instance.primary_node == o_node2, "Three-node instance?"
7984
        p_minor = o_minor2
7985

    
7986
      new_alone_id = (self.instance.primary_node, self.new_node, None,
7987
                      p_minor, new_minor, o_secret)
7988
      new_net_id = (self.instance.primary_node, self.new_node, o_port,
7989
                    p_minor, new_minor, o_secret)
7990

    
7991
      iv_names[idx] = (dev, dev.children, new_net_id)
7992
      logging.debug("Allocated new_minor: %s, new_logical_id: %s", new_minor,
7993
                    new_net_id)
7994
      new_drbd = objects.Disk(dev_type=constants.LD_DRBD8,
7995
                              logical_id=new_alone_id,
7996
                              children=dev.children,
7997
                              size=dev.size)
7998
      try:
7999
        _CreateSingleBlockDev(self.lu, self.new_node, self.instance, new_drbd,
8000
                              _GetInstanceInfoText(self.instance), False)
8001
      except errors.GenericError:
8002
        self.cfg.ReleaseDRBDMinors(self.instance.name)
8003
        raise
8004

    
8005
    # We have new devices, shutdown the drbd on the old secondary
8006
    for idx, dev in enumerate(self.instance.disks):
8007
      self.lu.LogInfo("Shutting down drbd for disk/%d on old node" % idx)
8008
      self.cfg.SetDiskID(dev, self.target_node)
8009
      msg = self.rpc.call_blockdev_shutdown(self.target_node, dev).fail_msg
8010
      if msg:
8011
        self.lu.LogWarning("Failed to shutdown drbd for disk/%d on old"
8012
                           "node: %s" % (idx, msg),
8013
                           hint=("Please cleanup this device manually as"
8014
                                 " soon as possible"))
8015

    
8016
    self.lu.LogInfo("Detaching primary drbds from the network (=> standalone)")
8017
    result = self.rpc.call_drbd_disconnect_net([self.instance.primary_node],
8018
                                               self.node_secondary_ip,
8019
                                               self.instance.disks)\
8020
                                              [self.instance.primary_node]
8021

    
8022
    msg = result.fail_msg
8023
    if msg:
8024
      # detaches didn't succeed (unlikely)
8025
      self.cfg.ReleaseDRBDMinors(self.instance.name)
8026
      raise errors.OpExecError("Can't detach the disks from the network on"
8027
                               " old node: %s" % (msg,))
8028

    
8029
    # if we managed to detach at least one, we update all the disks of
8030
    # the instance to point to the new secondary
8031
    self.lu.LogInfo("Updating instance configuration")
8032
    for dev, _, new_logical_id in iv_names.itervalues():
8033
      dev.logical_id = new_logical_id
8034
      self.cfg.SetDiskID(dev, self.instance.primary_node)
8035

    
8036
    self.cfg.Update(self.instance, feedback_fn)
8037

    
8038
    # and now perform the drbd attach
8039
    self.lu.LogInfo("Attaching primary drbds to new secondary"
8040
                    " (standalone => connected)")
8041
    result = self.rpc.call_drbd_attach_net([self.instance.primary_node,
8042
                                            self.new_node],
8043
                                           self.node_secondary_ip,
8044
                                           self.instance.disks,
8045
                                           self.instance.name,
8046
                                           False)
8047
    for to_node, to_result in result.items():
8048
      msg = to_result.fail_msg
8049
      if msg:
8050
        self.lu.LogWarning("Can't attach drbd disks on node %s: %s",
8051
                           to_node, msg,
8052
                           hint=("please do a gnt-instance info to see the"
8053
                                 " status of disks"))
8054
    cstep = 5
8055
    if self.early_release:
8056
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8057
      cstep += 1
8058
      self._RemoveOldStorage(self.target_node, iv_names)
8059
      # WARNING: we release all node locks here, do not do other RPCs
8060
      # than WaitForSync to the primary node
8061
      self._ReleaseNodeLock([self.instance.primary_node,
8062
                             self.target_node,
8063
                             self.new_node])
8064

    
8065
    # Wait for sync
8066
    # This can fail as the old devices are degraded and _WaitForSync
8067
    # does a combined result over all disks, so we don't check its return value
8068
    self.lu.LogStep(cstep, steps_total, "Sync devices")
8069
    cstep += 1
8070
    _WaitForSync(self.lu, self.instance)
8071

    
8072
    # Check all devices manually
8073
    self._CheckDevices(self.instance.primary_node, iv_names)
8074

    
8075
    # Step: remove old storage
8076
    if not self.early_release:
8077
      self.lu.LogStep(cstep, steps_total, "Removing old storage")
8078
      self._RemoveOldStorage(self.target_node, iv_names)
8079

    
8080

    
8081
class LURepairNodeStorage(NoHooksLU):
8082
  """Repairs the volume group on a node.
8083

8084
  """
8085
  _OP_REQP = [("node_name", _TNonEmptyString)]
8086
  REQ_BGL = False
8087

    
8088
  def CheckArguments(self):
8089
    self.op.node_name = _ExpandNodeName(self.cfg, self.op.node_name)
8090

    
8091
    _CheckStorageType(self.op.storage_type)
8092

    
8093
    storage_type = self.op.storage_type
8094

    
8095
    if (constants.SO_FIX_CONSISTENCY not in
8096
        constants.VALID_STORAGE_OPERATIONS.get(storage_type, [])):
8097
      raise errors.OpPrereqError("Storage units of type '%s' can not be"
8098
                                 " repaired" % storage_type,
8099
                                 errors.ECODE_INVAL)
8100

    
8101
  def ExpandNames(self):
8102
    self.needed_locks = {
8103
      locking.LEVEL_NODE: [self.op.node_name],
8104
      }
8105

    
8106
  def _CheckFaultyDisks(self, instance, node_name):
8107
    """Ensure faulty disks abort the opcode or at least warn."""
8108
    try:
8109
      if _FindFaultyInstanceDisks(self.cfg, self.rpc, instance,
8110
                                  node_name, True):
8111
        raise errors.OpPrereqError("Instance '%s' has faulty disks on"
8112
                                   " node '%s'" % (instance.name, node_name),
8113
                                   errors.ECODE_STATE)
8114
    except errors.OpPrereqError, err:
8115
      if self.op.ignore_consistency:
8116
        self.proc.LogWarning(str(err.args[0]))
8117
      else:
8118
        raise
8119

    
8120
  def CheckPrereq(self):
8121
    """Check prerequisites.
8122

8123
    """
8124
    # Check whether any instance on this node has faulty disks
8125
    for inst in _GetNodeInstances(self.cfg, self.op.node_name):
8126
      if not inst.admin_up:
8127
        continue
8128
      check_nodes = set(inst.all_nodes)
8129
      check_nodes.discard(self.op.node_name)
8130
      for inst_node_name in check_nodes:
8131
        self._CheckFaultyDisks(inst, inst_node_name)
8132

    
8133
  def Exec(self, feedback_fn):
8134
    feedback_fn("Repairing storage unit '%s' on %s ..." %
8135
                (self.op.name, self.op.node_name))
8136

    
8137
    st_args = _GetStorageTypeArgs(self.cfg, self.op.storage_type)
8138
    result = self.rpc.call_storage_execute(self.op.node_name,
8139
                                           self.op.storage_type, st_args,
8140
                                           self.op.name,
8141
                                           constants.SO_FIX_CONSISTENCY)
8142
    result.Raise("Failed to repair storage unit '%s' on %s" %
8143
                 (self.op.name, self.op.node_name))
8144

    
8145

    
8146
class LUNodeEvacuationStrategy(NoHooksLU):
8147
  """Computes the node evacuation strategy.
8148

8149
  """
8150
  _OP_REQP = [("nodes", _TListOf(_TNonEmptyString))]
8151
  _OP_DEFS = [
8152
    ("remote_node", None),
8153
    ("iallocator", None),
8154
    ]
8155
  REQ_BGL = False
8156

    
8157
  def CheckArguments(self):
8158
    if self.op.remote_node is not None and self.op.iallocator is not None:
8159
      raise errors.OpPrereqError("Give either the iallocator or the new"
8160
                                 " secondary, not both", errors.ECODE_INVAL)
8161

    
8162
  def ExpandNames(self):
8163
    self.op.nodes = _GetWantedNodes(self, self.op.nodes)
8164
    self.needed_locks = locks = {}
8165
    if self.op.remote_node is None:
8166
      locks[locking.LEVEL_NODE] = locking.ALL_SET
8167
    else:
8168
      self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8169
      locks[locking.LEVEL_NODE] = self.op.nodes + [self.op.remote_node]
8170

    
8171
  def Exec(self, feedback_fn):
8172
    if self.op.remote_node is not None:
8173
      instances = []
8174
      for node in self.op.nodes:
8175
        instances.extend(_GetNodeSecondaryInstances(self.cfg, node))
8176
      result = []
8177
      for i in instances:
8178
        if i.primary_node == self.op.remote_node:
8179
          raise errors.OpPrereqError("Node %s is the primary node of"
8180
                                     " instance %s, cannot use it as"
8181
                                     " secondary" %
8182
                                     (self.op.remote_node, i.name),
8183
                                     errors.ECODE_INVAL)
8184
        result.append([i.name, self.op.remote_node])
8185
    else:
8186
      ial = IAllocator(self.cfg, self.rpc,
8187
                       mode=constants.IALLOCATOR_MODE_MEVAC,
8188
                       evac_nodes=self.op.nodes)
8189
      ial.Run(self.op.iallocator, validate=True)
8190
      if not ial.success:
8191
        raise errors.OpExecError("No valid evacuation solution: %s" % ial.info,
8192
                                 errors.ECODE_NORES)
8193
      result = ial.result
8194
    return result
8195

    
8196

    
8197
class LUGrowDisk(LogicalUnit):
8198
  """Grow a disk of an instance.
8199

8200
  """
8201
  HPATH = "disk-grow"
8202
  HTYPE = constants.HTYPE_INSTANCE
8203
  _OP_REQP = [
8204
    ("instance_name", _TNonEmptyString),
8205
    ("disk", _TInt),
8206
    ("amount", _TInt),
8207
    ("wait_for_sync", _TBool),
8208
    ]
8209
  REQ_BGL = False
8210

    
8211
  def ExpandNames(self):
8212
    self._ExpandAndLockInstance()
8213
    self.needed_locks[locking.LEVEL_NODE] = []
8214
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8215

    
8216
  def DeclareLocks(self, level):
8217
    if level == locking.LEVEL_NODE:
8218
      self._LockInstancesNodes()
8219

    
8220
  def BuildHooksEnv(self):
8221
    """Build hooks env.
8222

8223
    This runs on the master, the primary and all the secondaries.
8224

8225
    """
8226
    env = {
8227
      "DISK": self.op.disk,
8228
      "AMOUNT": self.op.amount,
8229
      }
8230
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
8231
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8232
    return env, nl, nl
8233

    
8234
  def CheckPrereq(self):
8235
    """Check prerequisites.
8236

8237
    This checks that the instance is in the cluster.
8238

8239
    """
8240
    instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8241
    assert instance is not None, \
8242
      "Cannot retrieve locked instance %s" % self.op.instance_name
8243
    nodenames = list(instance.all_nodes)
8244
    for node in nodenames:
8245
      _CheckNodeOnline(self, node)
8246

    
8247
    self.instance = instance
8248

    
8249
    if instance.disk_template not in constants.DTS_GROWABLE:
8250
      raise errors.OpPrereqError("Instance's disk layout does not support"
8251
                                 " growing.", errors.ECODE_INVAL)
8252

    
8253
    self.disk = instance.FindDisk(self.op.disk)
8254

    
8255
    if instance.disk_template != constants.DT_FILE:
8256
      # TODO: check the free disk space for file, when that feature will be
8257
      # supported
8258
      _CheckNodesFreeDisk(self, nodenames, self.op.amount)
8259

    
8260
  def Exec(self, feedback_fn):
8261
    """Execute disk grow.
8262

8263
    """
8264
    instance = self.instance
8265
    disk = self.disk
8266

    
8267
    disks_ok, _ = _AssembleInstanceDisks(self, self.instance, disks=[disk])
8268
    if not disks_ok:
8269
      raise errors.OpExecError("Cannot activate block device to grow")
8270

    
8271
    for node in instance.all_nodes:
8272
      self.cfg.SetDiskID(disk, node)
8273
      result = self.rpc.call_blockdev_grow(node, disk, self.op.amount)
8274
      result.Raise("Grow request failed to node %s" % node)
8275

    
8276
      # TODO: Rewrite code to work properly
8277
      # DRBD goes into sync mode for a short amount of time after executing the
8278
      # "resize" command. DRBD 8.x below version 8.0.13 contains a bug whereby
8279
      # calling "resize" in sync mode fails. Sleeping for a short amount of
8280
      # time is a work-around.
8281
      time.sleep(5)
8282

    
8283
    disk.RecordGrow(self.op.amount)
8284
    self.cfg.Update(instance, feedback_fn)
8285
    if self.op.wait_for_sync:
8286
      disk_abort = not _WaitForSync(self, instance, disks=[disk])
8287
      if disk_abort:
8288
        self.proc.LogWarning("Warning: disk sync-ing has not returned a good"
8289
                             " status.\nPlease check the instance.")
8290
      if not instance.admin_up:
8291
        _SafeShutdownInstanceDisks(self, instance, disks=[disk])
8292
    elif not instance.admin_up:
8293
      self.proc.LogWarning("Not shutting down the disk even if the instance is"
8294
                           " not supposed to be running because no wait for"
8295
                           " sync mode was requested.")
8296

    
8297

    
8298
class LUQueryInstanceData(NoHooksLU):
8299
  """Query runtime instance data.
8300

8301
  """
8302
  _OP_REQP = [
8303
    ("instances", _TListOf(_TNonEmptyString)),
8304
    ("static", _TBool),
8305
    ]
8306
  REQ_BGL = False
8307

    
8308
  def ExpandNames(self):
8309
    self.needed_locks = {}
8310
    self.share_locks = dict.fromkeys(locking.LEVELS, 1)
8311

    
8312
    if self.op.instances:
8313
      self.wanted_names = []
8314
      for name in self.op.instances:
8315
        full_name = _ExpandInstanceName(self.cfg, name)
8316
        self.wanted_names.append(full_name)
8317
      self.needed_locks[locking.LEVEL_INSTANCE] = self.wanted_names
8318
    else:
8319
      self.wanted_names = None
8320
      self.needed_locks[locking.LEVEL_INSTANCE] = locking.ALL_SET
8321

    
8322
    self.needed_locks[locking.LEVEL_NODE] = []
8323
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8324

    
8325
  def DeclareLocks(self, level):
8326
    if level == locking.LEVEL_NODE:
8327
      self._LockInstancesNodes()
8328

    
8329
  def CheckPrereq(self):
8330
    """Check prerequisites.
8331

8332
    This only checks the optional instance list against the existing names.
8333

8334
    """
8335
    if self.wanted_names is None:
8336
      self.wanted_names = self.acquired_locks[locking.LEVEL_INSTANCE]
8337

    
8338
    self.wanted_instances = [self.cfg.GetInstanceInfo(name) for name
8339
                             in self.wanted_names]
8340

    
8341
  def _ComputeBlockdevStatus(self, node, instance_name, dev):
8342
    """Returns the status of a block device
8343

8344
    """
8345
    if self.op.static or not node:
8346
      return None
8347

    
8348
    self.cfg.SetDiskID(dev, node)
8349

    
8350
    result = self.rpc.call_blockdev_find(node, dev)
8351
    if result.offline:
8352
      return None
8353

    
8354
    result.Raise("Can't compute disk status for %s" % instance_name)
8355

    
8356
    status = result.payload
8357
    if status is None:
8358
      return None
8359

    
8360
    return (status.dev_path, status.major, status.minor,
8361
            status.sync_percent, status.estimated_time,
8362
            status.is_degraded, status.ldisk_status)
8363

    
8364
  def _ComputeDiskStatus(self, instance, snode, dev):
8365
    """Compute block device status.
8366

8367
    """
8368
    if dev.dev_type in constants.LDS_DRBD:
8369
      # we change the snode then (otherwise we use the one passed in)
8370
      if dev.logical_id[0] == instance.primary_node:
8371
        snode = dev.logical_id[1]
8372
      else:
8373
        snode = dev.logical_id[0]
8374

    
8375
    dev_pstatus = self._ComputeBlockdevStatus(instance.primary_node,
8376
                                              instance.name, dev)
8377
    dev_sstatus = self._ComputeBlockdevStatus(snode, instance.name, dev)
8378

    
8379
    if dev.children:
8380
      dev_children = [self._ComputeDiskStatus(instance, snode, child)
8381
                      for child in dev.children]
8382
    else:
8383
      dev_children = []
8384

    
8385
    data = {
8386
      "iv_name": dev.iv_name,
8387
      "dev_type": dev.dev_type,
8388
      "logical_id": dev.logical_id,
8389
      "physical_id": dev.physical_id,
8390
      "pstatus": dev_pstatus,
8391
      "sstatus": dev_sstatus,
8392
      "children": dev_children,
8393
      "mode": dev.mode,
8394
      "size": dev.size,
8395
      }
8396

    
8397
    return data
8398

    
8399
  def Exec(self, feedback_fn):
8400
    """Gather and return data"""
8401
    result = {}
8402

    
8403
    cluster = self.cfg.GetClusterInfo()
8404

    
8405
    for instance in self.wanted_instances:
8406
      if not self.op.static:
8407
        remote_info = self.rpc.call_instance_info(instance.primary_node,
8408
                                                  instance.name,
8409
                                                  instance.hypervisor)
8410
        remote_info.Raise("Error checking node %s" % instance.primary_node)
8411
        remote_info = remote_info.payload
8412
        if remote_info and "state" in remote_info:
8413
          remote_state = "up"
8414
        else:
8415
          remote_state = "down"
8416
      else:
8417
        remote_state = None
8418
      if instance.admin_up:
8419
        config_state = "up"
8420
      else:
8421
        config_state = "down"
8422

    
8423
      disks = [self._ComputeDiskStatus(instance, None, device)
8424
               for device in instance.disks]
8425

    
8426
      idict = {
8427
        "name": instance.name,
8428
        "config_state": config_state,
8429
        "run_state": remote_state,
8430
        "pnode": instance.primary_node,
8431
        "snodes": instance.secondary_nodes,
8432
        "os": instance.os,
8433
        # this happens to be the same format used for hooks
8434
        "nics": _NICListToTuple(self, instance.nics),
8435
        "disk_template": instance.disk_template,
8436
        "disks": disks,
8437
        "hypervisor": instance.hypervisor,
8438
        "network_port": instance.network_port,
8439
        "hv_instance": instance.hvparams,
8440
        "hv_actual": cluster.FillHV(instance, skip_globals=True),
8441
        "be_instance": instance.beparams,
8442
        "be_actual": cluster.FillBE(instance),
8443
        "os_instance": instance.osparams,
8444
        "os_actual": cluster.SimpleFillOS(instance.os, instance.osparams),
8445
        "serial_no": instance.serial_no,
8446
        "mtime": instance.mtime,
8447
        "ctime": instance.ctime,
8448
        "uuid": instance.uuid,
8449
        }
8450

    
8451
      result[instance.name] = idict
8452

    
8453
    return result
8454

    
8455

    
8456
class LUSetInstanceParams(LogicalUnit):
8457
  """Modifies an instances's parameters.
8458

8459
  """
8460
  HPATH = "instance-modify"
8461
  HTYPE = constants.HTYPE_INSTANCE
8462
  _OP_REQP = [("instance_name", _TNonEmptyString)]
8463
  _OP_DEFS = [
8464
    ("nics", _EmptyList),
8465
    ("disks", _EmptyList),
8466
    ("beparams", _EmptyDict),
8467
    ("hvparams", _EmptyDict),
8468
    ("disk_template", None),
8469
    ("remote_node", None),
8470
    ("os_name", None),
8471
    ("force_variant", False),
8472
    ("osparams", None),
8473
    ("force", False),
8474
    ]
8475
  REQ_BGL = False
8476

    
8477
  def CheckArguments(self):
8478
    if not (self.op.nics or self.op.disks or self.op.disk_template or
8479
            self.op.hvparams or self.op.beparams or self.op.os_name):
8480
      raise errors.OpPrereqError("No changes submitted", errors.ECODE_INVAL)
8481

    
8482
    if self.op.hvparams:
8483
      _CheckGlobalHvParams(self.op.hvparams)
8484

    
8485
    # Disk validation
8486
    disk_addremove = 0
8487
    for disk_op, disk_dict in self.op.disks:
8488
      utils.ForceDictType(disk_dict, constants.IDISK_PARAMS_TYPES)
8489
      if disk_op == constants.DDM_REMOVE:
8490
        disk_addremove += 1
8491
        continue
8492
      elif disk_op == constants.DDM_ADD:
8493
        disk_addremove += 1
8494
      else:
8495
        if not isinstance(disk_op, int):
8496
          raise errors.OpPrereqError("Invalid disk index", errors.ECODE_INVAL)
8497
        if not isinstance(disk_dict, dict):
8498
          msg = "Invalid disk value: expected dict, got '%s'" % disk_dict
8499
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8500

    
8501
      if disk_op == constants.DDM_ADD:
8502
        mode = disk_dict.setdefault('mode', constants.DISK_RDWR)
8503
        if mode not in constants.DISK_ACCESS_SET:
8504
          raise errors.OpPrereqError("Invalid disk access mode '%s'" % mode,
8505
                                     errors.ECODE_INVAL)
8506
        size = disk_dict.get('size', None)
8507
        if size is None:
8508
          raise errors.OpPrereqError("Required disk parameter size missing",
8509
                                     errors.ECODE_INVAL)
8510
        try:
8511
          size = int(size)
8512
        except (TypeError, ValueError), err:
8513
          raise errors.OpPrereqError("Invalid disk size parameter: %s" %
8514
                                     str(err), errors.ECODE_INVAL)
8515
        disk_dict['size'] = size
8516
      else:
8517
        # modification of disk
8518
        if 'size' in disk_dict:
8519
          raise errors.OpPrereqError("Disk size change not possible, use"
8520
                                     " grow-disk", errors.ECODE_INVAL)
8521

    
8522
    if disk_addremove > 1:
8523
      raise errors.OpPrereqError("Only one disk add or remove operation"
8524
                                 " supported at a time", errors.ECODE_INVAL)
8525

    
8526
    if self.op.disks and self.op.disk_template is not None:
8527
      raise errors.OpPrereqError("Disk template conversion and other disk"
8528
                                 " changes not supported at the same time",
8529
                                 errors.ECODE_INVAL)
8530

    
8531
    if self.op.disk_template:
8532
      _CheckDiskTemplate(self.op.disk_template)
8533
      if (self.op.disk_template in constants.DTS_NET_MIRROR and
8534
          self.op.remote_node is None):
8535
        raise errors.OpPrereqError("Changing the disk template to a mirrored"
8536
                                   " one requires specifying a secondary node",
8537
                                   errors.ECODE_INVAL)
8538

    
8539
    # NIC validation
8540
    nic_addremove = 0
8541
    for nic_op, nic_dict in self.op.nics:
8542
      utils.ForceDictType(nic_dict, constants.INIC_PARAMS_TYPES)
8543
      if nic_op == constants.DDM_REMOVE:
8544
        nic_addremove += 1
8545
        continue
8546
      elif nic_op == constants.DDM_ADD:
8547
        nic_addremove += 1
8548
      else:
8549
        if not isinstance(nic_op, int):
8550
          raise errors.OpPrereqError("Invalid nic index", errors.ECODE_INVAL)
8551
        if not isinstance(nic_dict, dict):
8552
          msg = "Invalid nic value: expected dict, got '%s'" % nic_dict
8553
          raise errors.OpPrereqError(msg, errors.ECODE_INVAL)
8554

    
8555
      # nic_dict should be a dict
8556
      nic_ip = nic_dict.get('ip', None)
8557
      if nic_ip is not None:
8558
        if nic_ip.lower() == constants.VALUE_NONE:
8559
          nic_dict['ip'] = None
8560
        else:
8561
          if not utils.IsValidIP4(nic_ip):
8562
            raise errors.OpPrereqError("Invalid IP address '%s'" % nic_ip,
8563
                                       errors.ECODE_INVAL)
8564

    
8565
      nic_bridge = nic_dict.get('bridge', None)
8566
      nic_link = nic_dict.get('link', None)
8567
      if nic_bridge and nic_link:
8568
        raise errors.OpPrereqError("Cannot pass 'bridge' and 'link'"
8569
                                   " at the same time", errors.ECODE_INVAL)
8570
      elif nic_bridge and nic_bridge.lower() == constants.VALUE_NONE:
8571
        nic_dict['bridge'] = None
8572
      elif nic_link and nic_link.lower() == constants.VALUE_NONE:
8573
        nic_dict['link'] = None
8574

    
8575
      if nic_op == constants.DDM_ADD:
8576
        nic_mac = nic_dict.get('mac', None)
8577
        if nic_mac is None:
8578
          nic_dict['mac'] = constants.VALUE_AUTO
8579

    
8580
      if 'mac' in nic_dict:
8581
        nic_mac = nic_dict['mac']
8582
        if nic_mac not in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8583
          nic_mac = utils.NormalizeAndValidateMac(nic_mac)
8584

    
8585
        if nic_op != constants.DDM_ADD and nic_mac == constants.VALUE_AUTO:
8586
          raise errors.OpPrereqError("'auto' is not a valid MAC address when"
8587
                                     " modifying an existing nic",
8588
                                     errors.ECODE_INVAL)
8589

    
8590
    if nic_addremove > 1:
8591
      raise errors.OpPrereqError("Only one NIC add or remove operation"
8592
                                 " supported at a time", errors.ECODE_INVAL)
8593

    
8594
  def ExpandNames(self):
8595
    self._ExpandAndLockInstance()
8596
    self.needed_locks[locking.LEVEL_NODE] = []
8597
    self.recalculate_locks[locking.LEVEL_NODE] = constants.LOCKS_REPLACE
8598

    
8599
  def DeclareLocks(self, level):
8600
    if level == locking.LEVEL_NODE:
8601
      self._LockInstancesNodes()
8602
      if self.op.disk_template and self.op.remote_node:
8603
        self.op.remote_node = _ExpandNodeName(self.cfg, self.op.remote_node)
8604
        self.needed_locks[locking.LEVEL_NODE].append(self.op.remote_node)
8605

    
8606
  def BuildHooksEnv(self):
8607
    """Build hooks env.
8608

8609
    This runs on the master, primary and secondaries.
8610

8611
    """
8612
    args = dict()
8613
    if constants.BE_MEMORY in self.be_new:
8614
      args['memory'] = self.be_new[constants.BE_MEMORY]
8615
    if constants.BE_VCPUS in self.be_new:
8616
      args['vcpus'] = self.be_new[constants.BE_VCPUS]
8617
    # TODO: export disk changes. Note: _BuildInstanceHookEnv* don't export disk
8618
    # information at all.
8619
    if self.op.nics:
8620
      args['nics'] = []
8621
      nic_override = dict(self.op.nics)
8622
      for idx, nic in enumerate(self.instance.nics):
8623
        if idx in nic_override:
8624
          this_nic_override = nic_override[idx]
8625
        else:
8626
          this_nic_override = {}
8627
        if 'ip' in this_nic_override:
8628
          ip = this_nic_override['ip']
8629
        else:
8630
          ip = nic.ip
8631
        if 'mac' in this_nic_override:
8632
          mac = this_nic_override['mac']
8633
        else:
8634
          mac = nic.mac
8635
        if idx in self.nic_pnew:
8636
          nicparams = self.nic_pnew[idx]
8637
        else:
8638
          nicparams = self.cluster.SimpleFillNIC(nic.nicparams)
8639
        mode = nicparams[constants.NIC_MODE]
8640
        link = nicparams[constants.NIC_LINK]
8641
        args['nics'].append((ip, mac, mode, link))
8642
      if constants.DDM_ADD in nic_override:
8643
        ip = nic_override[constants.DDM_ADD].get('ip', None)
8644
        mac = nic_override[constants.DDM_ADD]['mac']
8645
        nicparams = self.nic_pnew[constants.DDM_ADD]
8646
        mode = nicparams[constants.NIC_MODE]
8647
        link = nicparams[constants.NIC_LINK]
8648
        args['nics'].append((ip, mac, mode, link))
8649
      elif constants.DDM_REMOVE in nic_override:
8650
        del args['nics'][-1]
8651

    
8652
    env = _BuildInstanceHookEnvByObject(self, self.instance, override=args)
8653
    if self.op.disk_template:
8654
      env["NEW_DISK_TEMPLATE"] = self.op.disk_template
8655
    nl = [self.cfg.GetMasterNode()] + list(self.instance.all_nodes)
8656
    return env, nl, nl
8657

    
8658
  def CheckPrereq(self):
8659
    """Check prerequisites.
8660

8661
    This only checks the instance list against the existing names.
8662

8663
    """
8664
    # checking the new params on the primary/secondary nodes
8665

    
8666
    instance = self.instance = self.cfg.GetInstanceInfo(self.op.instance_name)
8667
    cluster = self.cluster = self.cfg.GetClusterInfo()
8668
    assert self.instance is not None, \
8669
      "Cannot retrieve locked instance %s" % self.op.instance_name
8670
    pnode = instance.primary_node
8671
    nodelist = list(instance.all_nodes)
8672

    
8673
    # OS change
8674
    if self.op.os_name and not self.op.force:
8675
      _CheckNodeHasOS(self, instance.primary_node, self.op.os_name,
8676
                      self.op.force_variant)
8677
      instance_os = self.op.os_name
8678
    else:
8679
      instance_os = instance.os
8680

    
8681
    if self.op.disk_template:
8682
      if instance.disk_template == self.op.disk_template:
8683
        raise errors.OpPrereqError("Instance already has disk template %s" %
8684
                                   instance.disk_template, errors.ECODE_INVAL)
8685

    
8686
      if (instance.disk_template,
8687
          self.op.disk_template) not in self._DISK_CONVERSIONS:
8688
        raise errors.OpPrereqError("Unsupported disk template conversion from"
8689
                                   " %s to %s" % (instance.disk_template,
8690
                                                  self.op.disk_template),
8691
                                   errors.ECODE_INVAL)
8692
      _CheckInstanceDown(self, instance, "cannot change disk template")
8693
      if self.op.disk_template in constants.DTS_NET_MIRROR:
8694
        _CheckNodeOnline(self, self.op.remote_node)
8695
        _CheckNodeNotDrained(self, self.op.remote_node)
8696
        disks = [{"size": d.size} for d in instance.disks]
8697
        required = _ComputeDiskSize(self.op.disk_template, disks)
8698
        _CheckNodesFreeDisk(self, [self.op.remote_node], required)
8699

    
8700
    # hvparams processing
8701
    if self.op.hvparams:
8702
      hv_type = instance.hypervisor
8703
      i_hvdict = _GetUpdatedParams(instance.hvparams, self.op.hvparams)
8704
      utils.ForceDictType(i_hvdict, constants.HVS_PARAMETER_TYPES)
8705
      hv_new = cluster.SimpleFillHV(hv_type, instance.os, i_hvdict)
8706

    
8707
      # local check
8708
      hypervisor.GetHypervisor(hv_type).CheckParameterSyntax(hv_new)
8709
      _CheckHVParams(self, nodelist, instance.hypervisor, hv_new)
8710
      self.hv_new = hv_new # the new actual values
8711
      self.hv_inst = i_hvdict # the new dict (without defaults)
8712
    else:
8713
      self.hv_new = self.hv_inst = {}
8714

    
8715
    # beparams processing
8716
    if self.op.beparams:
8717
      i_bedict = _GetUpdatedParams(instance.beparams, self.op.beparams,
8718
                                   use_none=True)
8719
      utils.ForceDictType(i_bedict, constants.BES_PARAMETER_TYPES)
8720
      be_new = cluster.SimpleFillBE(i_bedict)
8721
      self.be_new = be_new # the new actual values
8722
      self.be_inst = i_bedict # the new dict (without defaults)
8723
    else:
8724
      self.be_new = self.be_inst = {}
8725

    
8726
    # osparams processing
8727
    if self.op.osparams:
8728
      i_osdict = _GetUpdatedParams(instance.osparams, self.op.osparams)
8729
      _CheckOSParams(self, True, nodelist, instance_os, i_osdict)
8730
      self.os_new = cluster.SimpleFillOS(instance_os, i_osdict)
8731
      self.os_inst = i_osdict # the new dict (without defaults)
8732
    else:
8733
      self.os_new = self.os_inst = {}
8734

    
8735
    self.warn = []
8736

    
8737
    if constants.BE_MEMORY in self.op.beparams and not self.op.force:
8738
      mem_check_list = [pnode]
8739
      if be_new[constants.BE_AUTO_BALANCE]:
8740
        # either we changed auto_balance to yes or it was from before
8741
        mem_check_list.extend(instance.secondary_nodes)
8742
      instance_info = self.rpc.call_instance_info(pnode, instance.name,
8743
                                                  instance.hypervisor)
8744
      nodeinfo = self.rpc.call_node_info(mem_check_list, self.cfg.GetVGName(),
8745
                                         instance.hypervisor)
8746
      pninfo = nodeinfo[pnode]
8747
      msg = pninfo.fail_msg
8748
      if msg:
8749
        # Assume the primary node is unreachable and go ahead
8750
        self.warn.append("Can't get info from primary node %s: %s" %
8751
                         (pnode,  msg))
8752
      elif not isinstance(pninfo.payload.get('memory_free', None), int):
8753
        self.warn.append("Node data from primary node %s doesn't contain"
8754
                         " free memory information" % pnode)
8755
      elif instance_info.fail_msg:
8756
        self.warn.append("Can't get instance runtime information: %s" %
8757
                        instance_info.fail_msg)
8758
      else:
8759
        if instance_info.payload:
8760
          current_mem = int(instance_info.payload['memory'])
8761
        else:
8762
          # Assume instance not running
8763
          # (there is a slight race condition here, but it's not very probable,
8764
          # and we have no other way to check)
8765
          current_mem = 0
8766
        miss_mem = (be_new[constants.BE_MEMORY] - current_mem -
8767
                    pninfo.payload['memory_free'])
8768
        if miss_mem > 0:
8769
          raise errors.OpPrereqError("This change will prevent the instance"
8770
                                     " from starting, due to %d MB of memory"
8771
                                     " missing on its primary node" % miss_mem,
8772
                                     errors.ECODE_NORES)
8773

    
8774
      if be_new[constants.BE_AUTO_BALANCE]:
8775
        for node, nres in nodeinfo.items():
8776
          if node not in instance.secondary_nodes:
8777
            continue
8778
          msg = nres.fail_msg
8779
          if msg:
8780
            self.warn.append("Can't get info from secondary node %s: %s" %
8781
                             (node, msg))
8782
          elif not isinstance(nres.payload.get('memory_free', None), int):
8783
            self.warn.append("Secondary node %s didn't return free"
8784
                             " memory information" % node)
8785
          elif be_new[constants.BE_MEMORY] > nres.payload['memory_free']:
8786
            self.warn.append("Not enough memory to failover instance to"
8787
                             " secondary node %s" % node)
8788

    
8789
    # NIC processing
8790
    self.nic_pnew = {}
8791
    self.nic_pinst = {}
8792
    for nic_op, nic_dict in self.op.nics:
8793
      if nic_op == constants.DDM_REMOVE:
8794
        if not instance.nics:
8795
          raise errors.OpPrereqError("Instance has no NICs, cannot remove",
8796
                                     errors.ECODE_INVAL)
8797
        continue
8798
      if nic_op != constants.DDM_ADD:
8799
        # an existing nic
8800
        if not instance.nics:
8801
          raise errors.OpPrereqError("Invalid NIC index %s, instance has"
8802
                                     " no NICs" % nic_op,
8803
                                     errors.ECODE_INVAL)
8804
        if nic_op < 0 or nic_op >= len(instance.nics):
8805
          raise errors.OpPrereqError("Invalid NIC index %s, valid values"
8806
                                     " are 0 to %d" %
8807
                                     (nic_op, len(instance.nics) - 1),
8808
                                     errors.ECODE_INVAL)
8809
        old_nic_params = instance.nics[nic_op].nicparams
8810
        old_nic_ip = instance.nics[nic_op].ip
8811
      else:
8812
        old_nic_params = {}
8813
        old_nic_ip = None
8814

    
8815
      update_params_dict = dict([(key, nic_dict[key])
8816
                                 for key in constants.NICS_PARAMETERS
8817
                                 if key in nic_dict])
8818

    
8819
      if 'bridge' in nic_dict:
8820
        update_params_dict[constants.NIC_LINK] = nic_dict['bridge']
8821

    
8822
      new_nic_params = _GetUpdatedParams(old_nic_params,
8823
                                         update_params_dict)
8824
      utils.ForceDictType(new_nic_params, constants.NICS_PARAMETER_TYPES)
8825
      new_filled_nic_params = cluster.SimpleFillNIC(new_nic_params)
8826
      objects.NIC.CheckParameterSyntax(new_filled_nic_params)
8827
      self.nic_pinst[nic_op] = new_nic_params
8828
      self.nic_pnew[nic_op] = new_filled_nic_params
8829
      new_nic_mode = new_filled_nic_params[constants.NIC_MODE]
8830

    
8831
      if new_nic_mode == constants.NIC_MODE_BRIDGED:
8832
        nic_bridge = new_filled_nic_params[constants.NIC_LINK]
8833
        msg = self.rpc.call_bridges_exist(pnode, [nic_bridge]).fail_msg
8834
        if msg:
8835
          msg = "Error checking bridges on node %s: %s" % (pnode, msg)
8836
          if self.op.force:
8837
            self.warn.append(msg)
8838
          else:
8839
            raise errors.OpPrereqError(msg, errors.ECODE_ENVIRON)
8840
      if new_nic_mode == constants.NIC_MODE_ROUTED:
8841
        if 'ip' in nic_dict:
8842
          nic_ip = nic_dict['ip']
8843
        else:
8844
          nic_ip = old_nic_ip
8845
        if nic_ip is None:
8846
          raise errors.OpPrereqError('Cannot set the nic ip to None'
8847
                                     ' on a routed nic', errors.ECODE_INVAL)
8848
      if 'mac' in nic_dict:
8849
        nic_mac = nic_dict['mac']
8850
        if nic_mac is None:
8851
          raise errors.OpPrereqError('Cannot set the nic mac to None',
8852
                                     errors.ECODE_INVAL)
8853
        elif nic_mac in (constants.VALUE_AUTO, constants.VALUE_GENERATE):
8854
          # otherwise generate the mac
8855
          nic_dict['mac'] = self.cfg.GenerateMAC(self.proc.GetECId())
8856
        else:
8857
          # or validate/reserve the current one
8858
          try:
8859
            self.cfg.ReserveMAC(nic_mac, self.proc.GetECId())
8860
          except errors.ReservationError:
8861
            raise errors.OpPrereqError("MAC address %s already in use"
8862
                                       " in cluster" % nic_mac,
8863
                                       errors.ECODE_NOTUNIQUE)
8864

    
8865
    # DISK processing
8866
    if self.op.disks and instance.disk_template == constants.DT_DISKLESS:
8867
      raise errors.OpPrereqError("Disk operations not supported for"
8868
                                 " diskless instances",
8869
                                 errors.ECODE_INVAL)
8870
    for disk_op, _ in self.op.disks:
8871
      if disk_op == constants.DDM_REMOVE:
8872
        if len(instance.disks) == 1:
8873
          raise errors.OpPrereqError("Cannot remove the last disk of"
8874
                                     " an instance", errors.ECODE_INVAL)
8875
        _CheckInstanceDown(self, instance, "cannot remove disks")
8876

    
8877
      if (disk_op == constants.DDM_ADD and
8878
          len(instance.nics) >= constants.MAX_DISKS):
8879
        raise errors.OpPrereqError("Instance has too many disks (%d), cannot"
8880
                                   " add more" % constants.MAX_DISKS,
8881
                                   errors.ECODE_STATE)
8882
      if disk_op not in (constants.DDM_ADD, constants.DDM_REMOVE):
8883
        # an existing disk
8884
        if disk_op < 0 or disk_op >= len(instance.disks):
8885
          raise errors.OpPrereqError("Invalid disk index %s, valid values"
8886
                                     " are 0 to %d" %
8887
                                     (disk_op, len(instance.disks)),
8888
                                     errors.ECODE_INVAL)
8889

    
8890
    return
8891

    
8892
  def _ConvertPlainToDrbd(self, feedback_fn):
8893
    """Converts an instance from plain to drbd.
8894

8895
    """
8896
    feedback_fn("Converting template to drbd")
8897
    instance = self.instance
8898
    pnode = instance.primary_node
8899
    snode = self.op.remote_node
8900

    
8901
    # create a fake disk info for _GenerateDiskTemplate
8902
    disk_info = [{"size": d.size, "mode": d.mode} for d in instance.disks]
8903
    new_disks = _GenerateDiskTemplate(self, self.op.disk_template,
8904
                                      instance.name, pnode, [snode],
8905
                                      disk_info, None, None, 0)
8906
    info = _GetInstanceInfoText(instance)
8907
    feedback_fn("Creating aditional volumes...")
8908
    # first, create the missing data and meta devices
8909
    for disk in new_disks:
8910
      # unfortunately this is... not too nice
8911
      _CreateSingleBlockDev(self, pnode, instance, disk.children[1],
8912
                            info, True)
8913
      for child in disk.children:
8914
        _CreateSingleBlockDev(self, snode, instance, child, info, True)
8915
    # at this stage, all new LVs have been created, we can rename the
8916
    # old ones
8917
    feedback_fn("Renaming original volumes...")
8918
    rename_list = [(o, n.children[0].logical_id)
8919
                   for (o, n) in zip(instance.disks, new_disks)]
8920
    result = self.rpc.call_blockdev_rename(pnode, rename_list)
8921
    result.Raise("Failed to rename original LVs")
8922

    
8923
    feedback_fn("Initializing DRBD devices...")
8924
    # all child devices are in place, we can now create the DRBD devices
8925
    for disk in new_disks:
8926
      for node in [pnode, snode]:
8927
        f_create = node == pnode
8928
        _CreateSingleBlockDev(self, node, instance, disk, info, f_create)
8929

    
8930
    # at this point, the instance has been modified
8931
    instance.disk_template = constants.DT_DRBD8
8932
    instance.disks = new_disks
8933
    self.cfg.Update(instance, feedback_fn)
8934

    
8935
    # disks are created, waiting for sync
8936
    disk_abort = not _WaitForSync(self, instance)
8937
    if disk_abort:
8938
      raise errors.OpExecError("There are some degraded disks for"
8939
                               " this instance, please cleanup manually")
8940

    
8941
  def _ConvertDrbdToPlain(self, feedback_fn):
8942
    """Converts an instance from drbd to plain.
8943

8944
    """
8945
    instance = self.instance
8946
    assert len(instance.secondary_nodes) == 1
8947
    pnode = instance.primary_node
8948
    snode = instance.secondary_nodes[0]
8949
    feedback_fn("Converting template to plain")
8950

    
8951
    old_disks = instance.disks
8952
    new_disks = [d.children[0] for d in old_disks]
8953

    
8954
    # copy over size and mode
8955
    for parent, child in zip(old_disks, new_disks):
8956
      child.size = parent.size
8957
      child.mode = parent.mode
8958

    
8959
    # update instance structure
8960
    instance.disks = new_disks
8961
    instance.disk_template = constants.DT_PLAIN
8962
    self.cfg.Update(instance, feedback_fn)
8963

    
8964
    feedback_fn("Removing volumes on the secondary node...")
8965
    for disk in old_disks:
8966
      self.cfg.SetDiskID(disk, snode)
8967
      msg = self.rpc.call_blockdev_remove(snode, disk).fail_msg
8968
      if msg:
8969
        self.LogWarning("Could not remove block device %s on node %s,"
8970
                        " continuing anyway: %s", disk.iv_name, snode, msg)
8971

    
8972
    feedback_fn("Removing unneeded volumes on the primary node...")
8973
    for idx, disk in enumerate(old_disks):
8974
      meta = disk.children[1]
8975
      self.cfg.SetDiskID(meta, pnode)
8976
      msg = self.rpc.call_blockdev_remove(pnode, meta).fail_msg
8977
      if msg:
8978
        self.LogWarning("Could not remove metadata for disk %d on node %s,"
8979
                        " continuing anyway: %s", idx, pnode, msg)
8980

    
8981

    
8982
  def Exec(self, feedback_fn):
8983
    """Modifies an instance.
8984

8985
    All parameters take effect only at the next restart of the instance.
8986

8987
    """
8988
    # Process here the warnings from CheckPrereq, as we don't have a
8989
    # feedback_fn there.
8990
    for warn in self.warn:
8991
      feedback_fn("WARNING: %s" % warn)
8992

    
8993
    result = []
8994
    instance = self.instance
8995
    # disk changes
8996
    for disk_op, disk_dict in self.op.disks:
8997
      if disk_op == constants.DDM_REMOVE:
8998
        # remove the last disk
8999
        device = instance.disks.pop()
9000
        device_idx = len(instance.disks)
9001
        for node, disk in device.ComputeNodeTree(instance.primary_node):
9002
          self.cfg.SetDiskID(disk, node)
9003
          msg = self.rpc.call_blockdev_remove(node, disk).fail_msg
9004
          if msg:
9005
            self.LogWarning("Could not remove disk/%d on node %s: %s,"
9006
                            " continuing anyway", device_idx, node, msg)
9007
        result.append(("disk/%d" % device_idx, "remove"))
9008
      elif disk_op == constants.DDM_ADD:
9009
        # add a new disk
9010
        if instance.disk_template == constants.DT_FILE:
9011
          file_driver, file_path = instance.disks[0].logical_id
9012
          file_path = os.path.dirname(file_path)
9013
        else:
9014
          file_driver = file_path = None
9015
        disk_idx_base = len(instance.disks)
9016
        new_disk = _GenerateDiskTemplate(self,
9017
                                         instance.disk_template,
9018
                                         instance.name, instance.primary_node,
9019
                                         instance.secondary_nodes,
9020
                                         [disk_dict],
9021
                                         file_path,
9022
                                         file_driver,
9023
                                         disk_idx_base)[0]
9024
        instance.disks.append(new_disk)
9025
        info = _GetInstanceInfoText(instance)
9026

    
9027
        logging.info("Creating volume %s for instance %s",
9028
                     new_disk.iv_name, instance.name)
9029
        # Note: this needs to be kept in sync with _CreateDisks
9030
        #HARDCODE
9031
        for node in instance.all_nodes:
9032
          f_create = node == instance.primary_node
9033
          try:
9034
            _CreateBlockDev(self, node, instance, new_disk,
9035
                            f_create, info, f_create)
9036
          except errors.OpExecError, err:
9037
            self.LogWarning("Failed to create volume %s (%s) on"
9038
                            " node %s: %s",
9039
                            new_disk.iv_name, new_disk, node, err)
9040
        result.append(("disk/%d" % disk_idx_base, "add:size=%s,mode=%s" %
9041
                       (new_disk.size, new_disk.mode)))
9042
      else:
9043
        # change a given disk
9044
        instance.disks[disk_op].mode = disk_dict['mode']
9045
        result.append(("disk.mode/%d" % disk_op, disk_dict['mode']))
9046

    
9047
    if self.op.disk_template:
9048
      r_shut = _ShutdownInstanceDisks(self, instance)
9049
      if not r_shut:
9050
        raise errors.OpExecError("Cannot shutdow instance disks, unable to"
9051
                                 " proceed with disk template conversion")
9052
      mode = (instance.disk_template, self.op.disk_template)
9053
      try:
9054
        self._DISK_CONVERSIONS[mode](self, feedback_fn)
9055
      except:
9056
        self.cfg.ReleaseDRBDMinors(instance.name)
9057
        raise
9058
      result.append(("disk_template", self.op.disk_template))
9059

    
9060
    # NIC changes
9061
    for nic_op, nic_dict in self.op.nics:
9062
      if nic_op == constants.DDM_REMOVE:
9063
        # remove the last nic
9064
        del instance.nics[-1]
9065
        result.append(("nic.%d" % len(instance.nics), "remove"))
9066
      elif nic_op == constants.DDM_ADD:
9067
        # mac and bridge should be set, by now
9068
        mac = nic_dict['mac']
9069
        ip = nic_dict.get('ip', None)
9070
        nicparams = self.nic_pinst[constants.DDM_ADD]
9071
        new_nic = objects.NIC(mac=mac, ip=ip, nicparams=nicparams)
9072
        instance.nics.append(new_nic)
9073
        result.append(("nic.%d" % (len(instance.nics) - 1),
9074
                       "add:mac=%s,ip=%s,mode=%s,link=%s" %
9075
                       (new_nic.mac, new_nic.ip,
9076
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_MODE],
9077
                        self.nic_pnew[constants.DDM_ADD][constants.NIC_LINK]
9078
                       )))
9079
      else:
9080
        for key in 'mac', 'ip':
9081
          if key in nic_dict:
9082
            setattr(instance.nics[nic_op], key, nic_dict[key])
9083
        if nic_op in self.nic_pinst:
9084
          instance.nics[nic_op].nicparams = self.nic_pinst[nic_op]
9085
        for key, val in nic_dict.iteritems():
9086
          result.append(("nic.%s/%d" % (key, nic_op), val))
9087

    
9088
    # hvparams changes
9089
    if self.op.hvparams:
9090
      instance.hvparams = self.hv_inst
9091
      for key, val in self.op.hvparams.iteritems():
9092
        result.append(("hv/%s" % key, val))
9093

    
9094
    # beparams changes
9095
    if self.op.beparams:
9096
      instance.beparams = self.be_inst
9097
      for key, val in self.op.beparams.iteritems():
9098
        result.append(("be/%s" % key, val))
9099

    
9100
    # OS change
9101
    if self.op.os_name:
9102
      instance.os = self.op.os_name
9103

    
9104
    # osparams changes
9105
    if self.op.osparams:
9106
      instance.osparams = self.os_inst
9107
      for key, val in self.op.osparams.iteritems():
9108
        result.append(("os/%s" % key, val))
9109

    
9110
    self.cfg.Update(instance, feedback_fn)
9111

    
9112
    return result
9113

    
9114
  _DISK_CONVERSIONS = {
9115
    (constants.DT_PLAIN, constants.DT_DRBD8): _ConvertPlainToDrbd,
9116
    (constants.DT_DRBD8, constants.DT_PLAIN): _ConvertDrbdToPlain,
9117
    }
9118

    
9119

    
9120
class LUQueryExports(NoHooksLU):
9121
  """Query the exports list
9122

9123
  """
9124
  _OP_REQP = [("nodes", _TListOf(_TNonEmptyString))]
9125
  REQ_BGL = False
9126

    
9127
  def ExpandNames(self):
9128
    self.needed_locks = {}
9129
    self.share_locks[locking.LEVEL_NODE] = 1
9130
    if not self.op.nodes:
9131
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9132
    else:
9133
      self.needed_locks[locking.LEVEL_NODE] = \
9134
        _GetWantedNodes(self, self.op.nodes)
9135

    
9136
  def Exec(self, feedback_fn):
9137
    """Compute the list of all the exported system images.
9138

9139
    @rtype: dict
9140
    @return: a dictionary with the structure node->(export-list)
9141
        where export-list is a list of the instances exported on
9142
        that node.
9143

9144
    """
9145
    self.nodes = self.acquired_locks[locking.LEVEL_NODE]
9146
    rpcresult = self.rpc.call_export_list(self.nodes)
9147
    result = {}
9148
    for node in rpcresult:
9149
      if rpcresult[node].fail_msg:
9150
        result[node] = False
9151
      else:
9152
        result[node] = rpcresult[node].payload
9153

    
9154
    return result
9155

    
9156

    
9157
class LUPrepareExport(NoHooksLU):
9158
  """Prepares an instance for an export and returns useful information.
9159

9160
  """
9161
  _OP_REQP = [
9162
    ("instance_name", _TNonEmptyString),
9163
    ("mode", _TElemOf(constants.EXPORT_MODES)),
9164
    ]
9165
  REQ_BGL = False
9166

    
9167
  def ExpandNames(self):
9168
    self._ExpandAndLockInstance()
9169

    
9170
  def CheckPrereq(self):
9171
    """Check prerequisites.
9172

9173
    """
9174
    instance_name = self.op.instance_name
9175

    
9176
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9177
    assert self.instance is not None, \
9178
          "Cannot retrieve locked instance %s" % self.op.instance_name
9179
    _CheckNodeOnline(self, self.instance.primary_node)
9180

    
9181
    self._cds = _GetClusterDomainSecret()
9182

    
9183
  def Exec(self, feedback_fn):
9184
    """Prepares an instance for an export.
9185

9186
    """
9187
    instance = self.instance
9188

    
9189
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9190
      salt = utils.GenerateSecret(8)
9191

    
9192
      feedback_fn("Generating X509 certificate on %s" % instance.primary_node)
9193
      result = self.rpc.call_x509_cert_create(instance.primary_node,
9194
                                              constants.RIE_CERT_VALIDITY)
9195
      result.Raise("Can't create X509 key and certificate on %s" % result.node)
9196

    
9197
      (name, cert_pem) = result.payload
9198

    
9199
      cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM,
9200
                                             cert_pem)
9201

    
9202
      return {
9203
        "handshake": masterd.instance.ComputeRemoteExportHandshake(self._cds),
9204
        "x509_key_name": (name, utils.Sha1Hmac(self._cds, name, salt=salt),
9205
                          salt),
9206
        "x509_ca": utils.SignX509Certificate(cert, self._cds, salt),
9207
        }
9208

    
9209
    return None
9210

    
9211

    
9212
class LUExportInstance(LogicalUnit):
9213
  """Export an instance to an image in the cluster.
9214

9215
  """
9216
  HPATH = "instance-export"
9217
  HTYPE = constants.HTYPE_INSTANCE
9218
  _OP_REQP = [
9219
    ("instance_name", _TNonEmptyString),
9220
    ("target_node", _TNonEmptyString),
9221
    ("shutdown", _TBool),
9222
    ("mode", _TElemOf(constants.EXPORT_MODES)),
9223
    ]
9224
  _OP_DEFS = [
9225
    ("shutdown_timeout", constants.DEFAULT_SHUTDOWN_TIMEOUT),
9226
    ("remove_instance", False),
9227
    ("ignore_remove_failures", False),
9228
    ("mode", constants.EXPORT_MODE_LOCAL),
9229
    ("x509_key_name", None),
9230
    ("destination_x509_ca", None),
9231
    ]
9232
  REQ_BGL = False
9233

    
9234
  def CheckArguments(self):
9235
    """Check the arguments.
9236

9237
    """
9238
    self.x509_key_name = self.op.x509_key_name
9239
    self.dest_x509_ca_pem = self.op.destination_x509_ca
9240

    
9241
    if self.op.remove_instance and not self.op.shutdown:
9242
      raise errors.OpPrereqError("Can not remove instance without shutting it"
9243
                                 " down before")
9244

    
9245
    if self.op.mode == constants.EXPORT_MODE_REMOTE:
9246
      if not self.x509_key_name:
9247
        raise errors.OpPrereqError("Missing X509 key name for encryption",
9248
                                   errors.ECODE_INVAL)
9249

    
9250
      if not self.dest_x509_ca_pem:
9251
        raise errors.OpPrereqError("Missing destination X509 CA",
9252
                                   errors.ECODE_INVAL)
9253

    
9254
  def ExpandNames(self):
9255
    self._ExpandAndLockInstance()
9256

    
9257
    # Lock all nodes for local exports
9258
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9259
      # FIXME: lock only instance primary and destination node
9260
      #
9261
      # Sad but true, for now we have do lock all nodes, as we don't know where
9262
      # the previous export might be, and in this LU we search for it and
9263
      # remove it from its current node. In the future we could fix this by:
9264
      #  - making a tasklet to search (share-lock all), then create the
9265
      #    new one, then one to remove, after
9266
      #  - removing the removal operation altogether
9267
      self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9268

    
9269
  def DeclareLocks(self, level):
9270
    """Last minute lock declaration."""
9271
    # All nodes are locked anyway, so nothing to do here.
9272

    
9273
  def BuildHooksEnv(self):
9274
    """Build hooks env.
9275

9276
    This will run on the master, primary node and target node.
9277

9278
    """
9279
    env = {
9280
      "EXPORT_MODE": self.op.mode,
9281
      "EXPORT_NODE": self.op.target_node,
9282
      "EXPORT_DO_SHUTDOWN": self.op.shutdown,
9283
      "SHUTDOWN_TIMEOUT": self.op.shutdown_timeout,
9284
      # TODO: Generic function for boolean env variables
9285
      "REMOVE_INSTANCE": str(bool(self.op.remove_instance)),
9286
      }
9287

    
9288
    env.update(_BuildInstanceHookEnvByObject(self, self.instance))
9289

    
9290
    nl = [self.cfg.GetMasterNode(), self.instance.primary_node]
9291

    
9292
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9293
      nl.append(self.op.target_node)
9294

    
9295
    return env, nl, nl
9296

    
9297
  def CheckPrereq(self):
9298
    """Check prerequisites.
9299

9300
    This checks that the instance and node names are valid.
9301

9302
    """
9303
    instance_name = self.op.instance_name
9304

    
9305
    self.instance = self.cfg.GetInstanceInfo(instance_name)
9306
    assert self.instance is not None, \
9307
          "Cannot retrieve locked instance %s" % self.op.instance_name
9308
    _CheckNodeOnline(self, self.instance.primary_node)
9309

    
9310
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9311
      self.op.target_node = _ExpandNodeName(self.cfg, self.op.target_node)
9312
      self.dst_node = self.cfg.GetNodeInfo(self.op.target_node)
9313
      assert self.dst_node is not None
9314

    
9315
      _CheckNodeOnline(self, self.dst_node.name)
9316
      _CheckNodeNotDrained(self, self.dst_node.name)
9317

    
9318
      self._cds = None
9319
      self.dest_disk_info = None
9320
      self.dest_x509_ca = None
9321

    
9322
    elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9323
      self.dst_node = None
9324

    
9325
      if len(self.op.target_node) != len(self.instance.disks):
9326
        raise errors.OpPrereqError(("Received destination information for %s"
9327
                                    " disks, but instance %s has %s disks") %
9328
                                   (len(self.op.target_node), instance_name,
9329
                                    len(self.instance.disks)),
9330
                                   errors.ECODE_INVAL)
9331

    
9332
      cds = _GetClusterDomainSecret()
9333

    
9334
      # Check X509 key name
9335
      try:
9336
        (key_name, hmac_digest, hmac_salt) = self.x509_key_name
9337
      except (TypeError, ValueError), err:
9338
        raise errors.OpPrereqError("Invalid data for X509 key name: %s" % err)
9339

    
9340
      if not utils.VerifySha1Hmac(cds, key_name, hmac_digest, salt=hmac_salt):
9341
        raise errors.OpPrereqError("HMAC for X509 key name is wrong",
9342
                                   errors.ECODE_INVAL)
9343

    
9344
      # Load and verify CA
9345
      try:
9346
        (cert, _) = utils.LoadSignedX509Certificate(self.dest_x509_ca_pem, cds)
9347
      except OpenSSL.crypto.Error, err:
9348
        raise errors.OpPrereqError("Unable to load destination X509 CA (%s)" %
9349
                                   (err, ), errors.ECODE_INVAL)
9350

    
9351
      (errcode, msg) = utils.VerifyX509Certificate(cert, None, None)
9352
      if errcode is not None:
9353
        raise errors.OpPrereqError("Invalid destination X509 CA (%s)" %
9354
                                   (msg, ), errors.ECODE_INVAL)
9355

    
9356
      self.dest_x509_ca = cert
9357

    
9358
      # Verify target information
9359
      disk_info = []
9360
      for idx, disk_data in enumerate(self.op.target_node):
9361
        try:
9362
          (host, port, magic) = \
9363
            masterd.instance.CheckRemoteExportDiskInfo(cds, idx, disk_data)
9364
        except errors.GenericError, err:
9365
          raise errors.OpPrereqError("Target info for disk %s: %s" %
9366
                                     (idx, err), errors.ECODE_INVAL)
9367

    
9368
        disk_info.append((host, port, magic))
9369

    
9370
      assert len(disk_info) == len(self.op.target_node)
9371
      self.dest_disk_info = disk_info
9372

    
9373
    else:
9374
      raise errors.ProgrammerError("Unhandled export mode %r" %
9375
                                   self.op.mode)
9376

    
9377
    # instance disk type verification
9378
    # TODO: Implement export support for file-based disks
9379
    for disk in self.instance.disks:
9380
      if disk.dev_type == constants.LD_FILE:
9381
        raise errors.OpPrereqError("Export not supported for instances with"
9382
                                   " file-based disks", errors.ECODE_INVAL)
9383

    
9384
  def _CleanupExports(self, feedback_fn):
9385
    """Removes exports of current instance from all other nodes.
9386

9387
    If an instance in a cluster with nodes A..D was exported to node C, its
9388
    exports will be removed from the nodes A, B and D.
9389

9390
    """
9391
    assert self.op.mode != constants.EXPORT_MODE_REMOTE
9392

    
9393
    nodelist = self.cfg.GetNodeList()
9394
    nodelist.remove(self.dst_node.name)
9395

    
9396
    # on one-node clusters nodelist will be empty after the removal
9397
    # if we proceed the backup would be removed because OpQueryExports
9398
    # substitutes an empty list with the full cluster node list.
9399
    iname = self.instance.name
9400
    if nodelist:
9401
      feedback_fn("Removing old exports for instance %s" % iname)
9402
      exportlist = self.rpc.call_export_list(nodelist)
9403
      for node in exportlist:
9404
        if exportlist[node].fail_msg:
9405
          continue
9406
        if iname in exportlist[node].payload:
9407
          msg = self.rpc.call_export_remove(node, iname).fail_msg
9408
          if msg:
9409
            self.LogWarning("Could not remove older export for instance %s"
9410
                            " on node %s: %s", iname, node, msg)
9411

    
9412
  def Exec(self, feedback_fn):
9413
    """Export an instance to an image in the cluster.
9414

9415
    """
9416
    assert self.op.mode in constants.EXPORT_MODES
9417

    
9418
    instance = self.instance
9419
    src_node = instance.primary_node
9420

    
9421
    if self.op.shutdown:
9422
      # shutdown the instance, but not the disks
9423
      feedback_fn("Shutting down instance %s" % instance.name)
9424
      result = self.rpc.call_instance_shutdown(src_node, instance,
9425
                                               self.op.shutdown_timeout)
9426
      # TODO: Maybe ignore failures if ignore_remove_failures is set
9427
      result.Raise("Could not shutdown instance %s on"
9428
                   " node %s" % (instance.name, src_node))
9429

    
9430
    # set the disks ID correctly since call_instance_start needs the
9431
    # correct drbd minor to create the symlinks
9432
    for disk in instance.disks:
9433
      self.cfg.SetDiskID(disk, src_node)
9434

    
9435
    activate_disks = (not instance.admin_up)
9436

    
9437
    if activate_disks:
9438
      # Activate the instance disks if we'exporting a stopped instance
9439
      feedback_fn("Activating disks for %s" % instance.name)
9440
      _StartInstanceDisks(self, instance, None)
9441

    
9442
    try:
9443
      helper = masterd.instance.ExportInstanceHelper(self, feedback_fn,
9444
                                                     instance)
9445

    
9446
      helper.CreateSnapshots()
9447
      try:
9448
        if (self.op.shutdown and instance.admin_up and
9449
            not self.op.remove_instance):
9450
          assert not activate_disks
9451
          feedback_fn("Starting instance %s" % instance.name)
9452
          result = self.rpc.call_instance_start(src_node, instance, None, None)
9453
          msg = result.fail_msg
9454
          if msg:
9455
            feedback_fn("Failed to start instance: %s" % msg)
9456
            _ShutdownInstanceDisks(self, instance)
9457
            raise errors.OpExecError("Could not start instance: %s" % msg)
9458

    
9459
        if self.op.mode == constants.EXPORT_MODE_LOCAL:
9460
          (fin_resu, dresults) = helper.LocalExport(self.dst_node)
9461
        elif self.op.mode == constants.EXPORT_MODE_REMOTE:
9462
          connect_timeout = constants.RIE_CONNECT_TIMEOUT
9463
          timeouts = masterd.instance.ImportExportTimeouts(connect_timeout)
9464

    
9465
          (key_name, _, _) = self.x509_key_name
9466

    
9467
          dest_ca_pem = \
9468
            OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM,
9469
                                            self.dest_x509_ca)
9470

    
9471
          (fin_resu, dresults) = helper.RemoteExport(self.dest_disk_info,
9472
                                                     key_name, dest_ca_pem,
9473
                                                     timeouts)
9474
      finally:
9475
        helper.Cleanup()
9476

    
9477
      # Check for backwards compatibility
9478
      assert len(dresults) == len(instance.disks)
9479
      assert compat.all(isinstance(i, bool) for i in dresults), \
9480
             "Not all results are boolean: %r" % dresults
9481

    
9482
    finally:
9483
      if activate_disks:
9484
        feedback_fn("Deactivating disks for %s" % instance.name)
9485
        _ShutdownInstanceDisks(self, instance)
9486

    
9487
    # Remove instance if requested
9488
    if self.op.remove_instance:
9489
      if not (compat.all(dresults) and fin_resu):
9490
        feedback_fn("Not removing instance %s as parts of the export failed" %
9491
                    instance.name)
9492
      else:
9493
        feedback_fn("Removing instance %s" % instance.name)
9494
        _RemoveInstance(self, feedback_fn, instance,
9495
                        self.op.ignore_remove_failures)
9496

    
9497
    if self.op.mode == constants.EXPORT_MODE_LOCAL:
9498
      self._CleanupExports(feedback_fn)
9499

    
9500
    return fin_resu, dresults
9501

    
9502

    
9503
class LURemoveExport(NoHooksLU):
9504
  """Remove exports related to the named instance.
9505

9506
  """
9507
  _OP_REQP = [("instance_name", _TNonEmptyString)]
9508
  REQ_BGL = False
9509

    
9510
  def ExpandNames(self):
9511
    self.needed_locks = {}
9512
    # We need all nodes to be locked in order for RemoveExport to work, but we
9513
    # don't need to lock the instance itself, as nothing will happen to it (and
9514
    # we can remove exports also for a removed instance)
9515
    self.needed_locks[locking.LEVEL_NODE] = locking.ALL_SET
9516

    
9517
  def Exec(self, feedback_fn):
9518
    """Remove any export.
9519

9520
    """
9521
    instance_name = self.cfg.ExpandInstanceName(self.op.instance_name)
9522
    # If the instance was not found we'll try with the name that was passed in.
9523
    # This will only work if it was an FQDN, though.
9524
    fqdn_warn = False
9525
    if not instance_name:
9526
      fqdn_warn = True
9527
      instance_name = self.op.instance_name
9528

    
9529
    locked_nodes = self.acquired_locks[locking.LEVEL_NODE]
9530
    exportlist = self.rpc.call_export_list(locked_nodes)
9531
    found = False
9532
    for node in exportlist:
9533
      msg = exportlist[node].fail_msg
9534
      if msg:
9535
        self.LogWarning("Failed to query node %s (continuing): %s", node, msg)
9536
        continue
9537
      if instance_name in exportlist[node].payload:
9538
        found = True
9539
        result = self.rpc.call_export_remove(node, instance_name)
9540
        msg = result.fail_msg
9541
        if msg:
9542
          logging.error("Could not remove export for instance %s"
9543
                        " on node %s: %s", instance_name, node, msg)
9544

    
9545
    if fqdn_warn and not found:
9546
      feedback_fn("Export not found. If trying to remove an export belonging"
9547
                  " to a deleted instance please use its Fully Qualified"
9548
                  " Domain Name.")
9549

    
9550

    
9551
class TagsLU(NoHooksLU): # pylint: disable-msg=W0223
9552
  """Generic tags LU.
9553

9554
  This is an abstract class which is the parent of all the other tags LUs.
9555

9556
  """
9557

    
9558
  def ExpandNames(self):
9559
    self.needed_locks = {}
9560
    if self.op.kind == constants.TAG_NODE:
9561
      self.op.name = _ExpandNodeName(self.cfg, self.op.name)
9562
      self.needed_locks[locking.LEVEL_NODE] = self.op.name
9563
    elif self.op.kind == constants.TAG_INSTANCE:
9564
      self.op.name = _ExpandInstanceName(self.cfg, self.op.name)
9565
      self.needed_locks[locking.LEVEL_INSTANCE] = self.op.name
9566

    
9567
  def CheckPrereq(self):
9568
    """Check prerequisites.
9569

9570
    """
9571
    if self.op.kind == constants.TAG_CLUSTER:
9572
      self.target = self.cfg.GetClusterInfo()
9573
    elif self.op.kind == constants.TAG_NODE:
9574
      self.target = self.cfg.GetNodeInfo(self.op.name)
9575
    elif self.op.kind == constants.TAG_INSTANCE:
9576
      self.target = self.cfg.GetInstanceInfo(self.op.name)
9577
    else:
9578
      raise errors.OpPrereqError("Wrong tag type requested (%s)" %
9579
                                 str(self.op.kind), errors.ECODE_INVAL)
9580

    
9581

    
9582
class LUGetTags(TagsLU):
9583
  """Returns the tags of a given object.
9584

9585
  """
9586
  _OP_REQP = [
9587
    ("kind", _TElemOf(constants.VALID_TAG_TYPES)),
9588
    ("name", _TNonEmptyString),
9589
    ]
9590
  REQ_BGL = False
9591

    
9592
  def Exec(self, feedback_fn):
9593
    """Returns the tag list.
9594

9595
    """
9596
    return list(self.target.GetTags())
9597

    
9598

    
9599
class LUSearchTags(NoHooksLU):
9600
  """Searches the tags for a given pattern.
9601

9602
  """
9603
  _OP_REQP = [("pattern", _TNonEmptyString)]
9604
  REQ_BGL = False
9605

    
9606
  def ExpandNames(self):
9607
    self.needed_locks = {}
9608

    
9609
  def CheckPrereq(self):
9610
    """Check prerequisites.
9611

9612
    This checks the pattern passed for validity by compiling it.
9613

9614
    """
9615
    try:
9616
      self.re = re.compile(self.op.pattern)
9617
    except re.error, err:
9618
      raise errors.OpPrereqError("Invalid search pattern '%s': %s" %
9619
                                 (self.op.pattern, err), errors.ECODE_INVAL)
9620

    
9621
  def Exec(self, feedback_fn):
9622
    """Returns the tag list.
9623

9624
    """
9625
    cfg = self.cfg
9626
    tgts = [("/cluster", cfg.GetClusterInfo())]
9627
    ilist = cfg.GetAllInstancesInfo().values()
9628
    tgts.extend([("/instances/%s" % i.name, i) for i in ilist])
9629
    nlist = cfg.GetAllNodesInfo().values()
9630
    tgts.extend([("/nodes/%s" % n.name, n) for n in nlist])
9631
    results = []
9632
    for path, target in tgts:
9633
      for tag in target.GetTags():
9634
        if self.re.search(tag):
9635
          results.append((path, tag))
9636
    return results
9637

    
9638

    
9639
class LUAddTags(TagsLU):
9640
  """Sets a tag on a given object.
9641

9642
  """
9643
  _OP_REQP = [
9644
    ("kind", _TElemOf(constants.VALID_TAG_TYPES)),
9645
    ("name", _TNonEmptyString),
9646
    ("tags", _TListOf(objects.TaggableObject.ValidateTag)),
9647
    ]
9648
  REQ_BGL = False
9649

    
9650
  def CheckPrereq(self):
9651
    """Check prerequisites.
9652

9653
    This checks the type and length of the tag name and value.
9654

9655
    """
9656
    TagsLU.CheckPrereq(self)
9657
    for tag in self.op.tags:
9658
      objects.TaggableObject.ValidateTag(tag)
9659

    
9660
  def Exec(self, feedback_fn):
9661
    """Sets the tag.
9662

9663
    """
9664
    try:
9665
      for tag in self.op.tags:
9666
        self.target.AddTag(tag)
9667
    except errors.TagError, err:
9668
      raise errors.OpExecError("Error while setting tag: %s" % str(err))
9669
    self.cfg.Update(self.target, feedback_fn)
9670

    
9671

    
9672
class LUDelTags(TagsLU):
9673
  """Delete a list of tags from a given object.
9674

9675
  """
9676
  _OP_REQP = [
9677
    ("kind", _TElemOf(constants.VALID_TAG_TYPES)),
9678
    ("name", _TNonEmptyString),
9679
    ("tags", _TListOf(objects.TaggableObject.ValidateTag)),
9680
    ]
9681
  REQ_BGL = False
9682

    
9683
  def CheckPrereq(self):
9684
    """Check prerequisites.
9685

9686
    This checks that we have the given tag.
9687

9688
    """
9689
    TagsLU.CheckPrereq(self)
9690
    for tag in self.op.tags:
9691
      objects.TaggableObject.ValidateTag(tag)
9692
    del_tags = frozenset(self.op.tags)
9693
    cur_tags = self.target.GetTags()
9694
    if not del_tags <= cur_tags:
9695
      diff_tags = del_tags - cur_tags
9696
      diff_names = ["'%s'" % tag for tag in diff_tags]
9697
      diff_names.sort()
9698
      raise errors.OpPrereqError("Tag(s) %s not found" %
9699
                                 (",".join(diff_names)), errors.ECODE_NOENT)
9700

    
9701
  def Exec(self, feedback_fn):
9702
    """Remove the tag from the object.
9703

9704
    """
9705
    for tag in self.op.tags:
9706
      self.target.RemoveTag(tag)
9707
    self.cfg.Update(self.target, feedback_fn)
9708

    
9709

    
9710
class LUTestDelay(NoHooksLU):
9711
  """Sleep for a specified amount of time.
9712

9713
  This LU sleeps on the master and/or nodes for a specified amount of
9714
  time.
9715

9716
  """
9717
  _OP_REQP = [
9718
    ("duration", _TFloat),
9719
    ("on_master", _TBool),
9720
    ("on_nodes", _TListOf(_TNonEmptyString)),
9721
    ("repeat", _TPositiveInt)
9722
    ]
9723
  _OP_DEFS = [
9724
    ("repeat", 0),
9725
    ]
9726
  REQ_BGL = False
9727

    
9728
  def ExpandNames(self):
9729
    """Expand names and set required locks.
9730

9731
    This expands the node list, if any.
9732

9733
    """
9734
    self.needed_locks = {}
9735
    if self.op.on_nodes:
9736
      # _GetWantedNodes can be used here, but is not always appropriate to use
9737
      # this way in ExpandNames. Check LogicalUnit.ExpandNames docstring for
9738
      # more information.
9739
      self.op.on_nodes = _GetWantedNodes(self, self.op.on_nodes)
9740
      self.needed_locks[locking.LEVEL_NODE] = self.op.on_nodes
9741

    
9742
  def _TestDelay(self):
9743
    """Do the actual sleep.
9744

9745
    """
9746
    if self.op.on_master:
9747
      if not utils.TestDelay(self.op.duration):
9748
        raise errors.OpExecError("Error during master delay test")
9749
    if self.op.on_nodes:
9750
      result = self.rpc.call_test_delay(self.op.on_nodes, self.op.duration)
9751
      for node, node_result in result.items():
9752
        node_result.Raise("Failure during rpc call to node %s" % node)
9753

    
9754
  def Exec(self, feedback_fn):
9755
    """Execute the test delay opcode, with the wanted repetitions.
9756

9757
    """
9758
    if self.op.repeat == 0:
9759
      self._TestDelay()
9760
    else:
9761
      top_value = self.op.repeat - 1
9762
      for i in range(self.op.repeat):
9763
        self.LogInfo("Test delay iteration %d/%d" % (i, top_value))
9764
        self._TestDelay()
9765

    
9766

    
9767
class IAllocator(object):
9768
  """IAllocator framework.
9769

9770
  An IAllocator instance has three sets of attributes:
9771
    - cfg that is needed to query the cluster
9772
    - input data (all members of the _KEYS class attribute are required)
9773
    - four buffer attributes (in|out_data|text), that represent the
9774
      input (to the external script) in text and data structure format,
9775
      and the output from it, again in two formats
9776
    - the result variables from the script (success, info, nodes) for
9777
      easy usage
9778

9779
  """
9780
  # pylint: disable-msg=R0902
9781
  # lots of instance attributes
9782
  _ALLO_KEYS = [
9783
    "name", "mem_size", "disks", "disk_template",
9784
    "os", "tags", "nics", "vcpus", "hypervisor",
9785
    ]
9786
  _RELO_KEYS = [
9787
    "name", "relocate_from",
9788
    ]
9789
  _EVAC_KEYS = [
9790
    "evac_nodes",
9791
    ]
9792

    
9793
  def __init__(self, cfg, rpc, mode, **kwargs):
9794
    self.cfg = cfg
9795
    self.rpc = rpc
9796
    # init buffer variables
9797
    self.in_text = self.out_text = self.in_data = self.out_data = None
9798
    # init all input fields so that pylint is happy
9799
    self.mode = mode
9800
    self.mem_size = self.disks = self.disk_template = None
9801
    self.os = self.tags = self.nics = self.vcpus = None
9802
    self.hypervisor = None
9803
    self.relocate_from = None
9804
    self.name = None
9805
    self.evac_nodes = None
9806
    # computed fields
9807
    self.required_nodes = None
9808
    # init result fields
9809
    self.success = self.info = self.result = None
9810
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9811
      keyset = self._ALLO_KEYS
9812
      fn = self._AddNewInstance
9813
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9814
      keyset = self._RELO_KEYS
9815
      fn = self._AddRelocateInstance
9816
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9817
      keyset = self._EVAC_KEYS
9818
      fn = self._AddEvacuateNodes
9819
    else:
9820
      raise errors.ProgrammerError("Unknown mode '%s' passed to the"
9821
                                   " IAllocator" % self.mode)
9822
    for key in kwargs:
9823
      if key not in keyset:
9824
        raise errors.ProgrammerError("Invalid input parameter '%s' to"
9825
                                     " IAllocator" % key)
9826
      setattr(self, key, kwargs[key])
9827

    
9828
    for key in keyset:
9829
      if key not in kwargs:
9830
        raise errors.ProgrammerError("Missing input parameter '%s' to"
9831
                                     " IAllocator" % key)
9832
    self._BuildInputData(fn)
9833

    
9834
  def _ComputeClusterData(self):
9835
    """Compute the generic allocator input data.
9836

9837
    This is the data that is independent of the actual operation.
9838

9839
    """
9840
    cfg = self.cfg
9841
    cluster_info = cfg.GetClusterInfo()
9842
    # cluster data
9843
    data = {
9844
      "version": constants.IALLOCATOR_VERSION,
9845
      "cluster_name": cfg.GetClusterName(),
9846
      "cluster_tags": list(cluster_info.GetTags()),
9847
      "enabled_hypervisors": list(cluster_info.enabled_hypervisors),
9848
      # we don't have job IDs
9849
      }
9850
    iinfo = cfg.GetAllInstancesInfo().values()
9851
    i_list = [(inst, cluster_info.FillBE(inst)) for inst in iinfo]
9852

    
9853
    # node data
9854
    node_results = {}
9855
    node_list = cfg.GetNodeList()
9856

    
9857
    if self.mode == constants.IALLOCATOR_MODE_ALLOC:
9858
      hypervisor_name = self.hypervisor
9859
    elif self.mode == constants.IALLOCATOR_MODE_RELOC:
9860
      hypervisor_name = cfg.GetInstanceInfo(self.name).hypervisor
9861
    elif self.mode == constants.IALLOCATOR_MODE_MEVAC:
9862
      hypervisor_name = cluster_info.enabled_hypervisors[0]
9863

    
9864
    node_data = self.rpc.call_node_info(node_list, cfg.GetVGName(),
9865
                                        hypervisor_name)
9866
    node_iinfo = \
9867
      self.rpc.call_all_instances_info(node_list,
9868
                                       cluster_info.enabled_hypervisors)
9869
    for nname, nresult in node_data.items():
9870
      # first fill in static (config-based) values
9871
      ninfo = cfg.GetNodeInfo(nname)
9872
      pnr = {
9873
        "tags": list(ninfo.GetTags()),
9874
        "primary_ip": ninfo.primary_ip,
9875
        "secondary_ip": ninfo.secondary_ip,
9876
        "offline": ninfo.offline,
9877
        "drained": ninfo.drained,
9878
        "master_candidate": ninfo.master_candidate,
9879
        }
9880

    
9881
      if not (ninfo.offline or ninfo.drained):
9882
        nresult.Raise("Can't get data for node %s" % nname)
9883
        node_iinfo[nname].Raise("Can't get node instance info from node %s" %
9884
                                nname)
9885
        remote_info = nresult.payload
9886

    
9887
        for attr in ['memory_total', 'memory_free', 'memory_dom0',
9888
                     'vg_size', 'vg_free', 'cpu_total']:
9889
          if attr not in remote_info:
9890
            raise errors.OpExecError("Node '%s' didn't return attribute"
9891
                                     " '%s'" % (nname, attr))
9892
          if not isinstance(remote_info[attr], int):
9893
            raise errors.OpExecError("Node '%s' returned invalid value"
9894
                                     " for '%s': %s" %
9895
                                     (nname, attr, remote_info[attr]))
9896
        # compute memory used by primary instances
9897
        i_p_mem = i_p_up_mem = 0
9898
        for iinfo, beinfo in i_list:
9899
          if iinfo.primary_node == nname:
9900
            i_p_mem += beinfo[constants.BE_MEMORY]
9901
            if iinfo.name not in node_iinfo[nname].payload:
9902
              i_used_mem = 0
9903
            else:
9904
              i_used_mem = int(node_iinfo[nname].payload[iinfo.name]['memory'])
9905
            i_mem_diff = beinfo[constants.BE_MEMORY] - i_used_mem
9906
            remote_info['memory_free'] -= max(0, i_mem_diff)
9907

    
9908
            if iinfo.admin_up:
9909
              i_p_up_mem += beinfo[constants.BE_MEMORY]
9910

    
9911
        # compute memory used by instances
9912
        pnr_dyn = {
9913
          "total_memory": remote_info['memory_total'],
9914
          "reserved_memory": remote_info['memory_dom0'],
9915
          "free_memory": remote_info['memory_free'],
9916
          "total_disk": remote_info['vg_size'],
9917
          "free_disk": remote_info['vg_free'],
9918
          "total_cpus": remote_info['cpu_total'],
9919
          "i_pri_memory": i_p_mem,
9920
          "i_pri_up_memory": i_p_up_mem,
9921
          }
9922
        pnr.update(pnr_dyn)
9923

    
9924
      node_results[nname] = pnr
9925
    data["nodes"] = node_results
9926

    
9927
    # instance data
9928
    instance_data = {}
9929
    for iinfo, beinfo in i_list:
9930
      nic_data = []
9931
      for nic in iinfo.nics:
9932
        filled_params = cluster_info.SimpleFillNIC(nic.nicparams)
9933
        nic_dict = {"mac": nic.mac,
9934
                    "ip": nic.ip,
9935
                    "mode": filled_params[constants.NIC_MODE],
9936
                    "link": filled_params[constants.NIC_LINK],
9937
                   }
9938
        if filled_params[constants.NIC_MODE] == constants.NIC_MODE_BRIDGED:
9939
          nic_dict["bridge"] = filled_params[constants.NIC_LINK]
9940
        nic_data.append(nic_dict)
9941
      pir = {
9942
        "tags": list(iinfo.GetTags()),
9943
        "admin_up": iinfo.admin_up,
9944
        "vcpus": beinfo[constants.BE_VCPUS],
9945
        "memory": beinfo[constants.BE_MEMORY],
9946
        "os": iinfo.os,
9947
        "nodes": [iinfo.primary_node] + list(iinfo.secondary_nodes),
9948
        "nics": nic_data,
9949
        "disks": [{"size": dsk.size, "mode": dsk.mode} for dsk in iinfo.disks],
9950
        "disk_template": iinfo.disk_template,
9951
        "hypervisor": iinfo.hypervisor,
9952
        }
9953
      pir["disk_space_total"] = _ComputeDiskSize(iinfo.disk_template,
9954
                                                 pir["disks"])
9955
      instance_data[iinfo.name] = pir
9956

    
9957
    data["instances"] = instance_data
9958

    
9959
    self.in_data = data
9960

    
9961
  def _AddNewInstance(self):
9962
    """Add new instance data to allocator structure.
9963

9964
    This in combination with _AllocatorGetClusterData will create the
9965
    correct structure needed as input for the allocator.
9966

9967
    The checks for the completeness of the opcode must have already been
9968
    done.
9969

9970
    """
9971
    disk_space = _ComputeDiskSize(self.disk_template, self.disks)
9972

    
9973
    if self.disk_template in constants.DTS_NET_MIRROR:
9974
      self.required_nodes = 2
9975
    else:
9976
      self.required_nodes = 1
9977
    request = {
9978
      "name": self.name,
9979
      "disk_template": self.disk_template,
9980
      "tags": self.tags,
9981
      "os": self.os,
9982
      "vcpus": self.vcpus,
9983
      "memory": self.mem_size,
9984
      "disks": self.disks,
9985
      "disk_space_total": disk_space,
9986
      "nics": self.nics,
9987
      "required_nodes": self.required_nodes,
9988
      }
9989
    return request
9990

    
9991
  def _AddRelocateInstance(self):
9992
    """Add relocate instance data to allocator structure.
9993

9994
    This in combination with _IAllocatorGetClusterData will create the
9995
    correct structure needed as input for the allocator.
9996

9997
    The checks for the completeness of the opcode must have already been
9998
    done.
9999

10000
    """
10001
    instance = self.cfg.GetInstanceInfo(self.name)
10002
    if instance is None:
10003
      raise errors.ProgrammerError("Unknown instance '%s' passed to"
10004
                                   " IAllocator" % self.name)
10005

    
10006
    if instance.disk_template not in constants.DTS_NET_MIRROR:
10007
      raise errors.OpPrereqError("Can't relocate non-mirrored instances",
10008
                                 errors.ECODE_INVAL)
10009

    
10010
    if len(instance.secondary_nodes) != 1:
10011
      raise errors.OpPrereqError("Instance has not exactly one secondary node",
10012
                                 errors.ECODE_STATE)
10013

    
10014
    self.required_nodes = 1
10015
    disk_sizes = [{'size': disk.size} for disk in instance.disks]
10016
    disk_space = _ComputeDiskSize(instance.disk_template, disk_sizes)
10017

    
10018
    request = {
10019
      "name": self.name,
10020
      "disk_space_total": disk_space,
10021
      "required_nodes": self.required_nodes,
10022
      "relocate_from": self.relocate_from,
10023
      }
10024
    return request
10025

    
10026
  def _AddEvacuateNodes(self):
10027
    """Add evacuate nodes data to allocator structure.
10028

10029
    """
10030
    request = {
10031
      "evac_nodes": self.evac_nodes
10032
      }
10033
    return request
10034

    
10035
  def _BuildInputData(self, fn):
10036
    """Build input data structures.
10037

10038
    """
10039
    self._ComputeClusterData()
10040

    
10041
    request = fn()
10042
    request["type"] = self.mode
10043
    self.in_data["request"] = request
10044

    
10045
    self.in_text = serializer.Dump(self.in_data)
10046

    
10047
  def Run(self, name, validate=True, call_fn=None):
10048
    """Run an instance allocator and return the results.
10049

10050
    """
10051
    if call_fn is None:
10052
      call_fn = self.rpc.call_iallocator_runner
10053

    
10054
    result = call_fn(self.cfg.GetMasterNode(), name, self.in_text)
10055
    result.Raise("Failure while running the iallocator script")
10056

    
10057
    self.out_text = result.payload
10058
    if validate:
10059
      self._ValidateResult()
10060

    
10061
  def _ValidateResult(self):
10062
    """Process the allocator results.
10063

10064
    This will process and if successful save the result in
10065
    self.out_data and the other parameters.
10066

10067
    """
10068
    try:
10069
      rdict = serializer.Load(self.out_text)
10070
    except Exception, err:
10071
      raise errors.OpExecError("Can't parse iallocator results: %s" % str(err))
10072

    
10073
    if not isinstance(rdict, dict):
10074
      raise errors.OpExecError("Can't parse iallocator results: not a dict")
10075

    
10076
    # TODO: remove backwards compatiblity in later versions
10077
    if "nodes" in rdict and "result" not in rdict:
10078
      rdict["result"] = rdict["nodes"]
10079
      del rdict["nodes"]
10080

    
10081
    for key in "success", "info", "result":
10082
      if key not in rdict:
10083
        raise errors.OpExecError("Can't parse iallocator results:"
10084
                                 " missing key '%s'" % key)
10085
      setattr(self, key, rdict[key])
10086

    
10087
    if not isinstance(rdict["result"], list):
10088
      raise errors.OpExecError("Can't parse iallocator results: 'result' key"
10089
                               " is not a list")
10090
    self.out_data = rdict
10091

    
10092

    
10093
class LUTestAllocator(NoHooksLU):
10094
  """Run allocator tests.
10095

10096
  This LU runs the allocator tests
10097

10098
  """
10099
  _OP_REQP = [
10100
    ("direction", _TElemOf(constants.VALID_IALLOCATOR_DIRECTIONS)),
10101
    ("mode", _TElemOf(constants.VALID_IALLOCATOR_MODES)),
10102
    ("name", _TNonEmptyString),
10103
    ("nics", _TOr(_TNone, _TListOf(
10104
      _TDictOf(_TElemOf(["mac", "ip", "bridge"]),
10105
               _TOr(_TNone, _TNonEmptyString))))),
10106
    ("disks", _TOr(_TNone, _TList)),
10107
    ]
10108
  _OP_DEFS = [
10109
    ("hypervisor", None),
10110
    ("allocator", None),
10111
    ("nics", None),
10112
    ("disks", None),
10113
    ]
10114

    
10115
  def CheckPrereq(self):
10116
    """Check prerequisites.
10117

10118
    This checks the opcode parameters depending on the director and mode test.
10119

10120
    """
10121
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10122
      for attr in ["mem_size", "disks", "disk_template",
10123
                   "os", "tags", "nics", "vcpus"]:
10124
        if not hasattr(self.op, attr):
10125
          raise errors.OpPrereqError("Missing attribute '%s' on opcode input" %
10126
                                     attr, errors.ECODE_INVAL)
10127
      iname = self.cfg.ExpandInstanceName(self.op.name)
10128
      if iname is not None:
10129
        raise errors.OpPrereqError("Instance '%s' already in the cluster" %
10130
                                   iname, errors.ECODE_EXISTS)
10131
      if not isinstance(self.op.nics, list):
10132
        raise errors.OpPrereqError("Invalid parameter 'nics'",
10133
                                   errors.ECODE_INVAL)
10134
      if not isinstance(self.op.disks, list):
10135
        raise errors.OpPrereqError("Invalid parameter 'disks'",
10136
                                   errors.ECODE_INVAL)
10137
      for row in self.op.disks:
10138
        if (not isinstance(row, dict) or
10139
            "size" not in row or
10140
            not isinstance(row["size"], int) or
10141
            "mode" not in row or
10142
            row["mode"] not in ['r', 'w']):
10143
          raise errors.OpPrereqError("Invalid contents of the 'disks'"
10144
                                     " parameter", errors.ECODE_INVAL)
10145
      if self.op.hypervisor is None:
10146
        self.op.hypervisor = self.cfg.GetHypervisorType()
10147
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10148
      fname = _ExpandInstanceName(self.cfg, self.op.name)
10149
      self.op.name = fname
10150
      self.relocate_from = self.cfg.GetInstanceInfo(fname).secondary_nodes
10151
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10152
      if not hasattr(self.op, "evac_nodes"):
10153
        raise errors.OpPrereqError("Missing attribute 'evac_nodes' on"
10154
                                   " opcode input", errors.ECODE_INVAL)
10155
    else:
10156
      raise errors.OpPrereqError("Invalid test allocator mode '%s'" %
10157
                                 self.op.mode, errors.ECODE_INVAL)
10158

    
10159
    if self.op.direction == constants.IALLOCATOR_DIR_OUT:
10160
      if self.op.allocator is None:
10161
        raise errors.OpPrereqError("Missing allocator name",
10162
                                   errors.ECODE_INVAL)
10163
    elif self.op.direction != constants.IALLOCATOR_DIR_IN:
10164
      raise errors.OpPrereqError("Wrong allocator test '%s'" %
10165
                                 self.op.direction, errors.ECODE_INVAL)
10166

    
10167
  def Exec(self, feedback_fn):
10168
    """Run the allocator test.
10169

10170
    """
10171
    if self.op.mode == constants.IALLOCATOR_MODE_ALLOC:
10172
      ial = IAllocator(self.cfg, self.rpc,
10173
                       mode=self.op.mode,
10174
                       name=self.op.name,
10175
                       mem_size=self.op.mem_size,
10176
                       disks=self.op.disks,
10177
                       disk_template=self.op.disk_template,
10178
                       os=self.op.os,
10179
                       tags=self.op.tags,
10180
                       nics=self.op.nics,
10181
                       vcpus=self.op.vcpus,
10182
                       hypervisor=self.op.hypervisor,
10183
                       )
10184
    elif self.op.mode == constants.IALLOCATOR_MODE_RELOC:
10185
      ial = IAllocator(self.cfg, self.rpc,
10186
                       mode=self.op.mode,
10187
                       name=self.op.name,
10188
                       relocate_from=list(self.relocate_from),
10189
                       )
10190
    elif self.op.mode == constants.IALLOCATOR_MODE_MEVAC:
10191
      ial = IAllocator(self.cfg, self.rpc,
10192
                       mode=self.op.mode,
10193
                       evac_nodes=self.op.evac_nodes)
10194
    else:
10195
      raise errors.ProgrammerError("Uncatched mode %s in"
10196
                                   " LUTestAllocator.Exec", self.op.mode)
10197

    
10198
    if self.op.direction == constants.IALLOCATOR_DIR_IN:
10199
      result = ial.in_text
10200
    else:
10201
      ial.Run(self.op.allocator, validate=False)
10202
      result = ial.out_text
10203
    return result